Class: MarkdownExec::HashDelegatorParent

Inherits:
Object
  • Object
show all
Extended by:
HashDelegatorSelf
Includes:
CompactionHelpers
Defined in:
lib/hash_delegator.rb

Direct Known Subclasses

HashDelegator

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from HashDelegatorSelf

apply_color_from_hash, block_find, code_merge, count_matches_in_lines, create_directory_for_file, create_file_and_write_string_with_permissions, default_block_title_from_body, delete_consecutive_blank_lines!, error_handler, format_execution_streams, indent_all_lines, initialize_fcb_names, join_code_lines, merge_lists, next_link_state, parse_yaml_data_from_body, read_required_blocks_from_temp_file, remove_file_without_standard_errors, safeval, set_file_permissions, tty_prompt_without_disabled_symbol, update_menu_attrib_yield_selected, write_execution_output_to_file, yield_line_if_selected

Methods included from CompactionHelpers

#compact_and_convert_array_to_hash, #compact_and_index_hash, #compact_hash

Constructor Details

#initialize(delegate_object = {}) ⇒ HashDelegatorParent

Returns a new instance of HashDelegatorParent.



407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# File 'lib/hash_delegator.rb', line 407

def initialize(delegate_object = {})
  @delegate_object = delegate_object
  @prompt = HashDelegator.tty_prompt_without_disabled_symbol

  @most_recent_loaded_filename = nil
  @pass_args = []
  @run_state = OpenStruct.new(
    link_history: []
  )
  @link_history = LinkHistory.new
  @fout = FOut.new(@delegate_object) ### slice only relevant keys

  @process_mutex = Mutex.new
  @process_cv = ConditionVariable.new
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object

If a method is missing, treat it as a key for the @delegate_object.



1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
# File 'lib/hash_delegator.rb', line 1448

def method_missing(method_name, *args, &block)
  if @delegate_object.respond_to?(method_name)
    @delegate_object.send(method_name, *args, &block)
  elsif method_name.to_s.end_with?('=') && args.size == 1
    @delegate_object[method_name.to_s.chop.to_sym] = args.first
  else
    @delegate_object[method_name]
    # super
  end
end

Instance Attribute Details

#most_recent_loaded_filenameObject

Returns the value of attribute most_recent_loaded_filename.



402
403
404
# File 'lib/hash_delegator.rb', line 402

def most_recent_loaded_filename
  @most_recent_loaded_filename
end

#pass_argsObject

Returns the value of attribute pass_args.



402
403
404
# File 'lib/hash_delegator.rb', line 402

def pass_args
  @pass_args
end

#run_stateObject

Returns the value of attribute run_state.



402
403
404
# File 'lib/hash_delegator.rb', line 402

def run_state
  @run_state
end

Instance Method Details

#add_menu_chrome_blocks!(menu_blocks:, link_state:) ⇒ Object

Modifies the provided menu blocks array by adding ‘Back’ and ‘Exit’ options, along with initial and final dividers, based on the delegate object’s configuration.

Parameters:

  • menu_blocks (Array)

    The array of menu block elements to be modified.



437
438
439
440
441
442
443
444
445
446
447
448
449
# File 'lib/hash_delegator.rb', line 437

def add_menu_chrome_blocks!(menu_blocks:, link_state:)
  return unless @delegate_object[:menu_link_format].present?

  add_inherited_lines(menu_blocks: menu_blocks, link_state: link_state) if @delegate_object[:menu_with_inherited_lines]

  # back before exit
  add_back_option(menu_blocks: menu_blocks) if should_add_back_option?

  # exit after other options
  add_exit_option(menu_blocks: menu_blocks) if @delegate_object[:menu_with_exit]

  add_dividers(menu_blocks: menu_blocks)
end

#append_chrome_block(menu_blocks:, menu_state:) ⇒ Object

Appends a chrome block, which is a menu option for Back or Exit

Parameters:

  • all_blocks (Array)

    The current blocks in the menu

  • type (Symbol)

    The type of chrome block to add (:back or :exit)



476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
# File 'lib/hash_delegator.rb', line 476

def append_chrome_block(menu_blocks:, menu_state:)
  case menu_state
  when MenuState::BACK
    history_state_partition
    option_name = @delegate_object[:menu_option_back_name]
    insert_at_top = @delegate_object[:menu_back_at_top]
  when MenuState::EXIT
    option_name = @delegate_object[:menu_option_exit_name]
    insert_at_top = @delegate_object[:menu_exit_at_top]
  end

  formatted_name = format(@delegate_object[:menu_link_format],
                          HashDelegator.safeval(option_name))
  chrome_block = FCB.new(
    chrome: true,
    dname: HashDelegator.new(@delegate_object).string_send_color(
      formatted_name, :menu_link_color
    ),
    oname: formatted_name
  )

  if insert_at_top
    menu_blocks.unshift(chrome_block)
  else
    menu_blocks.push(chrome_block)
  end
end

#append_divider(menu_blocks:, position:) ⇒ Object

Appends a formatted divider to the specified position in a menu block array. The method checks for the presence of formatting options before appending.

Parameters:

  • menu_blocks (Array)

    The array of menu block elements.

  • position (Symbol)

    The position to insert the divider (:initial or :final).



542
543
544
545
546
547
# File 'lib/hash_delegator.rb', line 542

def append_divider(menu_blocks:, position:)
  return unless divider_formatting_present?(position)

  divider = create_divider(position)
  position == :initial ? menu_blocks.unshift(divider) : menu_blocks.push(divider)
end

#append_inherited_lines(menu_blocks:, link_state:, position: top) ⇒ Object

Appends a formatted divider to the specified position in a menu block array. The method checks for the presence of formatting options before appending.

Parameters:

  • menu_blocks (Array)

    The array of menu block elements.

  • position (Symbol) (defaults to: top)

    The position to insert the divider (:initial or :final).



509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
# File 'lib/hash_delegator.rb', line 509

def append_inherited_lines(menu_blocks:, link_state:, position: top)
  return unless link_state.inherited_lines.present?

  insert_at_top = @delegate_object[:menu_inherited_lines_at_top]
  chrome_blocks = link_state.inherited_lines.map do |line|
    formatted = format(@delegate_object[:menu_inherited_lines_format],
                       { line: line })
    FCB.new(
      chrome: true,
      disabled: '',
      dname: HashDelegator.new(@delegate_object).string_send_color(
        formatted, :menu_inherited_lines_color
      ),
      oname: formatted
    )
  end

  if insert_at_top
    # Prepend an array of elements to the beginning
    menu_blocks.unshift(*chrome_blocks)
  else
    # Append an array of elements to the end
    menu_blocks.concat(chrome_blocks)
  end
rescue StandardError
  HashDelegator.error_handler('append_inherited_lines')
end

#apply_shell_color_option(name, shell_color_option) ⇒ String

Applies shell color options to the given string if applicable.

Parameters:

  • name (String)

    The name to potentially colorize.

  • shell_color_option (Symbol, nil)

    The shell color option to apply.

Returns:

  • (String)

    The colorized or original name string.



556
557
558
559
560
561
562
# File 'lib/hash_delegator.rb', line 556

def apply_shell_color_option(name, shell_color_option)
  if shell_color_option && @delegate_object[shell_color_option].present?
    string_send_color(name, shell_color_option)
  else
    name
  end
end

#assign_key_value_in_bash(key, value) ⇒ Object



564
565
566
567
568
569
570
571
# File 'lib/hash_delegator.rb', line 564

def assign_key_value_in_bash(key, value)
  if value =~ /["$\\`]/
    # requiring ShellWords to write into Bash scripts
    "#{key}=#{Shellwords.escape(value)}"
  else
    "#{key}=\"#{value}\""
  end
end

#block_state_for_name_from_cli(block_name) ⇒ Object



1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
# File 'lib/hash_delegator.rb', line 1840

def block_state_for_name_from_cli(block_name)
  SelectedBlockMenuState.new(
    @dml_blocks_in_file.find do |item|
      item[:oname] == block_name
    end&.merge(
      block_name_from_cli: true,
      block_name_from_ui: false
    ),
    MenuState::CONTINUE
  )
end

#blocks_from_nested_filesArray<FCB>

Iterates through nested files to collect various types of blocks, including dividers, tasks, and others. The method categorizes blocks based on their type and processes them accordingly.

Returns:

  • (Array<FCB>)

    An array of FCB objects representing the blocks.



579
580
581
582
583
584
585
586
587
588
# File 'lib/hash_delegator.rb', line 579

def blocks_from_nested_files
  blocks = []
  iter_blocks_from_nested_files do |btype, fcb|
    process_block_based_on_type(blocks, btype, fcb)
  end
  # &bc  'blocks.count:', blocks.count
  blocks
rescue StandardError
  HashDelegator.error_handler('blocks_from_nested_files')
end

#calc_logged_stdout_filename(block_name:) ⇒ Object

private



592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
# File 'lib/hash_delegator.rb', line 592

def calc_logged_stdout_filename(block_name:)
  return unless @delegate_object[:saved_stdout_folder]

  @delegate_object[:logged_stdout_filename] =
    SavedAsset.stdout_name(blockname: block_name,
                           filename: File.basename(@delegate_object[:filename],
                                                   '.*'),
                           prefix: @delegate_object[:logged_stdout_filename_prefix],
                           time: Time.now.utc)

  @logged_stdout_filespec =
    @delegate_object[:logged_stdout_filespec] =
      File.join @delegate_object[:saved_stdout_folder],
                @delegate_object[:logged_stdout_filename]
end

#cfileObject



608
609
610
611
612
# File 'lib/hash_delegator.rb', line 608

def cfile
  @cfile ||= CachedNestedFileReader.new(
    import_pattern: @delegate_object.fetch(:import_pattern) #, "^ *@import +(?<name>.+?) *$")
  )
end

#check_file_existence(filename) ⇒ Object

Check whether the document exists and is readable



615
616
617
618
619
620
621
622
623
624
625
626
# File 'lib/hash_delegator.rb', line 615

def check_file_existence(filename)
  unless filename&.present?
    @fout.fout 'No blocks found.'
    return false
  end

  unless File.exist? filename
    @fout.fout 'Document is missing.'
    return false
  end
  true
end

#collect_required_code_lines(mdoc:, selected:, block_source:, link_state: LinkState.new) ⇒ Array<String>

Collects required code lines based on the selected block and the delegate object’s configuration. If the block type is VARS, it also sets environment variables based on the block’s content.

Parameters:

  • mdoc (YourMDocClass)

    An instance of the MDoc class.

  • selected (Hash)

    The selected block.

Returns:

  • (Array<String>)

    Required code blocks as an array of lines.



634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
# File 'lib/hash_delegator.rb', line 634

def collect_required_code_lines(mdoc:, selected:, block_source:, link_state: LinkState.new)
  required = mdoc.collect_recursively_required_code(
    anyname: selected[:nickname] || selected[:oname],
    label_format_above: @delegate_object[:shell_code_label_format_above],
    label_format_below: @delegate_object[:shell_code_label_format_below],
    block_source: block_source
  )
  dependencies = (link_state&.inherited_dependencies || {}).merge(required[:dependencies] || {})
  required[:unmet_dependencies] =
    (required[:unmet_dependencies] || []) - (link_state&.inherited_block_names || [])
  if required[:unmet_dependencies].present?
    ### filter against link_state.inherited_block_names

    warn format_and_highlight_dependencies(dependencies,
                                           highlight: required[:unmet_dependencies])
    runtime_exception(:runtime_exception_error_level,
                      'unmet_dependencies, flag: runtime_exception_error_level',
                      required[:unmet_dependencies])
  else
    warn format_and_highlight_dependencies(dependencies,
                                           highlight: [@delegate_object[:block_name]])
  end

  code_lines = selected[:shell] == BlockType::VARS ? set_environment_variables_for_block(selected) : []

  HashDelegator.code_merge(link_state&.inherited_lines, required[:code] + code_lines)
end

#command_execute(command, args: []) ⇒ Object



662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
# File 'lib/hash_delegator.rb', line 662

def command_execute(command, args: [])
  @run_state.files = Hash.new([])
  @run_state.options = @delegate_object
  @run_state.started_at = Time.now.utc

  if @delegate_object[:execute_in_own_window] &&
     @delegate_object[:execute_command_format].present? &&
     @run_state.saved_filespec.present?
    @run_state.in_own_window = true
    system(
      format(
        @delegate_object[:execute_command_format],
        {
          batch_index: @run_state.batch_index,
          batch_random: @run_state.batch_random,
          block_name: @delegate_object[:block_name],
          document_filename: File.basename(@delegate_object[:filename]),
          document_filespec: @delegate_object[:filename],
          home: Dir.pwd,
          output_filename: File.basename(@delegate_object[:logged_stdout_filespec]),
          output_filespec: @delegate_object[:logged_stdout_filespec],
          script_filename: @run_state.saved_filespec,
          script_filespec: File.join(Dir.pwd, @run_state.saved_filespec),
          started_at: @run_state.started_at.strftime(
            @delegate_object[:execute_command_title_time_format]
          )
        }
      )
    )

  else
    @run_state.in_own_window = false
    Open3.popen3(@delegate_object[:shell],
                 '-c', command,
                 @delegate_object[:filename],
                 *args) do |stdin, stdout, stderr, exec_thr|
      handle_stream(stream: stdout, file_type: ExecutionStreams::StdOut) do |line|
        yield nil, line, nil, exec_thr if block_given?
      end
      handle_stream(stream: stderr, file_type: ExecutionStreams::StdErr) do |line|
        yield nil, nil, line, exec_thr if block_given?
      end

      in_thr = handle_stream(stream: $stdin, file_type: ExecutionStreams::StdIn) do |line|
        stdin.puts(line)
        yield line, nil, nil, exec_thr if block_given?
      end

      wait_for_stream_processing
      exec_thr.join
      sleep 0.1
      in_thr.kill if in_thr&.alive?
    end
  end

  @run_state.completed_at = Time.now.utc
rescue Errno::ENOENT => err
  # Handle ENOENT error
  @run_state.aborted_at = Time.now.utc
  @run_state.error_message = err.message
  @run_state.error = err
  @run_state.files[ExecutionStreams::StdErr] += [@run_state.error_message]
  @fout.fout "Error ENOENT: #{err.inspect}"
rescue SignalException => err
  # Handle SignalException
  @run_state.aborted_at = Time.now.utc
  @run_state.error_message = 'SIGTERM'
  @run_state.error = err
  @run_state.files[ExecutionStreams::StdErr] += [@run_state.error_message]
  @fout.fout "Error ENOENT: #{err.inspect}"
end

#compile_execute_and_trigger_reuse(mdoc:, selected:, block_source:, link_state: nil) ⇒ LoadFileLinkState

This method is responsible for handling the execution of generic blocks in a markdown document. It collects the required code lines from the document and, depending on the configuration, may display the code for user approval before execution. It then executes the approved block.

Parameters:

  • mdoc (Object)

    The markdown document object containing code blocks.

  • selected (Hash)

    The selected item from the menu to be executed.

Returns:

  • (LoadFileLinkState)

    An object indicating whether to load the next block or reuse the current one.



758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
# File 'lib/hash_delegator.rb', line 758

def compile_execute_and_trigger_reuse(mdoc:, selected:, block_source:, link_state: nil)
  required_lines = collect_required_code_lines(mdoc: mdoc, selected: selected, link_state: link_state,
                                               block_source: block_source)
  output_or_approval = @delegate_object[:output_script] || @delegate_object[:user_must_approve]
  display_required_code(required_lines: required_lines) if output_or_approval
  allow_execution = if @delegate_object[:user_must_approve]
                      prompt_for_user_approval(required_lines: required_lines, selected: selected)
                    else
                      true
                    end

  execute_required_lines(required_lines: required_lines, selected: selected) if allow_execution

  link_state.block_name = nil
  LoadFileLinkState.new(LoadFile::Reuse, link_state)
end

#contains_wildcards?(expr) ⇒ Boolean

Check if the expression contains wildcard characters

Returns:

  • (Boolean)


1289
1290
1291
# File 'lib/hash_delegator.rb', line 1289

def contains_wildcards?(expr)
  expr.match(%r{\*|\?|\[})
end

#copy_to_clipboard(required_lines) ⇒ Object



775
776
777
778
779
780
781
# File 'lib/hash_delegator.rb', line 775

def copy_to_clipboard(required_lines)
  text = required_lines.flatten.join($INPUT_RECORD_SEPARATOR)
  Clipboard.copy(text)
  @fout.fout "Clipboard updated: #{required_lines.count} blocks," \
             " #{required_lines.flatten.count} lines," \
             " #{text.length} characters"
end

#count_blocks_in_filenameInteger

Counts the number of fenced code blocks in a file. It reads lines from a file and counts occurrences of lines matching the fenced block regex. Assumes that every fenced block starts and ends with a distinct line (hence divided by 2).

Returns:

  • (Integer)

    The count of fenced code blocks in the file.



788
789
790
791
792
793
# File 'lib/hash_delegator.rb', line 788

def count_blocks_in_filename
  regex = Regexp.new(@delegate_object[:fenced_start_and_end_regex])
  lines = cfile.readlines(@delegate_object[:filename],
                          import_paths: @delegate_object[:import_paths]&.split(':'))
  HashDelegator.count_matches_in_lines(lines, regex) / 2
end

#create_and_add_chrome_block(blocks:, match_data:, format_option:, color_method:) ⇒ Object

Creates and adds a formatted block to the blocks array based on the provided match and format options.

Parameters:

  • blocks (Array)

    The array of blocks to add the new block to.

  • match_data (MatchData)

    The match data containing named captures for formatting.

  • format_option (String)

    The format string to be used for the new block.

  • color_method (Symbol)

    The color method to apply to the block’s display name.



801
802
803
804
805
806
807
808
809
810
811
# File 'lib/hash_delegator.rb', line 801

def create_and_add_chrome_block(blocks:, match_data:, format_option:,
                                color_method:)
  oname = format(format_option,
                 match_data.named_captures.transform_keys(&:to_sym))
  blocks.push FCB.new(
    chrome: true,
    disabled: '',
    dname: oname.send(color_method),
    oname: oname
  )
end

#create_and_add_chrome_blocks(blocks, fcb) ⇒ Object

Processes lines within the file and converts them into blocks if they match certain criteria.

Parameters:

  • blocks (Array)

    The array to append new blocks to.

  • fcb (FCB)

    The file control block being processed.

  • opts (Hash)

    Options containing configuration for line processing.

  • use_chrome (Boolean)

    Indicates if the chrome styling should be applied.



819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
# File 'lib/hash_delegator.rb', line 819

def create_and_add_chrome_blocks(blocks, fcb)
  match_criteria = [
    { color: :menu_heading1_color, format: :menu_heading1_format, match: :heading1_match },
    { color: :menu_heading2_color, format: :menu_heading2_format, match: :heading2_match },
    { color: :menu_heading3_color, format: :menu_heading3_format, match: :heading3_match },
    { color: :menu_divider_color,  format: :menu_divider_format,  match: :menu_divider_match },
    { color: :menu_note_color,     format: :menu_note_format,     match: :menu_note_match },
    { color: :menu_task_color,     format: :menu_task_format,     match: :menu_task_match }
  ]
  # rubocop:enable Style/UnlessElse
  match_criteria.each do |criteria|
    unless @delegate_object[criteria[:match]].present? &&
           (mbody = fcb.body[0].match @delegate_object[criteria[:match]])
      next
    end

    create_and_add_chrome_block(
      blocks: blocks,
      match_data: mbody,
      format_option: @delegate_object[criteria[:format]],
      color_method: @delegate_object[criteria[:color]].to_sym
    )
    break
  end
end

#create_divider(position) ⇒ Object



845
846
847
848
849
850
851
852
853
854
855
856
# File 'lib/hash_delegator.rb', line 845

def create_divider(position)
  divider_key = position == :initial ? :menu_initial_divider : :menu_final_divider
  oname = format(@delegate_object[:menu_divider_format],
                 HashDelegator.safeval(@delegate_object[divider_key]))

  FCB.new(
    chrome: true,
    disabled: '',
    dname: string_send_color(oname, :menu_divider_color),
    oname: oname
  )
end

#debounce_allowsBoolean

Prompts user if named block is the same as the prior execution.

Returns:

  • (Boolean)

    Execute the named block.



861
862
863
864
865
866
867
868
869
870
871
872
873
# File 'lib/hash_delegator.rb', line 861

def debounce_allows
  return true unless @delegate_object[:debounce_execution]

  # filter block if selected in menu
  return true if @run_state.block_name_from_cli

  # return false if @prior_execution_block == @delegate_object[:block_name]
  return @allowed_execution_block == @prior_execution_block || prompt_approve_repeat if @prior_execution_block == @delegate_object[:block_name]

  @prior_execution_block = @delegate_object[:block_name]
  @allowed_execution_block = nil
  true
end

#debounce_resetObject



875
876
877
# File 'lib/hash_delegator.rb', line 875

def debounce_reset
  @prior_execution_block = nil
end

#determine_block_state(selected_option) ⇒ SelectedBlockMenuState

Determines the state of a selected block in the menu based on the selected option. It categorizes the selected option into either EXIT, BACK, or CONTINUE state.

Parameters:

  • selected_option (Hash)

    The selected menu option.

Returns:



884
885
886
887
888
889
890
891
892
893
894
895
896
# File 'lib/hash_delegator.rb', line 884

def determine_block_state(selected_option)
  option_name = selected_option.fetch(:oname, nil)
  if option_name == menu_chrome_formatted_option(:menu_option_exit_name)
    return SelectedBlockMenuState.new(nil,
                                      MenuState::EXIT)
  end
  if option_name == menu_chrome_formatted_option(:menu_option_back_name)
    return SelectedBlockMenuState.new(selected_option,
                                      MenuState::BACK)
  end

  SelectedBlockMenuState.new(selected_option, MenuState::CONTINUE)
end

#display_required_code(required_lines:) ⇒ Object

Displays the required lines of code with color formatting for the preview section. It wraps the code lines between a formatted header and tail.

Parameters:

  • required_lines (Array<String>)

    The lines of code to be displayed.



902
903
904
905
906
907
908
# File 'lib/hash_delegator.rb', line 902

def display_required_code(required_lines:)
  output_color_formatted(:script_preview_head,
                         :script_preview_frame_color)
  required_lines.each { |cb| @fout.fout cb }
  output_color_formatted(:script_preview_tail,
                         :script_preview_frame_color)
end

#divider_formatting_present?(position) ⇒ Boolean

Returns:

  • (Boolean)


910
911
912
913
# File 'lib/hash_delegator.rb', line 910

def divider_formatting_present?(position)
  divider_key = position == :initial ? :menu_initial_divider : :menu_final_divider
  @delegate_object[:menu_divider_format].present? && @delegate_object[divider_key].present?
end

#do_save_execution_outputObject



915
916
917
918
919
920
921
# File 'lib/hash_delegator.rb', line 915

def do_save_execution_output
  return unless @delegate_object[:save_execution_output]
  return if @run_state.in_own_window

  HashDelegator.write_execution_output_to_file(@run_state.files,
                                               @delegate_object[:logged_stdout_filespec])
end

#document_menu_loopNil

Select and execute a code block from a Markdown document.

This method allows the user to interactively select a code block from a Markdown document, obtain approval, and execute the chosen block of code.

Returns:

  • (Nil)

    Returns nil if no code block is selected or an error occurs.



1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
# File 'lib/hash_delegator.rb', line 1858

def document_menu_loop
  @menu_base_options = @delegate_object
  @dml_link_state = LinkState.new(
    block_name: @delegate_object[:block_name],
    document_filename: @delegate_object[:filename]
  )
  @run_state.block_name_from_cli = @dml_link_state.block_name.present?
  @cli_block_name = @dml_link_state.block_name
  @dml_now_using_cli = @run_state.block_name_from_cli
  @dml_menu_default_dname = nil
  @dml_block_state = SelectedBlockMenuState.new

  @run_state.batch_random = Random.new.rand
  @run_state.batch_index = 0

  InputSequencer.new(
    @delegate_object[:filename],
    @delegate_object[:input_cli_rest]
  ).run do |msg, data|
    case msg
    when :parse_document # once for each menu
      # puts "@ - parse document #{data}"
      ii_parse_document(data)

    when :display_menu
      # warn "@ - display menu:"
      # ii_display_menu
      @dml_block_state = SelectedBlockMenuState.new
      @delegate_object[:block_name] = nil

    when :user_choice
      if @dml_link_state.block_name.present?
        # @prior_block_was_link = true
        @dml_block_state.block = @dml_blocks_in_file.find do |item|
          item[:oname] == @dml_link_state.block_name
        end
        @dml_link_state.block_name = nil
      else
        # puts "? - Select a block to execute (or type #{$texit} to exit):"
        break if ii_user_choice == :break # into @dml_block_state
        break if @dml_block_state.block.nil? # no block matched
      end
      # puts "! - Executing block: #{data}"
      # @dml_block_state.block[:oname]
      @dml_block_state.block&.fetch(:oname, nil)

    when :execute_block
      block_name = data
      if block_name == '* Back' ####
        debounce_reset
        @menu_user_clicked_back_link = true
        load_file_link_state = pop_link_history_and_trigger_load
        @dml_link_state = load_file_link_state.link_state

        InputSequencer.merge_link_state(
          @dml_link_state,
          InputSequencer.next_link_state(
            block_name: @dml_link_state.block_name,
            document_filename: @dml_link_state.document_filename,
            prior_block_was_link: true
          )
        )

      else
        @dml_block_state = block_state_for_name_from_cli(block_name)
        if @dml_block_state.block[:shell] == BlockType::OPTS
          debounce_reset
          link_state = LinkState.new
          options_state = read_show_options_and_trigger_reuse(
            selected: @dml_block_state.block,
            link_state: link_state
          )

          @menu_base_options.merge!(options_state.options)
          @delegate_object.merge!(options_state.options)
          options_state.load_file_link_state.link_state
        else
          ii_execute_block(block_name)

          if prompt_user_exit(block_name_from_cli: @run_state.block_name_from_cli,
                              selected: @dml_block_state.block)
            return :break
          end

          ## order of block name processing: link block, cli, from user
          #
          @dml_link_state.block_name, @run_state.block_name_from_cli, cli_break = \
            HashDelegator.next_link_state(
              block_name: @dml_link_state.block_name,
              block_name_from_cli: !@dml_link_state.block_name.present?,
              block_state: @dml_block_state,
              was_using_cli: @dml_now_using_cli
            )

          if !@dml_block_state.block[:block_name_from_ui] && cli_break
            # &bsp '!block_name_from_ui + cli_break -> break'
            return :break
          end

          InputSequencer.next_link_state(
            block_name: @dml_link_state.block_name,
            prior_block_was_link: @dml_block_state.block[:shell] != BlockType::BASH
          )
        end
      end

    when :exit?
      data == $texit
    when :stay?
      data == $stay
    else
      raise "Invalid message: #{msg}"
    end
  end
rescue StandardError
  HashDelegator.error_handler('document_menu_loop',
                              { abort: true })
end

#dump_and_warn_block_state(selected:) ⇒ Object



2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
# File 'lib/hash_delegator.rb', line 2110

def dump_and_warn_block_state(selected:)
  if selected.nil?
    Exceptions.warn_format("Block not found -- name: #{@delegate_object[:block_name]}",
                           { abort: true })
  end

  return unless @delegate_object[:dump_selected_block]

  warn selected.to_yaml.sub(/^(?:---\n)?/, "Block:\n")
end

#dump_delobj(blocks_in_file, menu_blocks, link_state) ⇒ Object

Outputs warnings based on the delegate object’s configuration

Parameters:

  • delegate_object (Hash)

    The delegate object containing configuration flags.

  • blocks_in_file (Hash)

    Hash of blocks present in the file.

  • menu_blocks (Hash)

    Hash of menu blocks.

  • link_state (LinkState)

    Current state of the link.



2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
# File 'lib/hash_delegator.rb', line 2090

def dump_delobj(blocks_in_file, menu_blocks, link_state)
  warn format_and_highlight_hash(@delegate_object, label: '@delegate_object') if @delegate_object[:dump_delegate_object]

  if @delegate_object[:dump_blocks_in_file]
    warn format_and_highlight_dependencies(compact_and_index_hash(blocks_in_file),
                                           label: 'blocks_in_file')
  end

  if @delegate_object[:dump_menu_blocks]
    warn format_and_highlight_dependencies(compact_and_index_hash(menu_blocks),
                                           label: 'menu_blocks')
  end

  warn format_and_highlight_lines(link_state.inherited_block_names, label: 'inherited_block_names') if @delegate_object[:dump_inherited_block_names]
  warn format_and_highlight_lines(link_state.inherited_dependencies, label: 'inherited_dependencies') if @delegate_object[:dump_inherited_dependencies]
  return unless @delegate_object[:dump_inherited_lines]

  warn format_and_highlight_lines(link_state.inherited_lines, label: 'inherited_lines')
end

#exec_bash_next_state(selected:, mdoc:, link_state:, block_source: {}) ⇒ Object



2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
# File 'lib/hash_delegator.rb', line 2017

def exec_bash_next_state(selected:, mdoc:, link_state:, block_source: {})
  lfls = execute_shell_type(
    selected: selected,
    mdoc: mdoc,
    link_state: link_state,
    block_source: block_source
  )

  # if the same menu is being displayed, collect the display name of the selected menu item for use as the default item
  [lfls.link_state,
   lfls.load_file == LoadFile::Load ? nil : selected[:dname]]
end

#execute_required_lines(required_lines: [], selected: FCB.new) ⇒ Object

Executes a block of code that has been approved for execution. It sets the script block name, writes command files if required, and handles the execution including output formatting and summarization.

Parameters:

  • required_lines (Array<String>) (defaults to: [])

    The lines of code to be executed.

  • selected (FCB) (defaults to: FCB.new)

    The selected functional code block object.



929
930
931
932
933
934
# File 'lib/hash_delegator.rb', line 929

def execute_required_lines(required_lines: [], selected: FCB.new)
  write_command_file(required_lines: required_lines, selected: selected) if @delegate_object[:save_executed_script]
  calc_logged_stdout_filename(block_name: @dml_block_state.block[:oname]) if @dml_block_state
  format_and_execute_command(code_lines: required_lines)
  post_execution_process
end

#execute_shell_type(selected:, mdoc:, block_source:, link_state: LinkState.new) ⇒ Object

Execute a code block after approval and provide user interaction options.

This method displays required code blocks, asks for user approval, and executes the code block if approved. It also allows users to copy the code to the clipboard or save it to a file.

Parameters:

  • opts (Hash)

    Options hash containing configuration settings.

  • mdoc (YourMDocClass)

    An instance of the MDoc class.



945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
# File 'lib/hash_delegator.rb', line 945

def execute_shell_type(selected:, mdoc:, block_source:, link_state: LinkState.new)
  if selected.fetch(:shell, '') == BlockType::LINK
    debounce_reset
    push_link_history_and_trigger_load(link_block_body: selected.fetch(:body, ''),
                                       mdoc: mdoc,
                                       selected: selected,
                                       link_state: link_state,
                                       block_source: block_source)

  elsif @menu_user_clicked_back_link
    debounce_reset
    pop_link_history_and_trigger_load

  elsif selected[:shell] == BlockType::OPTS
    debounce_reset
    block_names = []
    code_lines = []
    dependencies = {}
    options_state = read_show_options_and_trigger_reuse(selected: selected, link_state: link_state)

    ## apply options to current state
    #
    @menu_base_options.merge!(options_state.options)
    @delegate_object.merge!(options_state.options)

    ### options_state.load_file_link_state
    link_state = LinkState.new
    link_history_push_and_next(
      curr_block_name: selected[:oname],
      curr_document_filename: @delegate_object[:filename],
      inherited_block_names: ((link_state&.inherited_block_names || []) + block_names).sort.uniq,
      inherited_dependencies: (link_state&.inherited_dependencies || {}).merge(dependencies || {}), ### merge, not replace, key data
      inherited_lines: HashDelegator.code_merge(link_state&.inherited_lines, code_lines),
      next_block_name: '',
      next_document_filename: @delegate_object[:filename],
      next_load_file: LoadFile::Reuse
    )

  elsif selected[:shell] == BlockType::VARS
    debounce_reset
    block_names = []
    code_lines = set_environment_variables_for_block(selected)
    dependencies = {}
    link_history_push_and_next(
      curr_block_name: selected[:oname],
      curr_document_filename: @delegate_object[:filename],
      inherited_block_names: ((link_state&.inherited_block_names || []) + block_names).sort.uniq,
      inherited_dependencies: (link_state&.inherited_dependencies || {}).merge(dependencies || {}), ### merge, not replace, key data
      inherited_lines: HashDelegator.code_merge(link_state&.inherited_lines, code_lines),
      next_block_name: '',
      next_document_filename: @delegate_object[:filename],
      next_load_file: LoadFile::Reuse
    )

  elsif debounce_allows
    compile_execute_and_trigger_reuse(mdoc: mdoc,
                                      selected: selected,
                                      link_state: link_state,
                                      block_source: block_source)

  else
    LoadFileLinkState.new(LoadFile::Reuse, link_state)
  end
end

#fetch_color(default: '', data_sym: :execution_report_preview_head, color_sym: :execution_report_preview_frame_color) ⇒ String

Retrieves a specific data symbol from the delegate object, converts it to a string, and applies a color style based on the specified color symbol.

Parameters:

  • default (String) (defaults to: '')

    The default value if the data symbol is not found.

  • data_sym (Symbol) (defaults to: :execution_report_preview_head)

    The symbol key to fetch data from the delegate object.

  • color_sym (Symbol) (defaults to: :execution_report_preview_frame_color)

    The symbol key to fetch the color option for styling.

Returns:

  • (String)

    The color-styled string.



1017
1018
1019
1020
1021
1022
# File 'lib/hash_delegator.rb', line 1017

def fetch_color(default: '',
                data_sym: :execution_report_preview_head,
                color_sym: :execution_report_preview_frame_color)
  data_string = @delegate_object.fetch(data_sym, default).to_s
  string_send_color(data_string, color_sym)
end

#format_and_execute_command(code_lines:) ⇒ Object



1024
1025
1026
1027
1028
1029
1030
1031
# File 'lib/hash_delegator.rb', line 1024

def format_and_execute_command(code_lines:)
  formatted_command = code_lines.flatten.join("\n")
  @fout.fout fetch_color(data_sym: :script_execution_head,
                         color_sym: :script_execution_frame_color)
  command_execute(formatted_command, args: @pass_args)
  @fout.fout fetch_color(data_sym: :script_execution_tail,
                         color_sym: :script_execution_frame_color)
end

#format_expression(expr) ⇒ Object

Format expression using environment variables and run state



1282
1283
1284
1285
1286
# File 'lib/hash_delegator.rb', line 1282

def format_expression(expr)
  data = link_load_format_data
  ENV.each { |key, value| data[key] = value }
  format(expr, data)
end

#format_multiline_body_as_title(body_lines) ⇒ String

Formats multiline body content as a title string. indents all but first line with two spaces so it displays correctly in menu

Parameters:

  • body_lines (Array<String>)

    The lines of body content.

Returns:

  • (String)

    Formatted title.



1087
1088
1089
1090
1091
# File 'lib/hash_delegator.rb', line 1087

def format_multiline_body_as_title(body_lines)
  body_lines.map.with_index do |line, index|
    index.zero? ? line : "  #{line}"
  end.join("\n") + "\n"
end

#format_references_send_color(default: '', context: {}, format_sym: :output_execution_label_format, color_sym: :execution_report_preview_frame_color) ⇒ String

Formats a string based on a given context and applies color styling to it. It retrieves format and color information from the delegate object and processes accordingly.

Parameters:

  • default (String) (defaults to: '')

    The default value if the format symbol is not found (unused in current implementation).

  • context (Hash) (defaults to: {})

    Contextual data used for string formatting.

  • format_sym (Symbol) (defaults to: :output_execution_label_format)

    Symbol key to fetch the format string from the delegate object.

  • color_sym (Symbol) (defaults to: :execution_report_preview_frame_color)

    Symbol key to fetch the color option for string styling.

Returns:

  • (String)

    The formatted and color-styled string.



1041
1042
1043
1044
1045
1046
1047
# File 'lib/hash_delegator.rb', line 1041

def format_references_send_color(default: '', context: {},
                                 format_sym: :output_execution_label_format,
                                 color_sym: :execution_report_preview_frame_color)
  formatted_string = format(@delegate_object.fetch(format_sym, ''),
                            context).to_s
  string_send_color(formatted_string, color_sym)
end

#formatted_expression(expr) ⇒ Object

Expand expression if it contains format specifiers



1277
1278
1279
# File 'lib/hash_delegator.rb', line 1277

def formatted_expression(expr)
  expr.include?('%{') ? format_expression(expr) : expr
end

#get_block_summary(fcb) ⇒ Object

Processes a block to generate its summary, modifying its attributes based on various matching criteria. It handles special formatting for bash blocks, extracting and setting properties like call, stdin, stdout, and dname.

Parameters:

  • fcb (Object)

    An object representing a functional code block.

Returns:

  • (Object)

    The modified functional code block with updated summary attributes.



1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
# File 'lib/hash_delegator.rb', line 1054

def get_block_summary(fcb)
  return fcb unless @delegate_object[:bash]

  fcb.call = fcb.title.match(Regexp.new(@delegate_object[:block_calls_scan]))&.fetch(1, nil)
  titlexcall = fcb.call ? fcb.title.sub("%#{fcb.call}", '') : fcb.title
  bm = extract_named_captures_from_option(titlexcall,
                                          @delegate_object[:block_name_match])

  fcb.stdin = extract_named_captures_from_option(titlexcall,
                                                 @delegate_object[:block_stdin_scan])
  fcb.stdout = extract_named_captures_from_option(titlexcall,
                                                  @delegate_object[:block_stdout_scan])

  shell_color_option = SHELL_COLOR_OPTIONS[fcb[:shell]]

  if @delegate_object[:block_name_nick_match].present? && fcb.oname =~ Regexp.new(@delegate_object[:block_name_nick_match])
    fcb.nickname = $~[0]
    fcb.title = fcb.oname = format_multiline_body_as_title(fcb.body)
  else
    fcb.title = fcb.oname = bm && bm[1] ? bm[:title] : titlexcall
  end

  fcb.dname = HashDelegator.indent_all_lines(
    apply_shell_color_option(fcb.oname, shell_color_option),
    fcb.fetch(:indent, nil)
  )
  fcb
end

#handle_back_or_continue(block_state) ⇒ Object

Updates the delegate object’s state based on the provided block state. It sets the block name and determines if the user clicked the back link in the menu.

Parameters:

  • block_state (Object)

    An object representing the state of a block in the menu.



1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
# File 'lib/hash_delegator.rb', line 1097

def handle_back_or_continue(block_state)
  return if block_state.nil?
  unless [MenuState::BACK,
          MenuState::CONTINUE].include?(block_state.state)
    return
  end

  @delegate_object[:block_name] = block_state.block[:oname]
  @menu_user_clicked_back_link = block_state.state == MenuState::BACK
end

#handle_stream(stream:, file_type:, swap: false) ⇒ Object



1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
# File 'lib/hash_delegator.rb', line 1108

def handle_stream(stream:, file_type:, swap: false)
  @process_mutex.synchronize do
    Thread.new do
      stream.each_line do |line|
        line.strip!
        @run_state.files[file_type] << line

        if @delegate_object[:output_stdout]
          # print line
          puts line
        end

        yield line if block_given?
      end
    rescue IOError
      # Handle IOError
    ensure
      @process_cv.signal
    end
  end
end

#ii_execute_block(block_name) ⇒ Object



2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
# File 'lib/hash_delegator.rb', line 2001

def ii_execute_block(block_name)
  @dml_block_state = block_state_for_name_from_cli(block_name)

  dump_and_warn_block_state(selected: @dml_block_state.block)
  @dml_link_state, @dml_menu_default_dname = \
    exec_bash_next_state(
      selected: @dml_block_state.block,
      mdoc: @dml_mdoc,
      link_state: @dml_link_state,
      block_source: {
        document_filename: @delegate_object[:filename],
        time_now_date: Time.now.utc.strftime(@delegate_object[:shell_code_label_time_format])
      }
    )
end

#ii_parse_document(_document_filename) ⇒ Object



1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
# File 'lib/hash_delegator.rb', line 1977

def ii_parse_document(_document_filename)
  @run_state.batch_index += 1
  @run_state.in_own_window = false

  # &bsp 'loop', block_name_from_cli, @cli_block_name
  @run_state.block_name_from_cli, @dml_now_using_cli, @dml_blocks_in_file, @dml_menu_blocks, @dml_mdoc = \
    set_delobj_menu_loop_vars(block_name_from_cli: @run_state.block_name_from_cli,
                              now_using_cli: @dml_now_using_cli,
                              link_state: @dml_link_state)
end

#ii_user_choiceObject



1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
# File 'lib/hash_delegator.rb', line 1988

def ii_user_choice
  @dml_block_state = load_cli_or_user_selected_block(all_blocks: @dml_blocks_in_file,
                                                     menu_blocks: @dml_menu_blocks,
                                                     default: @dml_menu_default_dname)
  # &bsp '@run_state.block_name_from_cli:',@run_state.block_name_from_cli
  if !@dml_block_state
    HashDelegator.error_handler('block_state missing', { abort: true })
  elsif @dml_block_state.state == MenuState::EXIT
    # &bsp 'load_cli_or_user_selected_block -> break'
    :break
  end
end

#initial_stateObject

Initializes variables for regex and other states



1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
# File 'lib/hash_delegator.rb', line 1131

def initial_state
  {
    fenced_start_and_end_regex: Regexp.new(@delegate_object.fetch(
                                             :fenced_start_and_end_regex, '^(?<indent> *)`{3,}'
                                           )),
    fenced_start_extended_regex: Regexp.new(@delegate_object.fetch(
                                              :fenced_start_and_end_regex, '^(?<indent> *)`{3,}'
                                            )),
    fcb: MarkdownExec::FCB.new,
    in_fenced_block: false,
    headings: []
  }
end

#iter_blocks_from_nested_files {|Symbol| ... } ⇒ Object

Iterates through blocks in a file, applying the provided block to each line. The iteration only occurs if the file exists.

Yields:

  • (Symbol)

    :filter Yields to obtain selected messages for processing.



1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
# File 'lib/hash_delegator.rb', line 1148

def iter_blocks_from_nested_files(&block)
  return unless check_file_existence(@delegate_object[:filename])

  state = initial_state
  selected_messages = yield :filter
  cfile.readlines(@delegate_object[:filename],
                  import_paths: @delegate_object[:import_paths]&.split(':')).each do |nested_line|
    if nested_line
      update_line_and_block_state(nested_line, state, selected_messages,
                                  &block)
    end
  end
end


1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
# File 'lib/hash_delegator.rb', line 1162

def link_block_data_eval(link_state, code_lines, selected, link_block_data, block_source:)
  all_code = HashDelegator.code_merge(link_state&.inherited_lines, code_lines)
  output_lines = []

  Tempfile.open do |file|
    cmd = "#{@delegate_object[:shell]} #{file.path}"
    file.write(all_code.join("\n"))
    file.rewind

    if link_block_data.fetch(LinkKeys::Exec, false)
      @run_state.files = Hash.new([])

      Open3.popen3(cmd) do |stdin, stdout, stderr, _exec_thr|
        handle_stream(stream: stdout, file_type: ExecutionStreams::StdOut) do |line|
          output_lines.push(line)
        end
        handle_stream(stream: stderr, file_type: ExecutionStreams::StdErr) do |line|
          output_lines.push(line)
        end

        in_thr = handle_stream(stream: $stdin, file_type: ExecutionStreams::StdIn) do |line|
          stdin.puts(line)
        end

        wait_for_stream_processing
        sleep 0.1
        in_thr.kill if in_thr&.alive?
      end

      ## select output_lines that look like assignment or match other specs
      #
      output_lines = process_string_array(
        output_lines,
        begin_pattern: @delegate_object.fetch(:output_assignment_begin, nil),
        end_pattern: @delegate_object.fetch(:output_assignment_end, nil),
        scan1: @delegate_object.fetch(:output_assignment_match, nil),
        format1: @delegate_object.fetch(:output_assignment_format, nil)
      )

    else
      output_lines = `#{cmd}`.split("\n")
    end
  end

  HashDelegator.error_handler('all_code eval output_lines is nil', { abort: true }) unless output_lines

  label_format_above = @delegate_object[:shell_code_label_format_above]
  label_format_below = @delegate_object[:shell_code_label_format_below]

  [label_format_above && format(label_format_above,
                                block_source.merge({ block_name: selected[:oname] }))] +
    output_lines.map do |line|
      re = Regexp.new(link_block_data.fetch('pattern', '(?<line>.*)'))
      re.gsub_format(line, link_block_data.fetch('format', '%{line}')) if re =~ line
    end.compact +
    [label_format_below && format(label_format_below,
                                  block_source.merge({ block_name: selected[:oname] }))]
end


1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
# File 'lib/hash_delegator.rb', line 1221

def link_history_push_and_next(
  curr_block_name:, curr_document_filename:,
  inherited_block_names:, inherited_dependencies:, inherited_lines:,
  next_block_name:, next_document_filename:,
  next_load_file:
)
  @link_history.push(
    LinkState.new(
      block_name: curr_block_name,
      document_filename: curr_document_filename,
      inherited_block_names: inherited_block_names,
      inherited_dependencies: inherited_dependencies,
      inherited_lines: inherited_lines
    )
  )
  LoadFileLinkState.new(
    next_load_file,
    LinkState.new(
      block_name: next_block_name,
      document_filename: next_document_filename,
      inherited_block_names: inherited_block_names,
      inherited_dependencies: inherited_dependencies,
      inherited_lines: inherited_lines
    )
  )
end


1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
# File 'lib/hash_delegator.rb', line 1344

def link_load_format_data
  {
    batch_index: @run_state.batch_index,
    batch_random: @run_state.batch_random,
    block_name: @delegate_object[:block_name],
    document_filename: File.basename(@delegate_object[:filename]),
    document_filespec: @delegate_object[:filename],
    home: Dir.pwd,
    started_at: Time.now.utc.strftime(@delegate_object[:execute_command_title_time_format])
  }
end

#load_auto_opts_block(all_blocks) ⇒ Boolean?

Loads auto blocks based on delegate object settings and updates if new filename is detected. Executes a specified block once per filename.

Parameters:

  • all_blocks (Array)

    Array of all block elements.

Returns:

  • (Boolean, nil)

    True if values were modified, nil otherwise.



1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
# File 'lib/hash_delegator.rb', line 1383

def load_auto_opts_block(all_blocks)
  block_name = @delegate_object[:document_load_opts_block_name]
  return unless block_name.present? && @most_recent_loaded_filename != @delegate_object[:filename]

  block = HashDelegator.block_find(all_blocks, :oname, block_name)
  return unless block

  options_state = read_show_options_and_trigger_reuse(selected: block)
  @menu_base_options.merge!(options_state.options)
  @delegate_object.merge!(options_state.options)

  @most_recent_loaded_filename = @delegate_object[:filename]
  true
end

#load_cli_or_user_selected_block(all_blocks: [], menu_blocks: [], default: nil) ⇒ Object



734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
# File 'lib/hash_delegator.rb', line 734

def load_cli_or_user_selected_block(all_blocks: [], menu_blocks: [], default: nil)
  if @delegate_object[:block_name].present?
    block = all_blocks.find do |item|
      item[:oname] == @delegate_object[:block_name]
    end&.merge(block_name_from_ui: false)
  else
    block_state = wait_for_user_selected_block(all_blocks, menu_blocks,
                                               default)
    block = block_state.block&.merge(block_name_from_ui: true)
    state = block_state.state
  end

  SelectedBlockMenuState.new(block, state)
rescue StandardError
  HashDelegator.error_handler('load_cli_or_user_selected_block')
end

#load_filespec_from_expression(expression) ⇒ Object

format + glob + select for file in load block name has references to ENV vars and doc and batch vars incl. timestamp



1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
# File 'lib/hash_delegator.rb', line 1250

def load_filespec_from_expression(expression)
  # Process expression with embedded formatting
  expanded_expression = formatted_expression(expression)

  # Handle wildcards or direct file specification
  if contains_wildcards?(expanded_expression)
    load_filespec_wildcard_expansion(expanded_expression)
  else
    expanded_expression
  end
end

#load_filespec_wildcard_expansion(expr) ⇒ Object

Handle expression with wildcard characters



1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
# File 'lib/hash_delegator.rb', line 1294

def load_filespec_wildcard_expansion(expr)
  files = find_files(expr)
  case files.count
  when 0
    HashDelegator.error_handler("no files found with '#{expr}' ", { abort: true })
  when 1
    files.first
  else
    prompt_select_code_filename(files)
  end
end

#manage_cli_selection_state(block_name_from_cli:, now_using_cli:, link_state:) ⇒ Object



2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
# File 'lib/hash_delegator.rb', line 2055

def manage_cli_selection_state(block_name_from_cli:, now_using_cli:, link_state:)
  if block_name_from_cli && @cli_block_name == @menu_base_options[:menu_persist_block_name]
    # &bsp 'pause cli control, allow user to select block'
    block_name_from_cli = false
    now_using_cli = false
    @menu_base_options[:block_name] = \
      @delegate_object[:block_name] = \
        link_state.block_name = \
          @cli_block_name = nil
  end

  @delegate_object = @menu_base_options.dup
  @menu_user_clicked_back_link = false
  [block_name_from_cli, now_using_cli]
end

#mdoc_and_blocks_from_nested_filesObject



1398
1399
1400
1401
1402
1403
1404
# File 'lib/hash_delegator.rb', line 1398

def mdoc_and_blocks_from_nested_files
  menu_blocks = blocks_from_nested_files
  mdoc = MDoc.new(menu_blocks) do |nopts|
    @delegate_object.merge!(nopts)
  end
  [menu_blocks, mdoc]
end

#mdoc_menu_and_blocks_from_nested_files(link_state) ⇒ Object

Handles the file loading and returns the blocks in the file and MDoc instance



1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
# File 'lib/hash_delegator.rb', line 1408

def mdoc_menu_and_blocks_from_nested_files(link_state)
  all_blocks, mdoc = mdoc_and_blocks_from_nested_files

  # recreate menu with new options
  #
  all_blocks, mdoc = mdoc_and_blocks_from_nested_files if load_auto_opts_block(all_blocks)
  # load_auto_link_block(all_blocks, link_state, mdoc, block_source: {})

  menu_blocks = mdoc.fcbs_per_options(@delegate_object)
  add_menu_chrome_blocks!(menu_blocks: menu_blocks, link_state: link_state)
  ### compress empty lines
  HashDelegator.delete_consecutive_blank_lines!(menu_blocks) if true
  [all_blocks, menu_blocks, mdoc]
end

Formats and optionally colors a menu option based on delegate object’s configuration.

Parameters:

  • option_symbol (Symbol) (defaults to: :menu_option_back_name)

    The symbol key for the menu option in the delegate object.

Returns:

  • (String)

    The formatted and possibly colored value of the menu option.



1426
1427
1428
1429
1430
1431
# File 'lib/hash_delegator.rb', line 1426

def menu_chrome_colored_option(option_symbol = :menu_option_back_name)
  formatted_option = menu_chrome_formatted_option(option_symbol)
  return formatted_option unless @delegate_object[:menu_chrome_color]

  string_send_color(formatted_option, :menu_chrome_color)
end

Formats a menu option based on the delegate object’s configuration. It safely evaluates the value of the option and optionally formats it.

Parameters:

  • option_symbol (Symbol) (defaults to: :menu_option_back_name)

    The symbol key for the menu option in the delegate object.

Returns:

  • (String)

    The formatted or original value of the menu option.



1437
1438
1439
1440
1441
1442
1443
1444
1445
# File 'lib/hash_delegator.rb', line 1437

def menu_chrome_formatted_option(option_symbol = :menu_option_back_name)
  option_value = HashDelegator.safeval(@delegate_object.fetch(option_symbol, ''))

  if @delegate_object[:menu_chrome_format]
    format(@delegate_object[:menu_chrome_format], option_value)
  else
    option_value
  end
end

#output_color_formatted(data_sym, color_sym) ⇒ Object



1459
1460
1461
1462
1463
# File 'lib/hash_delegator.rb', line 1459

def output_color_formatted(data_sym, color_sym)
  formatted_string = string_send_color(@delegate_object[data_sym],
                                       color_sym)
  @fout.fout formatted_string
end

#output_execution_resultObject



1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
# File 'lib/hash_delegator.rb', line 1465

def output_execution_result
  @fout.fout fetch_color(data_sym: :execution_report_preview_head,
                         color_sym: :execution_report_preview_frame_color)
  [
    ['Block', @run_state.script_block_name],
    ['Command', ([MarkdownExec::BIN_NAME, @delegate_object[:filename]] +
                 (@run_state.link_history.map { |item|
                    item[:block_name]
                  }) +
                 [@run_state.script_block_name]).join(' ')],
    ['Script', @run_state.saved_filespec],
    ['StdOut', @delegate_object[:logged_stdout_filespec]]
  ].each do |label, value|
    next unless value

    output_labeled_value(label, value, DISPLAY_LEVEL_ADMIN)
  end
  @fout.fout fetch_color(data_sym: :execution_report_preview_tail,
                         color_sym: :execution_report_preview_frame_color)
end

#output_execution_summaryObject



1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
# File 'lib/hash_delegator.rb', line 1486

def output_execution_summary
  return unless @delegate_object[:output_execution_summary]

  fout_section 'summary', {
    execute_aborted_at: @run_state.aborted_at,
    execute_completed_at: @run_state.completed_at,
    execute_error: @run_state.error,
    execute_error_message: @run_state.error_message,
    execute_files: @run_state.files,
    execute_options: @run_state.options,
    execute_started_at: @run_state.started_at,
    script_block_name: @run_state.script_block_name,
    saved_filespec: @run_state.saved_filespec
  }
end

#output_labeled_value(label, value, level) ⇒ Object



1502
1503
1504
1505
1506
1507
1508
1509
# File 'lib/hash_delegator.rb', line 1502

def output_labeled_value(label, value, level)
  @fout.lout format_references_send_color(
    context: { name: string_send_color(label, :output_execution_label_name_color),
               value: string_send_color(value.to_s,
                                        :output_execution_label_value_color) },
    format_sym: :output_execution_label_format
  ), level: level
end

#pop_add_current_code_to_head_and_trigger_load(link_state, block_names, code_lines, dependencies, selected) ⇒ Object



1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
# File 'lib/hash_delegator.rb', line 1511

def pop_add_current_code_to_head_and_trigger_load(link_state, block_names, code_lines,
                                                  dependencies, selected)
  pop = @link_history.pop # updatable
  if pop.document_filename
    next_state = LinkState.new(
      block_name: pop.block_name,
      document_filename: pop.document_filename,
      inherited_block_names:
       (pop.inherited_block_names + block_names).sort.uniq,
      inherited_dependencies:
       dependencies.merge(pop.inherited_dependencies || {}), ### merge, not replace, key data
      inherited_lines:
       HashDelegator.code_merge(pop.inherited_lines, code_lines)
    )
    @link_history.push(next_state)

    next_state.block_name = nil
    LoadFileLinkState.new(LoadFile::Load, next_state)
  else
    # no history exists; must have been called independently => retain script
    link_history_push_and_next(
      curr_block_name: selected[:oname],
      curr_document_filename: @delegate_object[:filename],
      inherited_block_names: ((link_state&.inherited_block_names || []) + block_names).sort.uniq,
      inherited_dependencies: (link_state&.inherited_dependencies || {}).merge(dependencies || {}), ### merge, not replace, key data
      inherited_lines: HashDelegator.code_merge(link_state&.inherited_lines, code_lines),
      next_block_name: '', # not link_block_data[LinkKeys::Block] || ''
      next_document_filename: @delegate_object[:filename], # not next_document_filename
      next_load_file: LoadFile::Reuse # not next_document_filename == @delegate_object[:filename] ? LoadFile::Reuse : LoadFile::Load
    )
    # LoadFileLinkState.new(LoadFile::Reuse, link_state)
  end
end

This method handles the back-link operation in the Markdown execution context. It updates the history state and prepares to load the next block.

Returns:



1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
# File 'lib/hash_delegator.rb', line 1549

def pop_link_history_and_trigger_load
  pop = @link_history.pop
  peek = @link_history.peek
  LoadFileLinkState.new(LoadFile::Load, LinkState.new(
                                          document_filename: pop.document_filename,
                                          inherited_block_names: peek.inherited_block_names,
                                          inherited_dependencies: peek.inherited_dependencies,
                                          inherited_lines: peek.inherited_lines
                                        ))
end

#post_execution_processObject



1560
1561
1562
1563
1564
# File 'lib/hash_delegator.rb', line 1560

def post_execution_process
  do_save_execution_output
  output_execution_summary
  output_execution_result
end

#prepare_blocks_menu(menu_blocks) ⇒ Array<Hash>

Prepare the blocks menu by adding labels and other necessary details.

Parameters:

  • all_blocks (Array<Hash>)

    The list of blocks from the file.

  • opts (Hash)

    The options hash.

Returns:



1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
# File 'lib/hash_delegator.rb', line 1571

def prepare_blocks_menu(menu_blocks)
  menu_blocks.map do |fcb|
    next if Filter.prepared_not_in_menu?(@delegate_object, fcb,
                                         %i[block_name_include_match block_name_wrapper_match])

    fcb.merge!(
      name: fcb.dname,
      label: BlockLabel.make(
        body: fcb[:body],
        filename: @delegate_object[:filename],
        headings: fcb.fetch(:headings, []),
        menu_blocks_with_docname: @delegate_object[:menu_blocks_with_docname],
        menu_blocks_with_headings: @delegate_object[:menu_blocks_with_headings],
        text: fcb[:text],
        title: fcb[:title]
      )
    )
    fcb.to_h
  end.compact
end


1592
1593
1594
1595
1596
# File 'lib/hash_delegator.rb', line 1592

def print_formatted_option(key, value)
  formatted_str = format(@delegate_object[:menu_opts_set_format],
                         { key: key, value: value })
  print string_send_color(formatted_str, :menu_opts_set_color)
end

#process_block_based_on_type(blocks, btype, fcb) ⇒ Object

private



1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
# File 'lib/hash_delegator.rb', line 1600

def process_block_based_on_type(blocks, btype, fcb)
  case btype
  when :blocks
    blocks.push(get_block_summary(fcb))
  when :filter
    %i[blocks line]
  when :line
    create_and_add_chrome_blocks(blocks, fcb) unless @delegate_object[:no_chrome]
  end
end

#process_string_array(arr, begin_pattern: nil, end_pattern: nil, scan1: nil, format1: nil) ⇒ Object



1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
# File 'lib/hash_delegator.rb', line 1611

def process_string_array(arr, begin_pattern: nil, end_pattern: nil, scan1: nil,
                         format1: nil)
  in_block = !begin_pattern.present?
  collected_lines = []

  arr.each do |line|
    if in_block
      if end_pattern.present? && line.match?(end_pattern)
        in_block = false
      elsif scan1.present?
        if format1.present?
          caps = extract_named_captures_from_option(line, scan1)
          if caps
            formatted = format(format1, caps)
            collected_lines << formatted
          end
        else
          caps = line.match(scan1)
          if caps
            formatted = caps[0]
            collected_lines << formatted
          end
        end
      else
        collected_lines << line
      end
    elsif begin_pattern.present? && line.match?(begin_pattern)
      in_block = true
    end
  end

  collected_lines
end

#prompt_approve_repeatObject



1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
# File 'lib/hash_delegator.rb', line 1645

def prompt_approve_repeat
  sel = @prompt.select(
    string_send_color(@delegate_object[:prompt_debounce],
                      :prompt_color_after_script_execution),
    default: @delegate_object[:prompt_no],
    filter: true,
    quiet: true
  ) do |menu|
    menu.choice @delegate_object[:prompt_yes]
    menu.choice @delegate_object[:prompt_no]
    menu.choice @delegate_object[:prompt_uninterrupted]
  end
  return false if sel == @delegate_object[:prompt_no]
  return true if sel == @delegate_object[:prompt_yes]

  @allowed_execution_block = @prior_execution_block
  true
rescue TTY::Reader::InputInterrupt
  exit 1
end

#prompt_for_filespec_with_wildcard(filespec) ⇒ Object

prompt user to enter a path (i.e. containing a path separator) or name to substitute into the wildcard expression



1317
1318
1319
1320
1321
1322
# File 'lib/hash_delegator.rb', line 1317

def prompt_for_filespec_with_wildcard(filespec)
  puts format(@delegate_object[:prompt_show_expr_format],
              { expr: filespec })
  puts @delegate_object[:prompt_enter_filespec]
  PathUtils.resolve_path_or_substitute(gets.chomp, filespec)
end

#prompt_for_user_approval(required_lines:, selected:) ⇒ Boolean

Presents a menu to the user for approving an action and performs additional tasks based on the selection. The function provides options for approval, rejection, copying data to clipboard, or saving data to a file.

Parameters:

  • opts (Hash)

    A hash containing various options for the menu.

  • required_lines (Array<String>)

    Lines of text or code that are subject to user approval.

Returns:

  • (Boolean)

    Returns true if the user approves (selects ‘Yes’), false otherwise.



1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
# File 'lib/hash_delegator.rb', line 1681

def prompt_for_user_approval(required_lines:, selected:)
  # Present a selection menu for user approval.
  sel = @prompt.select(
    string_send_color(@delegate_object[:prompt_approve_block],
                      :prompt_color_after_script_execution),
    filter: true
  ) do |menu|
    # sel = @prompt.select(@delegate_object[:prompt_approve_block], filter: true) do |menu|
    menu.default MenuOptions::YES
    menu.choice @delegate_object[:prompt_yes], MenuOptions::YES
    menu.choice @delegate_object[:prompt_no], MenuOptions::NO
    menu.choice @delegate_object[:prompt_script_to_clipboard],
                MenuOptions::SCRIPT_TO_CLIPBOARD
    menu.choice @delegate_object[:prompt_save_script],
                MenuOptions::SAVE_SCRIPT
  end

  if sel == MenuOptions::SCRIPT_TO_CLIPBOARD
    copy_to_clipboard(required_lines)
  elsif sel == MenuOptions::SAVE_SCRIPT
    save_to_file(required_lines: required_lines, selected: selected)
  end

  sel == MenuOptions::YES
rescue TTY::Reader::InputInterrupt
  exit 1
end

#prompt_select_code_filename(filenames) ⇒ Object

public



1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
# File 'lib/hash_delegator.rb', line 1726

def prompt_select_code_filename(filenames)
  @prompt.select(
    string_send_color(@delegate_object[:prompt_select_code_file],
                      :prompt_color_after_script_execution),
    filter: true,
    quiet: true
  ) do |menu|
    filenames.each do |filename|
      menu.choice filename
    end
  end
rescue TTY::Reader::InputInterrupt
  exit 1
end

#prompt_select_continueObject



1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
# File 'lib/hash_delegator.rb', line 1709

def prompt_select_continue
  sel = @prompt.select(
    string_send_color(@delegate_object[:prompt_after_script_execution],
                      :prompt_color_after_script_execution),
    filter: true,
    quiet: true
  ) do |menu|
    menu.choice @delegate_object[:prompt_yes]
    menu.choice @delegate_object[:prompt_exit]
  end
  sel == @delegate_object[:prompt_exit] ? MenuState::EXIT : MenuState::CONTINUE
rescue TTY::Reader::InputInterrupt
  exit 1
end

#prompt_user_exit(block_name_from_cli:, selected:) ⇒ Object

user prompt to exit if the menu will be displayed again



2048
2049
2050
2051
2052
2053
# File 'lib/hash_delegator.rb', line 2048

def prompt_user_exit(block_name_from_cli:, selected:)
  !block_name_from_cli &&
    selected[:shell] == BlockType::BASH &&
    @delegate_object[:pause_after_script_execution] &&
    prompt_select_continue == MenuState::EXIT
end

Handles the processing of a link block in Markdown Execution. It loads YAML data from the link_block_body content, pushes the state to history, sets environment variables, and decides on the next block to load.

Parameters:

  • link_block_body (Array<String>) (defaults to: [])

    The body content as an array of strings.

  • mdoc (Object) (defaults to: nil)

    Markdown document object.

  • selected (FCB) (defaults to: FCB.new)

    Selected code block.

Returns:



1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
# File 'lib/hash_delegator.rb', line 1749

def push_link_history_and_trigger_load(link_block_body: [], mdoc: nil, selected: FCB.new,
                                       link_state: LinkState.new, block_source: {})
  link_block_data = HashDelegator.parse_yaml_data_from_body(link_block_body)

  ## collect blocks specified by block
  #
  if mdoc
    code_info = mdoc.collect_recursively_required_code(
      anyname: selected[:oname],
      label_format_above: @delegate_object[:shell_code_label_format_above],
      label_format_below: @delegate_object[:shell_code_label_format_below],
      block_source: block_source
    )
    code_lines = code_info[:code]
    block_names = code_info[:block_names]
    dependencies = code_info[:dependencies]
  else
    block_names = []
    code_lines = []
    dependencies = {}
  end

  # load key and values from link block into current environment
  #
  if link_block_data[LinkKeys::Vars]
    code_lines.push BashCommentFormatter.format_comment(selected[:oname])
    (link_block_data[LinkKeys::Vars] || []).each do |(key, value)|
      ENV[key] = value.to_s
      code_lines.push(assign_key_value_in_bash(key, value))
    end
  end

  ## append blocks loaded, apply LinkKeys::Eval
  #
  if (load_expr = link_block_data.fetch(LinkKeys::Load, '')).present?
    load_filespec = load_filespec_from_expression(load_expr)
    code_lines += File.readlines(load_filespec, chomp: true) if load_filespec
  end

  # if an eval link block, evaluate code_lines and return its standard output
  #
  if link_block_data.fetch(LinkKeys::Eval,
                           false) || link_block_data.fetch(LinkKeys::Exec, false)
    code_lines = link_block_data_eval(link_state, code_lines, selected, link_block_data, block_source: block_source)
  end

  next_document_filename = write_inherited_lines_to_file(link_state, link_block_data)

  if link_block_data[LinkKeys::Return]
    pop_add_current_code_to_head_and_trigger_load(link_state, block_names, code_lines,
                                                  dependencies, selected)

  else
    link_history_push_and_next(
      curr_block_name: selected[:oname],
      curr_document_filename: @delegate_object[:filename],
      inherited_block_names: ((link_state&.inherited_block_names || []) + block_names).sort.uniq,
      inherited_dependencies: (link_state&.inherited_dependencies || {}).merge(dependencies || {}), ### merge, not replace, key data
      inherited_lines: HashDelegator.code_merge(link_state&.inherited_lines, code_lines),
      next_block_name: link_block_data.fetch(LinkKeys::NextBlock,
                                             nil) || link_block_data[LinkKeys::Block] || '',
      next_document_filename: next_document_filename,
      next_load_file: next_document_filename == @delegate_object[:filename] ? LoadFile::Reuse : LoadFile::Load
    )
  end
end

#puts_gets_oprompt_(filespec) ⇒ Object

Handle expression with wildcard characters allow user to select or enter



1308
1309
1310
1311
1312
1313
# File 'lib/hash_delegator.rb', line 1308

def puts_gets_oprompt_(filespec)
  puts format(@delegate_object[:prompt_show_expr_format],
              { expr: filespec })
  puts @delegate_object[:prompt_enter_filespec]
  gets.chomp
end

#read_show_options_and_trigger_reuse(selected:, link_state: LinkState.new) ⇒ LoadFileLinkState

Processes YAML data from the selected menu item, updating delegate objects and optionally printing formatted output.

Parameters:

  • selected (Hash)

    Selected item from the menu containing a YAML body.

  • tgt2 (Hash, nil)

    An optional target hash to update with YAML data.

Returns:



2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
# File 'lib/hash_delegator.rb', line 2301

def read_show_options_and_trigger_reuse(selected:, link_state: LinkState.new)
  obj = {}
  data = YAML.load(selected[:body].join("\n"))
  (data || []).each do |key, value|
    sym_key = key.to_sym
    obj[sym_key] = value

    print_formatted_option(key, value) if @delegate_object[:menu_opts_set_format].present?
  end

  link_state.block_name = nil
  OpenStruct.new(options: obj,
                 load_file_link_state: LoadFileLinkState.new(
                   LoadFile::Reuse, link_state
                 ))
end

#runtime_exception(exception_sym, name, items) ⇒ Object



1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
# File 'lib/hash_delegator.rb', line 1816

def runtime_exception(exception_sym, name, items)
  if @delegate_object[exception_sym] != 0
    data = { name: name, detail: items.join(', ') }
    warn(
      format(
        @delegate_object.fetch(:exception_format_name, "\n%{name}"),
        data
      ).send(@delegate_object.fetch(:exception_color_name, :red)) +
      format(
        @delegate_object.fetch(:exception_format_detail, " - %{detail}\n"),
        data
      ).send(@delegate_object.fetch(:exception_color_detail, :yellow))
    )
  end
  return unless (@delegate_object[exception_sym]).positive?

  exit @delegate_object[exception_sym]
end

#save_filespec_from_expression(expression) ⇒ Object



1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
# File 'lib/hash_delegator.rb', line 1262

def save_filespec_from_expression(expression)
  # Process expression with embedded formatting
  formatted = formatted_expression(expression)

  # Handle wildcards or direct file specification
  if contains_wildcards?(formatted)
    save_filespec_wildcard_expansion(formatted)
  else
    formatted
  end
end

#save_filespec_wildcard_expansion(filespec) ⇒ Object

Handle expression with wildcard characters allow user to select or enter



1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
# File 'lib/hash_delegator.rb', line 1326

def save_filespec_wildcard_expansion(filespec)
  files = find_files(filespec)
  case files.count
  when 0
    prompt_for_filespec_with_wildcard(filespec)
  else
    ## user selects from existing files or other
    # input into path with wildcard for easy entry
    #
    name = prompt_select_code_filename([@delegate_object[:prompt_filespec_other]] + files)
    if name == @delegate_object[:prompt_filespec_other]
      prompt_for_filespec_with_wildcard(filespec)
    else
      name
    end
  end
end

#save_to_file(required_lines:, selected:) ⇒ Object



1835
1836
1837
1838
# File 'lib/hash_delegator.rb', line 1835

def save_to_file(required_lines:, selected:)
  write_command_file(required_lines: required_lines, selected: selected)
  @fout.fout "File saved: #{@run_state.saved_filespec}"
end

#select_option_with_metadata(prompt_text, names, opts = {}) ⇒ Object

Presents a TTY prompt to select an option or exit, returns metadata including option and selected



2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
# File 'lib/hash_delegator.rb', line 2122

def (prompt_text, names, opts = {})

  ## configure to environment
  #
  unless opts[:select_page_height].positive?
    require 'io/console'
    opts[:per_page] = opts[:select_page_height] = [IO.console.winsize[0] - 3, 4].max
  end

  selection = @prompt.select(prompt_text,
                             names,
                             opts.merge(filter: true))
  item = names.find do |item|
    if item.instance_of?(String)
      item == selection
    else
      item[:dname] == selection
    end
  end
  item = { dname: item } if item.instance_of?(String)
  unless item
    HashDelegator.error_handler('select_option_with_metadata', error: 'menu item not found')
    exit 1
  end

  item.merge(
    if selection == menu_chrome_colored_option(:menu_option_back_name)
      { option: selection, shell: BlockType::LINK }
    elsif selection == menu_chrome_colored_option(:menu_option_exit_name)
      { option: selection }
    else
      { selected: selection }
    end
  )
rescue TTY::Reader::InputInterrupt
  exit 1
rescue StandardError
  HashDelegator.error_handler('select_option_with_metadata')
end

#set_delob_filename_block_name(link_state:, block_name_from_cli:) ⇒ Object

Update the block name in the link state and delegate object.

This method updates the block name based on whether it was specified through the CLI or derived from the link state.

Parameters:

  • link_state (LinkState)

    The current link state object.

  • block_name_from_cli (Boolean)

    Indicates if the block name is from CLI.



2078
2079
2080
2081
2082
# File 'lib/hash_delegator.rb', line 2078

def set_delob_filename_block_name(link_state:, block_name_from_cli:)
  @delegate_object[:filename] = link_state.document_filename
  link_state.block_name = @delegate_object[:block_name] =
    block_name_from_cli ? @cli_block_name : link_state.block_name
end

#set_delobj_menu_loop_vars(block_name_from_cli:, now_using_cli:, link_state:) ⇒ Object



2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
# File 'lib/hash_delegator.rb', line 2030

def set_delobj_menu_loop_vars(block_name_from_cli:, now_using_cli:, link_state:)
  block_name_from_cli, now_using_cli = \
    manage_cli_selection_state(block_name_from_cli: block_name_from_cli,
                               now_using_cli: now_using_cli,
                               link_state: link_state)
  set_delob_filename_block_name(link_state: link_state,
                                block_name_from_cli: block_name_from_cli)

  # update @delegate_object and @menu_base_options in auto_load
  #
  blocks_in_file, menu_blocks, mdoc = mdoc_menu_and_blocks_from_nested_files(link_state)
  dump_delobj(blocks_in_file, menu_blocks, link_state)

  [block_name_from_cli, now_using_cli, blocks_in_file, menu_blocks, mdoc]
end

#set_environment_variables_for_block(selected) ⇒ Object



2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
# File 'lib/hash_delegator.rb', line 2162

def set_environment_variables_for_block(selected)
  code_lines = []
  YAML.load(selected[:body].join("\n"))&.each do |key, value|
    ENV[key] = value.to_s

    require 'shellwords'
    code_lines.push "#{key}=\"#{Shellwords.escape(value)}\""

    next unless @delegate_object[:menu_vars_set_format].present?

    formatted_string = format(@delegate_object[:menu_vars_set_format],
                              { key: key, value: value })
    print string_send_color(formatted_string, :menu_vars_set_color)
  end
  code_lines
end

#should_add_back_option?Boolean

Returns:

  • (Boolean)


2179
2180
2181
# File 'lib/hash_delegator.rb', line 2179

def should_add_back_option?
  @delegate_object[:menu_with_back] && @link_history.prior_state_exist?
end

#start_fenced_block(line, headings, fenced_start_extended_regex) ⇒ MarkdownExec::FCB

Initializes a new fenced code block (FCB) object based on the provided line and heading information.

Parameters:

  • line (String)

    The line initiating the fenced block.

  • headings (Array<String>)

    Current headings hierarchy.

  • fenced_start_extended_regex (Regexp)

    Regular expression to identify fenced block start.

Returns:



2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
# File 'lib/hash_delegator.rb', line 2188

def start_fenced_block(line, headings, fenced_start_extended_regex)
  fcb_title_groups = line.match(fenced_start_extended_regex).named_captures.sym_keys
  rest = fcb_title_groups.fetch(:rest, '')
  reqs, wraps =
    ArrayUtil.partition_by_predicate(rest.scan(/\+[^\s]+/).map do |req|
                                       req[1..-1]
                                     end) do |name|
    !name.match(Regexp.new(@delegate_object[:block_name_wrapper_match]))
  end

  dname = oname = title = ''
  nickname = nil
  if @delegate_object[:block_name_nick_match].present? && oname =~ Regexp.new(@delegate_object[:block_name_nick_match])
    nickname = $~[0]
  else
    dname = oname = title = fcb_title_groups.fetch(:name, '')
  end

  MarkdownExec::FCB.new(
    body: [],
    call: rest.match(Regexp.new(@delegate_object[:block_calls_scan]))&.to_a&.first,
    dname: dname,
    headings: headings,
    indent: fcb_title_groups.fetch(:indent, ''),
    nickname: nickname,
    oname: oname,
    reqs: reqs,
    shell: fcb_title_groups.fetch(:shell, ''),
    stdin: if (tn = rest.match(/<(?<type>\$)?(?<name>[A-Za-z_-]\S+)/))
             tn.named_captures.sym_keys
           end,
    stdout: if (tn = rest.match(/>(?<type>\$)?(?<name>[A-Za-z_\-.\w]+)/))
              tn.named_captures.sym_keys
            end,
    title: title,
    wraps: wraps
  )
end

#string_send_color(string, color_sym) ⇒ String

Applies a color method to a string based on the provided color symbol. The color method is fetched from @delegate_object and applied to the string.

Parameters:

  • string (String)

    The string to which the color will be applied.

  • color_sym (Symbol)

    The symbol representing the color method.

  • default (String)

    Default color method to use if color_sym is not found in @delegate_object.

Returns:

  • (String)

    The string with the applied color method.



2233
2234
2235
# File 'lib/hash_delegator.rb', line 2233

def string_send_color(string, color_sym)
  HashDelegator.apply_color_from_hash(string, @delegate_object, color_sym)
end

#update_line_and_block_state(nested_line, state, selected_messages, &block) ⇒ Void

Processes an individual line within a loop, updating headings and handling fenced code blocks. This function is designed to be called within a loop that iterates through each line of a document.

Parameters:

  • line (String)

    The current line being processed.

  • state (Hash)

    The current state of the parser, including flags and data related to the processing.

  • opts (Hash)

    A hash containing various options for line and block processing.

  • selected_messages (Array<String>)

    Accumulator for lines or messages that are subject to further processing.

  • block (Proc)

    An optional block for further processing or transformation of lines.

Options Hash (state):

  • :headings (Array<String>)

    Current headings to be updated based on the line.

  • :fenced_start_and_end_regex (Regexp)

    Regular expression to match the start and end of a fenced block.

  • :in_fenced_block (Boolean)

    Flag indicating whether the current line is inside a fenced block.

  • :fcb (Object)

    An object representing the current fenced code block being processed.

Returns:

  • (Void)

    The function modifies the ‘state` and `selected_messages` arguments in place.



2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
# File 'lib/hash_delegator.rb', line 2256

def update_line_and_block_state(nested_line, state, selected_messages,
                                &block)
  line = nested_line.to_s
  if line.match(@delegate_object[:fenced_start_and_end_regex])
    if state[:in_fenced_block]
      ## end of code block
      #
      HashDelegator.update_menu_attrib_yield_selected(
        fcb: state[:fcb],
        messages: selected_messages,
        configuration: @delegate_object,
                                                      &block
      )
      state[:in_fenced_block] = false
    else
      ## start of code block
      #
      state[:fcb] =
        start_fenced_block(line, state[:headings],
                           @delegate_object[:fenced_start_extended_regex])
      state[:fcb][:depth] = nested_line[:depth]
      state[:in_fenced_block] = true
    end
  elsif state[:in_fenced_block] && state[:fcb].body
    ## add line to fenced code block
    # remove fcb indent if possible
    #
    state[:fcb].body += [
      line.chomp.sub(/^#{state[:fcb].indent}/, '')
    ]
  elsif nested_line[:depth].zero? || @delegate_object[:menu_include_imported_notes]
    # add line if it is depth 0 or option allows it
    #
    HashDelegator.yield_line_if_selected(line, selected_messages, &block)

  else
    # &bsp 'line is not recognized for block state'

  end
end

#wait_for_stream_processingObject



2318
2319
2320
2321
2322
# File 'lib/hash_delegator.rb', line 2318

def wait_for_stream_processing
  @process_mutex.synchronize do
    @process_cv.wait(@process_mutex)
  end
end

#wait_for_user_selected_block(all_blocks, menu_blocks, default) ⇒ Object



2324
2325
2326
2327
2328
2329
2330
# File 'lib/hash_delegator.rb', line 2324

def wait_for_user_selected_block(all_blocks, menu_blocks, default)
  block_state = wait_for_user_selection(all_blocks, menu_blocks, default)
  handle_back_or_continue(block_state)
  block_state
rescue StandardError
  HashDelegator.error_handler('wait_for_user_selected_block')
end

#wait_for_user_selection(_all_blocks, menu_blocks, default) ⇒ Object



2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
# File 'lib/hash_delegator.rb', line 2332

def wait_for_user_selection(_all_blocks, menu_blocks, default)
  prompt_title = string_send_color(
    @delegate_object[:prompt_select_block].to_s, :prompt_color_after_script_execution
  )

  block_menu = prepare_blocks_menu(menu_blocks)
  return SelectedBlockMenuState.new(nil, MenuState::EXIT) if block_menu.empty?

  # default value may not match if color is different from originating menu (opts changed while processing)
  selection_opts = if default && menu_blocks.map(&:dname).include?(default)
                     @delegate_object.merge(default: default)
                   else
                     @delegate_object
                   end

  sph = @delegate_object[:select_page_height]
  selection_opts.merge!(per_page: sph)

  selected_option = (prompt_title, block_menu,
                                                selection_opts)
  determine_block_state(selected_option)
end

#write_command_file(required_lines:, selected:) ⇒ Object

Handles the core logic for generating the command file’s metadata and content.



2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
# File 'lib/hash_delegator.rb', line 2356

def write_command_file(required_lines:, selected:)
  return unless @delegate_object[:save_executed_script]

  time_now = Time.now.utc
  @run_state.saved_script_filename =
    SavedAsset.script_name(
      blockname: selected[:nickname] || selected[:oname],
      filename: @delegate_object[:filename],
      prefix: @delegate_object[:saved_script_filename_prefix],
      time: time_now
    )
  @run_state.saved_filespec =
    File.join(@delegate_object[:saved_script_folder],
              @run_state.saved_script_filename)

  shebang = if @delegate_object[:shebang]&.present?
              "#{@delegate_object[:shebang]} #{@delegate_object[:shell]}\n"
            else
              ''
            end

  content = shebang +
            "# file_name: #{@delegate_object[:filename]}\n" \
            "# block_name: #{@delegate_object[:block_name]}\n" \
            "# time: #{time_now}\n" \
            "#{required_lines.flatten.join("\n")}\n"

  HashDelegator.create_file_and_write_string_with_permissions(
    @run_state.saved_filespec,
    content,
    @delegate_object[:saved_script_chmod]
  )
rescue StandardError
  HashDelegator.error_handler('write_command_file')
end

#write_inherited_lines_to_file(link_state, link_block_data) ⇒ Object



2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
# File 'lib/hash_delegator.rb', line 2392

def write_inherited_lines_to_file(link_state, link_block_data)
  save_expr = link_block_data.fetch(LinkKeys::Save, '')
  if save_expr.present?
    save_filespec = save_filespec_from_expression(save_expr)
    File.write(save_filespec, HashDelegator.join_code_lines(link_state&.inherited_lines))
    @delegate_object[:filename]
  else
    link_block_data[LinkKeys::File] || @delegate_object[:filename]
  end
end