Module: Wisco::Connector

Defined in:
lib/wisco/connector.rb

Class Method Summary collapse

Class Method Details

.candidate_files(dir) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/wisco/connector.rb', line 64

def candidate_files(dir)
  primary = 'connector.rb'
  others = Dir.glob(File.join(dir, '*.rb'))
              .map { |f| File.basename(f) }
              .reject { |f| f == primary }
              .sort

  result = []
  result << primary if File.exist?(File.join(dir, primary))
  result.concat(others)
  result
end

.detect_connector(dir) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/wisco/connector.rb', line 7

def detect_connector(dir)
  candidates = candidate_files(dir)

  if candidates.empty?
    warn "  No .rb files found in #{dir}"
    return nil
  end

  candidates.each do |filename|
    puts "  Checking #{filename}..."
    return filename if valid_connector?(File.join(dir, filename))
  end

  nil
end

.load_connector_from_config(target_dir) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
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
# File 'lib/wisco/connector.rb', line 23

def load_connector_from_config(target_dir)
  target_dir = File.expand_path(target_dir)
  config_path = Wisco.config_path(target_dir)

  unless File.exist?(config_path)
    warn "Error: No #{Wisco::WISCO_DIR}/#{Wisco::CONFIG_FILENAME} found in #{target_dir}."
    warn "       Run '#{Wisco::CLI_NAME} init' first."
    exit 1
  end

  config = Wisco::Config.load_config(config_path)
  connector_file = config.dig('connector', 'file')
  connector_path = config.dig('connector', 'path')

  if connector_file.nil? || connector_path.nil?
    warn "Error: #{Wisco::WISCO_DIR}/#{Wisco::CONFIG_FILENAME} is missing connector path/file. Run '#{Wisco::CLI_NAME} init' again."
    exit 1
  end

  full_path = File.join(connector_path, connector_file)
  unless File.exist?(full_path)
    warn "Error: Connector file not found: #{full_path}"
    exit 1
  end

  code = File.read(full_path)
  original_verbose = $VERBOSE
  $VERBOSE = nil
  begin
    result = eval(code) # rubocop:disable Security/Eval
  rescue Exception => e
    raise "\nConnector contains errors:\n#{e.message}"
    warn "Error: Failed to load connector: #{e.message}"
    exit 1
  ensure
    $VERBOSE = original_verbose
  end

  result
end

.valid_connector?(path) ⇒ Boolean

Returns:

  • (Boolean)


77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/wisco/connector.rb', line 77

def valid_connector?(path)
  code = File.read(path)
  original_verbose = $VERBOSE
  $VERBOSE = nil
  begin
    result = eval(code) # rubocop:disable Security/Eval
    result.is_a?(Hash) && result.key?(:title)
  rescue Exception => e
    false
  ensure
    $VERBOSE = original_verbose
  end
end