Class: Legion::CLI::Config

Inherits:
Thor
  • Object
show all
Defined in:
lib/legion/cli/config_command.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.exit_on_failure?Boolean

Returns:

  • (Boolean)


8
9
10
# File 'lib/legion/cli/config_command.rb', line 8

def self.exit_on_failure?
  true
end

Instance Method Details

#import(source) ⇒ Object



226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'lib/legion/cli/config_command.rb', line 226

def import(source)
  out = formatter
  require_relative 'config_import'

  out.info("Fetching config from #{source}...")
  body = ConfigImport.fetch_source(source)
  config = ConfigImport.parse_payload(body)
  paths = ConfigImport.write_config(config, force: options[:force])
  summary = ConfigImport.summary(config)

  if paths.empty?
    out.warn('No config files were written (empty configuration).')
  else
    paths.each { |p| out.success("Written: #{p}") }
  end
  out.info("Sections: #{summary[:sections].join(', ')}")
  if summary[:vault_clusters].any?
    out.info("Vault clusters: #{summary[:vault_clusters].join(', ')}")
    out.info("Run 'legion' to authenticate via LDAP during onboarding")
  end
rescue CLI::Error => e
  formatter.error(e.message)
  raise SystemExit, 1
end

#pathObject



63
64
65
66
67
68
69
70
71
72
73
74
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
# File 'lib/legion/cli/config_command.rb', line 63

def path
  out = formatter
  Connection.config_dir = options[:config_dir] if options[:config_dir]
  paths = config_search_paths

  if options[:json]
    out.json(paths.map { |p| { path: p[:path], exists: p[:exists], active: p[:active] } })
    return
  end

  out.header('Configuration Search Paths')
  out.spacer
  paths.each do |p|
    if p[:active]
      puts "  #{out.colorize('>>', :green)} #{p[:path]} #{out.colorize('(active)', :green)}"
    elsif p[:exists]
      puts "  #{out.colorize(' *', :yellow)} #{p[:path]} #{out.colorize('(exists)', :yellow)}"
    else
      puts "  #{out.colorize('  ', :gray)} #{out.colorize(p[:path], :gray)}"
    end
  end

  out.spacer
  out.header('Environment Variables')
  env_vars = %w[LEGION_ENV LEGION_CONFIG_DIR LEGION_LOG_LEVEL]
  env_vars.each do |var|
    val = ENV.fetch(var, nil)
    if val
      puts "  #{out.colorize(var, :cyan)} = #{val}"
    else
      puts "  #{out.colorize(var, :gray)} (not set)"
    end
  end
rescue CLI::Error => e
  formatter.error(e.message)
  raise SystemExit, 1
ensure
  Connection.shutdown
end

#resetObject



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/legion/cli/config_command.rb', line 193

def reset
  require_relative 'config_import'
  out = formatter
  dir = options[:config_dir] || ConfigImport::SETTINGS_DIR

  files = Dir.glob(File.join(dir, '*.json'))
  if files.empty?
    out.warn("No JSON files found in #{dir}")
    return
  end

  unless options[:force]
    out.warn("This will remove #{files.size} JSON file(s) from #{dir}:")
    files.each { |f| puts "    #{File.basename(f)}" }
    print '  Continue? [y/N] '
    answer = $stdin.gets&.strip
    unless answer&.match?(/\Ay(es)?\z/i)
      out.warn('Aborted.')
      return
    end
  end

  files.each { |f| FileUtils.rm_f(f) }

  if options[:json]
    out.json(removed: files, directory: dir)
  else
    out.success("Removed #{files.size} JSON file(s) from #{dir}")
  end
end

#scaffoldObject

Raises:

  • (SystemExit)


181
182
183
184
185
# File 'lib/legion/cli/config_command.rb', line 181

def scaffold
  out = formatter
  exit_code = ConfigScaffold.run(out, options)
  raise SystemExit, exit_code if exit_code != 0
end

#showObject



18
19
20
21
22
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
# File 'lib/legion/cli/config_command.rb', line 18

def show
  out = formatter
  Connection.config_dir = options[:config_dir] if options[:config_dir]
  Connection.ensure_settings(resolve_secrets: false)

  settings = if Legion::Settings.respond_to?(:to_hash)
               Legion::Settings.to_hash
             elsif Legion::Settings.respond_to?(:to_h)
               Legion::Settings.to_h
             else
               # Settings uses [] accessor, enumerate known sections
               %i[client transport data cache crypt extensions api].to_h do |key|
                 [key, Legion::Settings[key]]
               rescue StandardError => e
                 Legion::Logging.warn("ConfigCommand#show settings key #{key} read failed: #{e.message}") if defined?(Legion::Logging)
                 [key, nil]
               end.compact
             end

  if options[:section]
    key = options[:section].to_sym
    unless settings.key?(key)
      out.error("Section '#{options[:section]}' not found. Available: #{settings.keys.join(', ')}")
      raise SystemExit, 1
    end
    settings = { key => settings[key] }
  end

  # Redact sensitive values
  redacted = deep_redact(settings)

  if options[:json]
    out.json(redacted)
  else
    print_nested(out, redacted)
  end
rescue CLI::Error => e
  formatter.error(e.message)
  raise SystemExit, 1
ensure
  Connection.shutdown
end

#validateObject

rubocop:disable Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/legion/cli/config_command.rb', line 104

def validate # rubocop:disable Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity
  out = formatter
  Connection.config_dir = options[:config_dir] if options[:config_dir]

  issues = []
  warnings = []

  # Check settings load
  begin
    Connection.ensure_settings(resolve_secrets: false)
    out.success('Settings loaded successfully') unless options[:json]
  rescue StandardError => e
    issues << "Settings failed to load: #{e.message}"
  end

  # Check transport config
  if Connection.settings?
    transport = Legion::Settings[:transport] || {}
    transport_host = transport.dig(:connection, :host)
    warnings << 'Transport host not configured (RabbitMQ will use default localhost)' if transport_host.nil? || transport_host.to_s.empty?

    # Check data config
    data = Legion::Settings[:data] || {}
    warnings << 'Database adapter not configured' if data[:adapter].nil?

    # Check extensions config
    extensions = Legion::Settings[:extensions] || {}
    warnings << 'No extensions configured in settings' if extensions.empty?
  end

  # Check LLM config
  validate_llm(warnings) if Connection.settings?

  if options[:json]
    out.json(valid: issues.empty?, issues: issues, warnings: warnings)
    return
  end

  if issues.any?
    out.spacer
    out.header('Issues')
    issues.each { |i| out.error(i) }
  end

  if warnings.any?
    out.spacer
    out.header('Warnings')
    warnings.each { |w| out.warn(w) }
  end

  if issues.empty? && warnings.empty?
    out.success('Configuration looks good')
  elsif issues.empty?
    out.warn("Configuration valid with #{warnings.size} warning(s)")
  else
    out.error("Configuration has #{issues.size} issue(s)")
    raise SystemExit, 1
  end
rescue CLI::Error => e
  formatter.error(e.message)
  raise SystemExit, 1
ensure
  Connection.shutdown
end