Created
February 19, 2017 20:11
-
-
Save IceN9ne/370bf1346df8ca565c5b37c92b53c071 to your computer and use it in GitHub Desktop.
kvc to json
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 'json' | |
def kvc_to_hash(filename) | |
config = {} | |
network = nil | |
File.foreach(filename) do |line| | |
case line | |
when /^#/ | |
when /^\[(.*)\]$/ | |
network = $1 | |
config[network] = {:server => []} | |
when /^(\d+)_(\S+?)=(.*)/ | |
config[network][:server][$1.to_i] = {} if config[network][:server][$1.to_i].nil? | |
config[network][:server][$1.to_i][$2] = $3 | |
when /^NSRule(\d+)_(\S+?)=(.*)/ | |
config[network][:NSRule] = [] if config[network][:NSRule].nil? | |
config[network][:NSRule][$1.to_i] = {} if config[network][:NSRule][$1.to_i].nil? | |
config[network][:NSRule][$1.to_i][$2] = $3 | |
when /^(\S+?)=(.*)/ | |
config[network][$1] = $2 | |
else | |
puts "NOT FOUND: #{line}" | |
end | |
end | |
config | |
end | |
def hash_to_kvc(hash, filename = nil) | |
puts "# KVIrc configuration file" | |
hash.sort.each do |network, netdata| | |
puts "[#{network}]" | |
netdata.each do |netkey, netval| | |
case netkey.to_s | |
when 'server' | |
netval.each_with_index do |server, index| | |
server.each do |key, val| | |
puts "#{index}_#{key}=#{val}" | |
end | |
end | |
when 'NSRule' | |
netval.each_with_index do |nsrule, index| | |
nsrule.each do |rule, val| | |
puts "NSRule#{index}_#{rule}=#{val}" | |
end | |
end | |
else | |
puts "#{netkey}=#{netval}" | |
end | |
end | |
end | |
end | |
if __FILE__ == $0 | |
file = ARGV[0] | |
if file.nil? | |
puts "No file passed" | |
exit 1 | |
end | |
if file =~ /\.kvc$/i | |
hash = kvc_to_hash(file) | |
puts hash.to_json | |
elsif file =~ /\.json$/i | |
hash = JSON.parse(File.read(file)) | |
hash_to_kvc hash | |
else | |
puts "Invalid file for converting" | |
exit 1 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment