Class: RBS::Inline::Annotator::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/rbs/inline/annotator/cli.rb

Defined Under Namespace

Classes: Options, Spinner

Instance Method Summary collapse

Constructor Details

#initialize(argv) ⇒ CLI

Returns a new instance of CLI.



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/rbs/inline/annotator/cli.rb', line 22

def initialize(argv)
  @loader = RBS::EnvironmentLoader.new(core_root: nil)
  @argv = argv
  @options = Options.new(
    mode: 'write'
  )
  OptionParser.new do |opt|
    opt.on("-I DIR", "Load RBS files from the directory") do |dir|
      @loader.add(path: Pathname(dir))
    end
    opt.on("-m", "--mode MODE", "Mode [quiet, print-only, write] (default: write)") do |mode|
      @options.mode = mode
    end
  end.parse!(@argv)
end

Instance Method Details

#runObject



38
39
40
41
42
43
44
45
46
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
# File 'lib/rbs/inline/annotator/cli.rb', line 38

def run
  env = RBS::Environment.from_loader(@loader)
  targets = @argv.flat_map { Pathname.glob(_1) }.flat_map do |path|
    if path.directory?
      pattern = path / "**/*.rb"
      Pathname.glob(pattern.to_s)
    else
      path
    end
  end

  targets.sort!
  targets.uniq!

  Spinner.new.tap do |spinner|
    print "\e[?25l" if @options.mode == 'write'
    targets.each do |target|
      annotated_code, changed = Processor.new(target:, env:).process
      case @options.mode
      when 'write'
        File.write(target, annotated_code) if changed
      when 'print-only'
        puts annotated_code
      when 'quiet'
        # do nothing
      else
        raise "invalid mode: #{@options.mode}"
      end
      print "\r#{spinner.tick}" if @options.mode == 'write'
    end
  ensure
    print "\e[?25h" if @options.mode == 'write'
  end

  puts "\rDone!" if @options.mode == 'write'

  0 # exit code
end