Updated mcollective.init according to OSCI-658
[packages/precise/mcollective.git] / lib / mcollective / vendor / json / bin / prettify_json.rb
1 #!/usr/bin/env ruby
2
3 require 'json'
4 require 'fileutils'
5 include FileUtils
6 require 'spruz/go'
7 include Spruz::GO
8
9 opts = go 'slhi:', args = ARGV.dup
10 if opts['h'] || opts['l'] && opts['s']
11   puts <<EOT
12 Usage: #{File.basename($0)} [OPTION] [FILE]
13
14 If FILE is skipped, this scripts waits for input from STDIN. Otherwise
15 FILE is opened, read, and used as input for the prettifier.
16
17 OPTION can be
18   -s     to output the shortest possible JSON (precludes -l)
19   -l     to output a longer, better formatted JSON (precludes -s)
20   -i EXT prettifies FILE in place, saving a backup to FILE.EXT
21   -h     this help
22 EOT
23   exit 0
24 end
25
26 json_opts = { :max_nesting => false, :create_additions => false }
27
28 document =
29   if filename = args.first or filename == '-'
30     File.read(filename)
31   else
32     STDIN.read
33   end
34
35 json = JSON.parse document, json_opts
36
37 output = if opts['s']
38   JSON.fast_generate json, json_opts
39 else # default is -l
40   JSON.pretty_generate json, json_opts
41 end
42
43 if opts['i'] && filename
44   cp filename, "#{filename}.#{opts['i']}"
45   File.open(filename, 'w') { |f| f.puts output }
46 else
47   puts output
48 end