Module: PinterestURLNormalizer::CLI

Defined in:
lib/pinterest_url_normalizer/cli.rb

Overview

Command-line interface for the gem executable.

Class Method Summary collapse

Class Method Details

.run(arguments, input: $stdin, output: $stdout, error: $stderr) ⇒ Object



12
13
14
15
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
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/pinterest_url_normalizer/cli.rb', line 12

def run(arguments, input: $stdin, output: $stdout, error: $stderr)
  json_output = false
  parser = OptionParser.new do |options|
    options.banner = "Usage: pinterest-url-normalizer [--json] [URL ...]"
    options.on("--json", "Emit JSON Lines") { json_output = true }
  end

  urls = arguments.dup
  begin
    parser.parse!(urls)
  rescue OptionParser::ParseError => exception
    error.puts exception.message
    error.puts parser
    return 2
  end

  urls = input.each_line.map(&:strip).reject(&:empty?) if urls.empty?
  if urls.empty?
    error.puts parser
    return 2
  end

  exit_code = 0
  urls.each do |url|
    begin
      parsed = PinterestURLNormalizer.parse(url)
      if json_output
        output.puts JSON.generate(parsed.to_h.compact)
      else
        output.puts parsed.normalized_url
      end
    rescue Error => exception
      exit_code = 1
      if json_output
        output.puts JSON.generate(
          input: url,
          error: { code: exception.code, message: exception.message }
        )
      else
        error.puts "#{exception.code}: #{exception.message}: #{url}"
      end
    end
  end
  exit_code
end