Created
November 24, 2015 05:03
-
-
Save fujiwara/a834d69b2ddf794b252b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#!/usr/bin/env ruby | |
require 'json' | |
require 'optparse' | |
$header = '-- QUERY:' | |
def json2text(src=STDIN, dest=STDOUT) | |
JSON.parse(src.read).each do |q| | |
expression = q.delete('expression') | |
dest.puts "#{$header}#{q.to_json}" | |
dest.puts expression | |
dest.puts "" | |
end | |
end | |
def text2json(src=STDIN, dest=STDOUT) | |
queries = [] | |
buf = [] | |
index = -1 | |
src.each do |line| | |
next if line == "\n" | |
if line =~ /^#{$header}/ | |
if index >= 0 | |
queries[index]['expiression'] = buf.join('') | |
buf.clear | |
end | |
line.gsub!(/^#{$header}/, '') | |
line.gsub!(/ *$/, '') | |
index = index + 1 | |
queries[index] = JSON.parse(line) | |
elsif line =~ /^--/ | |
# skip comment line | |
next | |
else | |
buf << line | |
end | |
end | |
queries[index]['expression'] = buf.join('') | |
dest.puts queries.to_json | |
end | |
params = ARGV.getopts('i:') | |
case params['i'] | |
when 'text' | |
text2json | |
when 'json' | |
json2text | |
else | |
warn "invalid option -i #{params['i']}: use text or json" | |
exit 1 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment