Module: Jade::CLI::Fmt

Defined in:
lib/jade/cli/fmt.rb

Class Method Summary collapse

Class Method Details

.emit(formatted, source_text, file, mode) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/jade/cli/fmt.rb', line 57

def emit(formatted, source_text, file, mode)
  case mode
  when :in_place
    usage unless file
    write_in_place(formatted, source_text, file)

  when :check
    exit 0 if formatted == source_text
    warn "#{file || 'stdin'}: not formatted"
    exit 1

  when :stdout
    print formatted
  end
end

.format(file, mode) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/jade/cli/fmt.rb', line 34

def format(file, mode)
  source_text = read_source(file)
  source = Source.new(uri: file || 'stdin', text: source_text)

  case Parsing.parse(Lexer.tokenize(source), source:)
  in Ok([ast, comments])
    emit(Formatter.format(ast, comments:, source:) + "\n",
         source_text, file, mode)

  in Err(error)
    warn "Parse error: #{error.message}"
    exit 2
  end
end

.read_source(file) ⇒ Object



49
50
51
52
53
54
55
# File 'lib/jade/cli/fmt.rb', line 49

def read_source(file)
  case
  when file then File.read(file)
  when !$stdin.tty? then $stdin.read
  else usage
  end
end

.run(argv) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/jade/cli/fmt.rb', line 13

def run(argv)
  mode = :stdout
  file = nil

  argv.each do |arg|
    case arg
    when '-i', '--in-place' then mode = :in_place
    when '-c', '--check'    then mode = :check
    when '-h', '--help'     then usage
    when /\A-/
      warn "unknown option: #{arg}"
      usage
    else
      usage if file
      file = arg
    end
  end

  format(file, mode)
end

.usageObject



80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/jade/cli/fmt.rb', line 80

def usage
  warn <<~USAGE
    Usage: jade fmt [options] [file]

    Options:
      -i, --in-place   Rewrite the file in place.
      -c, --check      Exit 0 if formatted, 1 if drift, 2 on parse error.
                       Does not write.
      -h, --help       Show this message.

    Reads from stdin when no file is given.
  USAGE
  exit 1
end

.write_in_place(formatted, source_text, file) ⇒ Object



73
74
75
76
77
78
# File 'lib/jade/cli/fmt.rb', line 73

def write_in_place(formatted, source_text, file)
  return if formatted == source_text

  File.write(file, formatted)
  warn "Formatted #{file}"
end