class HammerCLI::Options::Normalizers::KeyValueList

Constants

FULL_RE
PAIR_RE

Public Class Methods

common_description() click to toggle source
# File lib/hammer_cli/options/normalizers.rb, line 62
def common_description
  _('Comma-separated list of key=value.') + "\n" +
    _('JSON is acceptable and preferred way for such parameters')
end
completion_type() click to toggle source
# File lib/hammer_cli/options/normalizers.rb, line 58
def completion_type
  :key_value_list
end

Public Instance Methods

format(val) click to toggle source
# File lib/hammer_cli/options/normalizers.rb, line 68
def format(val)
  return {} unless val.is_a?(String)
  return {} if val.empty?

  if valid_key_value?(val)
    parse_key_value(val)
  else
    begin
      formatter = JSONInput.new
      formatter.format(val)
    rescue ArgumentError
      raise ArgumentError, _("Value must be defined as a comma-separated list of key=value or valid JSON.")
    end
  end
end

Private Instance Methods

parse_key_value(val) click to toggle source
# File lib/hammer_cli/options/normalizers.rb, line 90
def parse_key_value(val)
  result = {}
  val.scan(Regexp.new(PAIR_RE)) do |key, value|
    value = value.strip
    if value.start_with?('[')
      value = value.scan(/[^,\[\]]+/)
    elsif value.start_with?('{')
      value = parse_key_value(value[1...-1])
    end

    result[key.strip] = strip_value(value)
  end
  result
end
strip_chars(string, chars) click to toggle source
# File lib/hammer_cli/options/normalizers.rb, line 119
def strip_chars(string, chars)
  chars = Regexp.escape(chars)
  string.gsub(/\A[#{chars}]+|[#{chars}]+\z/, '')
end
strip_value(value) click to toggle source
# File lib/hammer_cli/options/normalizers.rb, line 105
def strip_value(value)
  if value.is_a? Array
    value.map do |item|
      strip_chars(item.strip, '"\'')
    end
  elsif value.is_a? Hash
    value.map do |key, val|
      [strip_chars(key.strip, '"\''), strip_chars(val.strip, '"\'')]
    end.to_h
  else
    strip_chars(value.strip, '"\'')
  end
end
valid_key_value?(val) click to toggle source
# File lib/hammer_cli/options/normalizers.rb, line 86
def valid_key_value?(val)
  Regexp.new(FULL_RE).match(val)
end