feature: support simple config groups

Signed-off-by: Dominik Richter <dominik.richter@gmail.com>
This commit is contained in:
Dominik Richter 2015-09-30 11:32:24 +02:00
parent c5755f93fd
commit 2d8b63cb22

View file

@ -17,7 +17,8 @@ class SimpleConfig
# no comments can be added to the end of an assignment/statement line # no comments can be added to the end of an assignment/statement line
def parse(raw_data, opts = {}) def parse(raw_data, opts = {})
@params = {} @params = {}
options = default_options.merge(opts) @vals = @params
options = default_options.merge(opts || {})
rest = raw_data rest = raw_data
rest = parse_rest(rest, options) while rest.length > 0 rest = parse_rest(rest, options) while rest.length > 0
end end
@ -63,29 +64,41 @@ class SimpleConfig
[line, idx_nl] [line, idx_nl]
end end
def parse_line_params(line, opts) def parse_params_line(line, opts)
# now line contains what we are interested in parsing # now line contains what we are interested in parsing
# check if it is an assignment # check if it is an assignment
m = opts[:assignment_re].match(line) m = opts[:assignment_re].match(line)
if !m.nil? return nil if m.nil?
if opts[:multiple_values]
@params[m[1]] ||= [] if opts[:multiple_values]
@params[m[1]].push(parse_values(m, opts[:key_vals])) @vals[m[1]] ||= []
else @vals[m[1]].push(parse_values(m, opts[:key_vals]))
@params[m[1]] = parse_values(m, opts[:key_vals]) else
end @vals[m[1]] = parse_values(m, opts[:key_vals])
elsif !is_empty_line(line) end
if opts[:multiple_values] end
@params[line.strip] ||= []
else def parse_group_line(line, opts)
@params[line.strip] = '' return nil if opts[:group_re].nil?
end m = opts[:group_re].match(line)
return nil if m.nil?
@vals = @params[m[1]] = {}
end
def parse_implicit_assignment_line(line, opts)
return nil if is_empty_line(line)
if opts[:multiple_values]
@vals[line.strip] ||= []
else
@vals[line.strip] = ''
end end
end end
def parse_rest(rest, opts) def parse_rest(rest, opts)
line, idx_nl = parse_comment_line(rest, opts) line, idx_nl = parse_comment_line(rest, opts)
parse_line_params(line, opts) parse_params_line(line, opts) or
parse_group_line(line, opts) or
parse_implicit_assignment_line(line, opts)
# return whatever is left # return whatever is left
rest[(idx_nl + 1)..-1] || '' rest[(idx_nl + 1)..-1] || ''
@ -101,6 +114,7 @@ class SimpleConfig
multiline: false, multiline: false,
comment_char: '#', comment_char: '#',
assignment_re: /^\s*([^=]*?)\s*=\s*(.*?)\s*$/, assignment_re: /^\s*([^=]*?)\s*=\s*(.*?)\s*$/,
group_re: /\[([^\]]+)\]\s*$/,
key_vals: 1, # default for key=value, may require for 'key val1 val2 val3' key_vals: 1, # default for key=value, may require for 'key val1 val2 val3'
standalone_comments: false, standalone_comments: false,
multiple_values: false, multiple_values: false,