Class: Kapusta::Formatter

Inherits:
Object
  • Object
show all
Defined in:
lib/kapusta/formatter.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

MAX_WIDTH =
80
INDENT =
2
STDIN_PATH =
'-'
PIPELINE_FORMS =
%w[-> ->> -?> -?>> doto].freeze

Instance Method Summary collapse

Constructor Details

#initialize(argv) ⇒ Formatter

Returns a new instance of Formatter.



13
14
15
16
17
# File 'lib/kapusta/formatter.rb', line 13

def initialize(argv)
  @mode = :stdout
  @files = []
  parse_args(argv)
end

Instance Method Details

#runObject



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
# File 'lib/kapusta/formatter.rb', line 19

def run
  validate_args!

  formatted = @files.map do |path|
    original = read_source(path)
    [path, original, format_source(original)]
  end

  case @mode
  when :stdout
    $stdout.write(formatted.first[2])
  when :fix
    formatted.each do |path, _original, rewritten|
      raise Error, 'Cannot use --fix with stdin (-).' if stdin_path?(path)

      File.write(path, rewritten)
    end
  when :check
    dirty = formatted.reject { |_path, original, rewritten| original == rewritten }
    dirty.each do |path, _original, _rewritten|
      warn "Not formatted: #{path}"
    end
    return 1 unless dirty.empty?
  end

  0
rescue Error => e
  warn e.message
  1
end