Class: ThorAddons::Helpers::OptionsConfigFile

Inherits:
Object
  • Object
show all
Defined in:
lib/thor-addons/helpers/options_config_file.rb

Class Method Summary collapse

Class Method Details

.extract_command_data(data, command) ⇒ Object



13
14
15
# File 'lib/thor-addons/helpers/options_config_file.rb', line 13

def self.extract_command_data(data, command)
  [data.fetch("global", {}), data.fetch(command, {})]
end

.get_command_config_data(data, invocations, current_command_name) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/thor-addons/helpers/options_config_file.rb', line 17

def self.get_command_config_data(data, invocations, current_command_name)
  invocations ||= {}
  commands = (invocations.values.flatten << current_command_name)

  global_options, cmd_options = extract_command_data(data, commands.shift)

  commands.each do |cmd|
    should_break = cmd_options[cmd].nil?

    global, cmd_options = extract_command_data(cmd_options, cmd)
    global_options.merge!(global)

    break if should_break
  end

  global_options.merge(cmd_options)
end

.parse(config_file, invocations, current_command_name, defaults) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/thor-addons/helpers/options_config_file.rb', line 35

def self.parse(config_file, invocations, current_command_name, defaults)
  data = parse_config_file(config_file)
  opts = get_command_config_data(data, invocations, current_command_name)

  config_opts = opts.each_with_object({}) do |(key, value), hsh|
    if defaults.keys.map(&:to_s).include?(key.to_s)
      hsh[key] = value
    else
      STDERR.puts("[WARN] rejecting invalid config file option: '#{key}'")
    end
  end

  OptionsHash.new(config_opts)
end

.parse_config_file(config_file) ⇒ Object



6
7
8
9
10
11
# File 'lib/thor-addons/helpers/options_config_file.rb', line 6

def self.parse_config_file(config_file)
  YAML.load_file(config_file) || {}
rescue Errno::ENOENT, Psych::SyntaxError
  STDERR.puts("[WARN] Unable to parse 'config_file' '#{config_file}'.")
  {}
end