Created
April 4, 2012 17:59
-
-
Save gmcmillan/2304284 to your computer and use it in GitHub Desktop.
my.cnf parser
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
def self.parse_config(file) | |
config = {} | |
File.open(file).each_line do |line| | |
line.strip! | |
# skip lines with comments or blank lines | |
next if /^\#/.match(line) | |
next if /^\s*$/.match(line) | |
# store which group in the config the line belongs to (e.g. [mysqld]) | |
if(/^\[(.+?)\]/.match(line)) | |
@group = $1 | |
end | |
# match "'key' and 'key val' | |
if(/^([\w\d\_\-]+)\s*([\w\d\_\-]+)$/.match(line)) | |
param, value = line.split(/\s+/, 2) | |
# match 'key = val' or 'key=val' etc. | |
elsif(/^(.+?)\s*[=]\s*(.+)$/.match(line)) | |
param, value = line.split(/\s*=\s*/, 2) | |
end | |
var_name = "#{param}".chomp.strip | |
if value.nil? | |
# variables without a declared value should be set to true | |
new_value = true | |
else | |
value = value.chomp.strip | |
if value =~ /^['"](.*)['"]$/ | |
new_value = $1 | |
else | |
new_value = value | |
end | |
end | |
if @group.nil? | |
config["#{var_name}"] = new_value | |
else | |
config["#{@group}"] = {} if config["#{@group}"].nil? | |
config["#{@group}"]["#{var_name}"] = new_value unless var_name.empty? | |
end | |
end | |
return config | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment