Class: RBSJsonSchema::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/rbs_json_schema/cli.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(stdout:, stderr:) ⇒ CLI

Returns a new instance of CLI.



8
9
10
11
12
# File 'lib/rbs_json_schema/cli.rb', line 8

def initialize(stdout:, stderr:)
  @stdout = stdout
  @stderr = stderr
  @options = {}
end

Instance Attribute Details

#stderrObject (readonly)

Returns the value of attribute stderr.



6
7
8
# File 'lib/rbs_json_schema/cli.rb', line 6

def stderr
  @stderr
end

#stdoutObject (readonly)

Returns the value of attribute stdout.



5
6
7
# File 'lib/rbs_json_schema/cli.rb', line 5

def stdout
  @stdout
end

Instance Method Details

#run(args) ⇒ Object



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
# File 'lib/rbs_json_schema/cli.rb', line 14

def run(args)
  OptionParser.new do |opts|
    opts.banner = <<~USAGE
    Usage: rbs_json_schema [options...] [path...]

    Generates RBS files from JSON Schema.

    Options:
    USAGE

    opts.on("--[no-]stringify-keys", "Generate record types with string keys") do |bool|
      @options[:stringify_keys] = bool
    end

    opts.on("-o OUTPUT", "Output the generated RBS to a specific location") do |location|
      @options[:output] = location
    end
  end.parse!(args)

  generator = Generator.new(stringify_keys: @options[:stringify_keys], output: @options[:output], stdout: stdout, stderr: stderr)
  args.each do |path|
    path =
      begin
        Pathname(path).realpath
      rescue Errno::ENOENT => _
        raise ValidationError.new(message: "#{path}: No such file or directory found!")
      end

    case
    when path.file?
      generator.generate(URI.parse("file://#{path}"))
    when path.directory?
      Dir["#{path}/*.{json}"].sort.each do |file|
        file = Pathname(file).realpath
        generator.generate(URI.parse("file://#{file}"))
      end
    else
      raise ValidationError.new(message: "#{path}: No such file or directory found!")
    end
  end
  generator.write_output
end