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

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

Instance Method Details

#runObject



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

def run
  if @version
    puts "kapfmt #{Kapusta::VERSION}"
    return 0
  end

  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