Class: TreeRb::CliJson
- Inherits:
-
Object
- Object
- TreeRb::CliJson
- Defined in:
- lib/tree_rb/cli/cli_json.rb
Constant Summary collapse
- SUCCESS =
0
- FAILURE =
1
Class Method Summary collapse
Instance Method Summary collapse
Class Method Details
.run ⇒ Object
12 13 14 |
# File 'lib/tree_rb/cli/cli_json.rb', line 12 def self.run self.new.parse_args(ARGV) end |
Instance Method Details
#options_parser(options) ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/tree_rb/cli/cli_json.rb', line 16 def () parser = OptionParser.new parser. = 'Usage: rjson.rb [options] [directory]' parser.separator 'pretty format json file' parser.separator 'Code https://github.com/tokiro/treevisitor. Feedback to [email protected]' parser.on('-o [FILE]', '--output [FILE]', String) do |v| if [:output] puts 'only one file of output can be used' [:exit] = true end [:output] = v end [:force_overwrite_output] = false parser.on('--force', 'overwrite output') do [:force_overwrite_output] = true end parser.on_tail('--help', 'Show this message') do puts parser [:exit] = SUCCESS end parser.on_tail("--version", "Show the version") do puts "tree.rb version #{TreeRb::VERSION}" [:exit] = SUCCESS end parser end |
#parse_args(argv) ⇒ Object
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
# File 'lib/tree_rb/cli/cli_json.rb', line 47 def parse_args(argv) = { :verbose => true, :force => false, :output_plugins => 'build-dir' } parser = () begin rest = parser.parse(argv) rescue OptionParser::InvalidOption => e $stderr.puts e.to_s $stderr.puts "try --help for help" return FAILURE rescue OptionParser::MissingArgument => e $stderr.puts e.to_s $stderr.puts "try --help for help" return FAILURE end unless [:exit].nil? return [:exit] end ## ## option: output, force ## output = $stdout if [:output] filename = [:output] if File.exist?(filename) and not [:force_overwrite_output] $stderr.puts "catalog '#{filename}' exists use --force to overwrite" return FAILURE end output = File.open(filename, "w") $stderr.puts "Writing file '#{filename}'" end if rest.length < 1 $stderr.puts 'missing arg' return FAILURE else filename = rest[0] end show_input = false unless File.exists?(filename) $stderr.puts "input file not exists '#{filename}'" exit end my_json_str = File.read(filename) if show_input $stderr.puts '*************************' $stderr.puts my_json_str $stderr.puts '*************************' end begin my_json = JSON(my_json_str) rescue JSON::ParserError $stderr.puts 'json is malformed' return FAILURE end output.puts JSON.pretty_generate(my_json) SUCCESS end |