Created
January 3, 2010 18:36
-
-
Save paukul/268076 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'pp' | |
require 'treetop' | |
Treetop.load_from_string(DATA.read) | |
parser = PyConfigParser.new | |
conf = <<-STUFF | |
[section name] | |
key:value | |
other_key:value2 | |
[other section] | |
foo = bar, baz | |
narf: bla | |
[some other stuff] | |
white: space | |
STUFF | |
if config = parser.parse(conf) | |
config = config.build | |
else | |
puts parser.failure_reason | |
end | |
pp config | |
# => | |
# { | |
# "some other stuff" => { "white" =>"space" }, | |
# "section name" => { "other_key" => "value2", "key"=> "value" }, | |
# "other section" => { "foo" => ["bar", "baz"], "narf"=> "bla" } | |
# } | |
__END__ | |
grammar PyConfig | |
rule main | |
section* | |
{ | |
def build | |
@config = {} | |
elements.each do |section| | |
@config[section.name] = section.build | |
end | |
@config | |
end | |
} | |
end | |
rule section | |
'[' sectionname ']' eol | |
pairs:(sectionvalue eol)+ | |
white* | |
{ | |
def name | |
sectionname.text_value | |
end | |
def build | |
return pairs.elements.inject({}) do |pairs, elt| | |
pairs.merge!(elt.sectionvalue.build) | |
pairs | |
end | |
end | |
} | |
end | |
rule sectionname | |
(string / white)+ | |
end | |
rule sectionvalue | |
white* key separator value | |
{ | |
def build | |
separator.build(key, value) | |
end | |
} | |
end | |
rule separator | |
white* ':' white* | |
{ | |
def build(key, value) | |
{key.text_value => value.text_value.strip} | |
end | |
} | |
/ | |
white* '=' white* | |
{ | |
def build(key, value) | |
{key.text_value => value.text_value.split(',').map {|val| val.strip }} | |
end | |
} | |
end | |
rule key | |
string | |
end | |
rule value | |
(string / ',' / space)* | |
end | |
rule string | |
[a-zA-Z_0-9]+ | |
end | |
rule white | |
(space / eol) | |
end | |
rule space | |
[ \t] | |
end | |
rule eol | |
"\n" / ("\r" "\n"?) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment