Skip to content

Instantly share code, notes, and snippets.

@NickTX
Created February 7, 2015 05:53
Show Gist options
  • Select an option

  • Save NickTX/9d7e00ec07be6ec7f4e6 to your computer and use it in GitHub Desktop.

Select an option

Save NickTX/9d7e00ec07be6ec7f4e6 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'json'
require 'optparse'
require 'fileutils'
include FileUtils
options = {}
option_parser = OptionParser.new do |opts|
# Create overwrite switch
opts.on("-o","--overwrite") do
options[:overwrite] = true
end
# Option to read from file
opts.on("-f JSON_FILE","--input") do |json_file|
options[:json_file] = json_file
end
# Create backup_file flag
opts.on("-b BACKUP_FILE","--backup") do |backup_file|
options[:backup_file] = backup_file
end
end
option_parser.parse!
json = JSON[
if options[:json_file]
File.read options[:json_file]
else
STDIN.read
end
]
output = JSON.pretty_generate(json, {indent: " "})
if options[:json_file] && options[:overwrite]
if options[:backup_file]
#write to backup file here
system("cp #{options[:json_file]} #{options[:backup_file]}")
end
File.open(options[:json_file], 'w') { |file| file.puts output }
else
puts output
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment