Created
February 7, 2015 05:53
-
-
Save NickTX/9d7e00ec07be6ec7f4e6 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' | |
| 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