Module: Howzit::ScriptComm

Defined in:
lib/howzit/script_comm.rb

Overview

Script Communication module Handles communication from scripts to Howzit via a communication file

Class Method Summary collapse

Class Method Details

.apply(comm_file) ⇒ Object

Process communication and apply logs/variables

Parameters:

  • comm_file (String)

    Path to the communication file



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/howzit/script_comm.rb', line 75

def apply(comm_file)
  result = process(comm_file)
  return if result[:logs].empty? && result[:vars].empty?

  # Apply log messages
  result[:logs].each do |log_entry|
    level = log_entry[:level]
    message = log_entry[:message]
    next unless Howzit.console

    case level
    when :info
      Howzit.console.info(message)
    when :warn
      Howzit.console.warn(message)
    when :error
      Howzit.console.error(message)
    when :debug
      Howzit.console.debug(message)
    end
  end

  # Apply variables to named_arguments
  return if result[:vars].empty?

  Howzit.named_arguments ||= {}
  Howzit.named_arguments.merge!(result[:vars])
end

.create_comm_fileString

Create a communication file for scripts to write to

Returns:

  • (String)

    Path to the communication file



13
14
15
16
17
# File 'lib/howzit/script_comm.rb', line 13

def create_comm_file
  file = Tempfile.new('howzit_comm')
  file.close
  file.path
end

.process(comm_file) ⇒ Hash

Read and process the communication file after script execution

Parameters:

  • comm_file (String)

    Path to the communication file

Returns:

  • (Hash)

    Hash with :logs and :vars keys



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/howzit/script_comm.rb', line 37

def process(comm_file)
  return { logs: [], vars: {} } unless File.exist?(comm_file)

  logs = []
  vars = {}

  begin
    content = File.read(comm_file)
    content.each_line do |line|
      line = line.strip
      next if line.empty?

      case line
      when /^LOG:(info|warn|error|debug):(.+)$/i
        level = Regexp.last_match(1).downcase.to_sym
        message = Regexp.last_match(2)
        logs << { level: level, message: message }
      when /^VAR:([A-Z0-9_]+)=(.*)$/i
        key = Regexp.last_match(1)
        value = Regexp.last_match(2)
        vars[key] = value
      end
    end
  rescue StandardError => e
    Howzit.console&.warn("Error reading communication file: #{e.message}")
  ensure
    # Clean up the file
    File.unlink(comm_file) if File.exist?(comm_file)
  end

  { logs: logs, vars: vars }
end

.setupString

Set up the communication file and environment variable

Returns:

  • (String)

    Path to the communication file



24
25
26
27
28
# File 'lib/howzit/script_comm.rb', line 24

def setup
  comm_file = create_comm_file
  ENV['HOWZIT_COMM_FILE'] = comm_file
  comm_file
end