Module: HashDelegatorSelf

Included in:
MarkdownExec::HashDelegatorParent
Defined in:
lib/hash_delegator.rb

Instance Method Summary collapse

Instance Method Details

#apply_color_from_hash(string, color_methods, color_key, default_method: 'plain') ⇒ String

Applies an ANSI color method to a string using a specified color key. The method retrieves the color method from the provided hash. If the color key is not present in the hash, it uses a default color method.

Parameters:

  • string (String)

    The string to be colored.

  • color_methods (Hash)

    A hash where keys are color names (String/Symbol) and values are color methods.

  • color_key (String, Symbol)

    The key representing the desired

    color method in the color_methods hash.
    
  • default_method (String) (defaults to: 'plain')

    (optional) Default color method to use if color_key is not found in color_methods. Defaults to ‘plain’.

Returns:

  • (String)

    The colored string.



67
68
69
70
71
# File 'lib/hash_delegator.rb', line 67

def apply_color_from_hash(string, color_methods, color_key,
                          default_method: 'plain')
  color_method = color_methods.fetch(color_key, default_method).to_sym
  AnsiString.new(string.to_s).send(color_method)
end

#block_find(blocks, msg, value, default = nil) ⇒ Object?

Searches for the first element in a collection where the specified message sent to an element matches a given value. This method is particularly useful for finding a specific hash-like object within an enumerable collection. If no match is found, it returns a specified default value.

Parameters:

  • blocks (Enumerable)

    The collection of hash-like objects to search.

  • msg (Symbol, String)

    The message to send to each element of the collection.

  • value (Object)

    The value to match against the result of the message sent to each element.

  • default (Object, nil) (defaults to: nil)

    The default value to return if no match is found (optional).

Returns:

  • (Object, nil)

    The first matching element or the default value if no match is found.



89
90
91
# File 'lib/hash_delegator.rb', line 89

def block_find(blocks, msg, value, default = nil)
  blocks.find { |item| item.send(msg) == value } || default
end

#block_match(blocks, msg, value, default = nil) ⇒ Object



93
94
95
# File 'lib/hash_delegator.rb', line 93

def block_match(blocks, msg, value, default = nil)
  blocks.select { |item| value =~ item.send(msg) }
end

#block_select(blocks, msg, value, default = nil) ⇒ Object



97
98
99
# File 'lib/hash_delegator.rb', line 97

def block_select(blocks, msg, value, default = nil)
  blocks.select { |item| item.send(msg) == value }
end

#chrome_block_criteriaObject



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/hash_delegator.rb', line 101

def chrome_block_criteria
  [
    { center: :table_center,         format: :menu_note_format,
      match: :table_row_multi_line_match, type: BlockType::TEXT },
    { case_conversion: :upcase,      center: :heading1_center,
      collapse: :heading1_collapse,  collapsible: :heading1_collapsible,
      color: :menu_heading1_color,   format: :menu_heading1_format,      level: 1,
      match: :heading1_match,        type: BlockType::HEADING,           wrap: true },
    { center: :heading2_center,
      collapse: :heading2_collapse,  collapsible: :heading2_collapsible,
      color: :menu_heading2_color,   format: :menu_heading2_format,      level: 2,
      match: :heading2_match,        type: BlockType::HEADING,           wrap: true },
    { case_conversion: :downcase,    center: :heading3_center,
      collapse: :heading3_collapse,  collapsible: :heading3_collapsible,
      color: :menu_heading3_color,   format: :menu_heading3_format,      level: 3,
      match: :heading3_match,        type: BlockType::HEADING,           wrap: true },
    { center: :divider4_center,
      collapse: :divider4_collapse, collapsible: :divider4_collapsible,
      color: :menu_divider_color,    format: :menu_divider_format, level: 4,
      match: :divider_match,         type: BlockType::DIVIDER                       },
    { color: :menu_note_color,       format: :menu_note_format,
      match: :menu_note_match,       type: BlockType::TEXT,              wrap: true },
    { color: :menu_task_color,       format: :menu_task_format,
      match: :menu_task_match,       type: BlockType::TEXT,              wrap: true }
  ]
end

#count_matches_in_lines(lines, regex) ⇒ Object



128
129
130
# File 'lib/hash_delegator.rb', line 128

def count_matches_in_lines(lines, regex)
  lines.count { |line| line.to_s.match(regex) }
end

#create_directory_for_file(file_path) ⇒ Object



132
133
134
# File 'lib/hash_delegator.rb', line 132

def create_directory_for_file(file_path)
  FileUtils.mkdir_p(File.dirname(file_path))
end

#create_file_and_write_string_with_permissions(file_path, content, chmod_value) ⇒ Object

Creates a file at the specified path, writes the given

content to it, and sets file permissions if required.

Handles any errors encountered during the process.

Parameters:

  • file_path (String)

    The path where the file will be created.

  • content (String)

    The content to write into the file.

  • chmod_value (Integer)

    The file permission value to set; skips if zero.



145
146
147
148
149
150
151
152
# File 'lib/hash_delegator.rb', line 145

def create_file_and_write_string_with_permissions(file_path, content,
                                                  chmod_value)
  create_directory_for_file(file_path)
  File.write(file_path, content)
  set_file_permissions(file_path, chmod_value) unless chmod_value.zero?
rescue StandardError
  error_handler('create_file_and_write_string_with_permissions')
end

#default_block_title_from_body(fcb) ⇒ Object

Updates the title of an FCB object from its body content if the title is nil or empty.



160
161
162
163
164
# File 'lib/hash_delegator.rb', line 160

def default_block_title_from_body(fcb)
  return fcb.title unless fcb.title.nil? || fcb.title.empty?

  fcb.derive_title_from_body
end

#delete_consecutive_blank_lines!(blocks_menu) ⇒ Object

delete the current line if it is empty and the previous is also empty



167
168
169
170
171
172
173
174
175
# File 'lib/hash_delegator.rb', line 167

def delete_consecutive_blank_lines!(blocks_menu)
  blocks_menu.process_and_conditionally_delete! do |prev_item, current_item, _next_item|
    !current_item.is_split? &&
      prev_item&.fetch(:chrome, nil) &&
      !(prev_item && prev_item.oname.present?) &&
      current_item&.fetch(:chrome, nil) &&
      !(current_item && current_item.oname.present?)
  end
end

#error_handler(name = '', opts = {}, error: $!) ⇒ Object



177
178
179
180
181
182
# File 'lib/hash_delegator.rb', line 177

def error_handler(name = '', opts = {}, error: $!)
  Exceptions.error_handler(
    "HashDelegator.#{name} -- #{error}",
    opts
  )
end

#execute_bash_script_lines(transient_code: [], export: nil, export_name:, force: false, shell:, archive_script: false, archive_path_format: nil, archive_time_format: nil) ⇒ Array?

Note:

The method creates a temporary file with mode 0755 (executable) and automatically cleans it up after execution. If ‘@delegate_object` is true, the script will be copied to an archive location before execution.

Executes a bash script from an array of lines and optionally exports the result.

Creates a temporary executable file from the provided bash script lines, executes it using the configured shell, and optionally archives the script if archiving is enabled. The result can be marked as exportable based on the export configuration and command success status.

Examples:

Basic execution without export

result, exportable, new_lines = execute_bash_script_lines(
  transient_code: ["echo 'Hello'", "echo 'World'"],
  export: nil,
  force: false
)
# => [CommandResult, true, []]

Execution with export

export = OpenStruct.new(name: "MY_VAR", exportable: true)
result, exportable, new_lines = execute_bash_script_lines(
  transient_code: ["echo 'Hello World'"],
  export: export,
  force: true
)
# => [CommandResult, true, [{name: "MY_VAR", force: true, text: "Hello World\n"}]]

Parameters:

  • bash_script_lines (Array<String>)

    An array of strings representing the lines of the bash script to execute.

  • export (Object, nil) (defaults to: nil)

    An export configuration object that determines whether the result should be exported. If provided, must respond to:

    • ‘exportable` [Boolean, nil] Whether the result is exportable (nil defaults to true)

    • ‘name` [String] The name of the variable to export the result to

    If nil, the result will not be exported.

  • force (Boolean) (defaults to: false)

    Whether to force the export even if the variable already exists. This is included in the new_lines hash if exportable.

Returns:

  • (Array, nil)

    Returns an array with three elements:

    • 0
      CommandResult

      The result of executing the script, containing

      stdout and exit_status

    • 1
      Boolean

      Whether the result is exportable (true if export is nil

      or export.exportable is nil, otherwise based on export.exportable and command success)

    • 2
      Array<Hash>

      An array of hashes representing new lines to export.

      Each hash contains:

      • ‘:name` [String] The variable name

      • ‘:force` [Boolean] Whether to force the export

      • ‘:text` [String] The text content to export

    Returns nil if an error occurs during execution.



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# File 'lib/hash_delegator.rb', line 235

def execute_bash_script_lines(
  transient_code: [],
  export: nil,
  export_name:,
  force: false,
  shell:,
  archive_script: false, # @delegate_object[:archive_ad_hoc_scripts]
  archive_path_format: nil, # @delegate_object[:archive_path_format],
  archive_time_format: nil # @delegate_object[:archive_time_format]
)
  Tempfile.create('script_exec') do |temp_file|
    temp_file.write(join_code_lines(transient_code))
    temp_file.close # Close the file before chmod and execution
    File.chmod(0o755, temp_file.path)

    if archive_script && archive_path_format && archive_time_format
      archive_filename = format(
        archive_path_format,
        time: Time.now.strftime(archive_time_format)
      )
      `cp #{temp_file.path} #{archive_filename}`
    end

    tsc = TransformedShellCommand.new(
      "#{shell} #{temp_file.path}",
      regex: export.validate,
      format: export.transform
    )
    exportable = if export&.exportable.nil?
                   true
                 else
                   (export ? export.exportable : false)
                 end
    new_lines = []

    if false
      # optional comment
      new_lines << { comment: 'execute_bash_script_lines' }
    end

    exportable_success = exportable && tsc.success?
    if exportable_success
      new_lines << { name: export_name, force: force,
                     text: tsc.transformed_output }
    end

    CommandResult.new(
      exit_status: tsc.exit_code,
      exportable: exportable_success,
      new_lines: new_lines,
      script: transient_code,
      stdout: tsc.transformed_output,
      transformed_shell_command: tsc
    )
  end
rescue StandardError
  wwe $!, 'transient_code:', transient_code, 'export:', export
  # warn "Error executing script: #{err.message}"
  # return failure result
  CommandResult.new(
    exit_status: CommandResult::EXIT_STATUS_FAIL,
    exportable: false,
    new_lines: [],
    script: transient_code,
    stdout: ''
  )
end

#flatten_and_compact_arrays(*args) ⇒ Array

Takes multiple arrays as arguments, flattens them into a single array, and removes nil values.

Parameters:

  • args (Array<Array>)

    Variable number of arrays to be processed

Returns:

  • (Array)

    A single flattened array with nil values removed, or an empty array if the result is empty



306
307
308
309
# File 'lib/hash_delegator.rb', line 306

def flatten_and_compact_arrays(*args)
  merged = args.compact.flatten
  merged.empty? ? [] : merged
end

#indent_all_lines(body, indent = nil) ⇒ String

Indents all lines in a given string with a specified indentation string.

Parameters:

  • body (String)

    A multi-line string to be indented.

  • indent (String) (defaults to: nil)

    The string used for indentation (default is an empty string).

Returns:

  • (String)

    A single string with each line indented as specified.



316
317
318
319
320
# File 'lib/hash_delegator.rb', line 316

def indent_all_lines(body, indent = nil)
  return body unless indent&.present?

  body.lines.map { |line| indent + line.chomp }.join("\n")
end

#initialize_fcb_names(fcb) ⇒ Object



322
323
324
325
# File 'lib/hash_delegator.rb', line 322

def initialize_fcb_names(fcb)
  fcb.oname = fcb.dname = fcb.title || ''
  fcb.s2title = fcb.oname
end

#join_code_lines(lines) ⇒ Object



327
328
329
330
331
# File 'lib/hash_delegator.rb', line 327

def join_code_lines(lines)
  ((lines || []) + ['']).join("\n")
rescue StandardError
  wwe $!, 'lines:', lines
end


333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
# File 'lib/hash_delegator.rb', line 333

def next_link_state(
  block_name_from_cli:, was_using_cli:, block_state:, block_name: nil
)
  # Set block_name based on block_name_from_cli
  block_name = @cli_block_name if block_name_from_cli

  # Determine the state of breaker based on was_using_cli and the block type
  # true only when block_name is nil, block_name_from_cli is false,
  # was_using_cli is true, and the block_state.block.shell equals
  # BlockType::BASH. In all other scenarios, breaker is false.
  breaker = !block_name &&
            !block_name_from_cli &&
            was_using_cli &&
            block_state.block.type == BlockType::SHELL

  # Reset block_name_from_cli if the conditions are not met
  block_name_from_cli ||= false

  [block_name, block_name_from_cli, breaker]
end

#parse_yaml_data_from_body(body) ⇒ Object



354
355
356
357
358
359
# File 'lib/hash_delegator.rb', line 354

def parse_yaml_data_from_body(body)
  body&.any? ? YAML.load(body.join("\n")) : {}
rescue StandardError
  error_handler("parse_yaml_data_from_body for body: #{body}",
                { abort: true })
end

#persist_fcb_self(all_fcbs, options) ⇒ Object



567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
# File 'lib/hash_delegator.rb', line 567

def persist_fcb_self(all_fcbs, options)
  raise if all_fcbs.nil?

  # if the id is present, update the existing fcb
  if options[:id]
    fcb = all_fcbs.find { _1.id == options[:id] }
    if fcb
      fcb.update(options)
      return fcb
    end
  end
  MarkdownExec::FCB.new(options).tap do
    all_fcbs << _1
  end
end

#read_required_blocks_from_temp_file(temp_blocks_file_path) ⇒ Array<String>

Reads required code blocks from a temporary file specified

by an environment variable.

Returns:

  • (Array<String>)

    Lines read from the temporary file, or an empty array if file is not found or path is empty.



365
366
367
368
369
370
371
372
373
374
375
# File 'lib/hash_delegator.rb', line 365

def read_required_blocks_from_temp_file(temp_blocks_file_path)
  return [] if temp_blocks_file_path.to_s.empty?

  if File.exist?(temp_blocks_file_path)
    File.readlines(
      temp_blocks_file_path, chomp: true
    )
  else
    []
  end
end

#remove_file_without_standard_errors(path) ⇒ Object



377
378
379
# File 'lib/hash_delegator.rb', line 377

def remove_file_without_standard_errors(path)
  FileUtils.rm_f(path)
end

#safeval(str) ⇒ Object

Evaluates the given string as Ruby code within a safe context. If an error occurs, it calls the error_handler method with ‘safeval’.

Parameters:

  • str (String)

    The string to be evaluated.

Returns:

  • (Object)

    The result of evaluating the string.



385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
# File 'lib/hash_delegator.rb', line 385

def safeval(str)
  # # Restricting to evaluate only expressions
  # unless str.match?(/\A\s*\w+\s*[\+\-\*\/\=\%\&\|\<\>\!]+\s*\w+\s*\z/)
  #   error_handler('safeval') # 'Invalid expression'
  #   return
  # end

  # # Whitelisting allowed operations
  # allowed_methods = %w[+ - * / == != < > <= >= && || % &
  #  |]
  # unless allowed_methods.any? { |op| str.include?(op) }
  #   error_handler('safeval', 'Operation not allowed')
  #   return
  # end

  # # Sanitize input (example: removing potentially harmful characters)
  # str = str.gsub(/[^0-9\+\-\*\/\(\)\<\>\!\=\%\&\|]/, '')
  # Evaluate the sanitized string
  result = nil
  binding.eval("result = #{str}")

  result
rescue StandardError # catches NameError, StandardError
  pp $!, $@
  pp "code: #{str}"
  error_handler('safeval')
  exit 1
end

#set_file_permissions(file_path, chmod_value) ⇒ Object



414
415
416
# File 'lib/hash_delegator.rb', line 414

def set_file_permissions(file_path, chmod_value)
  File.chmod(chmod_value, file_path)
end

#tables_into_columns!(blocks_menu, delegate_object, screen_width_for_table) ⇒ Object

find tables in multiple lines and format horizontally



419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
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 419

def tables_into_columns!(blocks_menu, delegate_object, screen_width_for_table)
  return unless delegate_object[:tables_into_columns]

  lines = blocks_menu.map(&:oname)
  text_tables = TableExtractor.extract_tables(
    lines,
    regexp: delegate_object[:table_parse_regexp],
    multi_line_delimiter: delegate_object[:table_row_multi_line_delimiter],
    single_line_delimiter: delegate_object[:table_row_single_line_delimiter]
  )
  return unless text_tables.count.positive?

  text_tables.each do |table|
    next unless table[:columns].positive?

    range = table[:start_index]..(table[:start_index] + table[:rows] - 1)
    lines = blocks_menu[range].map(&:dname)
    table__hs = MarkdownTableFormatter.format_table__hs(
      column_count: table[:columns],
      decorate: {
        border: delegate_object[:table_border_color],
        header_row: if table[:rows] == 1
                      delegate_object[:table_row_color]
                    else
                      delegate_object[:table_header_row_color]
                    end,
        row: delegate_object[:table_row_color],
        separator_line: delegate_object[:table_separator_line_color]
      },
      lines: lines,
      max_table_width: screen_width_for_table,
      table: table,
      truncate: $table_cell_truncate
    )

    exceeded_table_cell = false # any cell in table is exceeded
    truncated_table_cell = false # any cell in table is truncated
    table__hs.each do |table_hs|
      table_hs.substrings.each do |substrings|
        substrings.each do |node|
          next unless node[:text].instance_of?(TrackedString)

          exceeded_table_cell ||= node[:text].exceeded
          truncated_table_cell = node[:text].truncated
          break if truncated_table_cell
        end
        break if truncated_table_cell
      end
      break if truncated_table_cell
    end

    unless table__hs.count == range.size
      raise 'Invalid result from MarkdownTableFormatter.format_table()'
    end

    # read indentation from first line
    indent = blocks_menu[range.first].oname.split('|', 2).first

    # replace text in each block
    range.each.with_index do |block_ind, ind|
      fcb = blocks_menu[block_ind]
      fcb.s3formatted_table_row = fcb.padded = table__hs[ind]
      fcb.padded_width = table__hs[ind].padded_width
      if fcb.center
        cw = (screen_width_for_table - table__hs[ind].padded_width) / 2
        if cw.positive?
          indent = ' ' * cw
          fcb.s3indent = fcb.indent = indent
        end
      else
        fcb.s3indent = fcb.indent
      end
      fcb.s3indent ||= ''
      fcb.dname = fcb.indented_decorated = fcb.s3indent + fcb.s3formatted_table_row.decorate

      if ind.zero?
        fcb.truncated_table_cell = truncated_table_cell
        if exceeded_table_cell
          fcb.delete_key(:disabled)
        end
      end
    end
  end
end

#tty_prompt_without_disabled_symbolTTY::Prompt

Creates a TTY prompt with custom settings. Specifically,

it disables the default 'cross' symbol and

defines a lambda function to handle interrupts.

Returns:

  • (TTY::Prompt)

    A new TTY::Prompt instance with specified configurations.



514
515
516
517
518
519
520
521
522
# File 'lib/hash_delegator.rb', line 514

def tty_prompt_without_disabled_symbol
  TTY::Prompt.new(
    interrupt: lambda {
      puts # next line in case not at start
      raise TTY::Reader::InputInterrupt
    },
    symbols: { cross: ' ' }
  )
end

#update_menu_attrib_yield_selected(fcb:, messages:, configuration: {}, &block) ⇒ Object

Updates the attributes of the given fcb object and

conditionally yields to a block.

It initializes fcb names and sets the default block title from fcb’s body. If the fcb has a body and meets certain conditions,

it yields to the given block.

Parameters:

  • fcb (Object)

    The fcb object whose attributes are to be updated.

  • selected_types (Array<Symbol>)

    A list of message types to determine if yielding is applicable.

  • block (Block)

    An optional block to yield to if conditions are met.



534
535
536
537
538
539
540
541
542
# File 'lib/hash_delegator.rb', line 534

def update_menu_attrib_yield_selected(fcb:, messages:, configuration: {},
                                      &block)
  initialize_fcb_names(fcb)
  return unless fcb.body

  default_block_title_from_body(fcb)
  MarkdownExec::Filter.yield_to_block_if_applicable(fcb, messages, configuration,
                                                    &block)
end

#yield_line_if_selected(line, selected_types, all_fcbs: nil, criteria: nil, source_id: '', &block) ⇒ Object

Yields a line as a new block if the selected message type includes :line.

Parameters:

  • line (String)

    The line to be processed.

  • selected_types (Array<Symbol>)

    A list of message types to check.

  • block (Proc)

    The block to be called with the line data.



548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
# File 'lib/hash_delegator.rb', line 548

def yield_line_if_selected(
  line, selected_types, all_fcbs: nil,
  criteria: nil, source_id: '', &block
)
  return unless block && block_type_selected?(selected_types, :line)

  opts = {
    block: nil,
    body: [line],
    id: source_id
  }
  # add style if it is a single line table
  opts[:criteria] = criteria if criteria

  block.call(:line, persist_fcb_self(all_fcbs, opts))
rescue StandardError
  wwe 'YAML loading error', { body: body, error: $! }
end