Module: SyntaxTree::CLI

Defined in:
lib/syntax_tree/cli.rb

Defined Under Namespace

Classes: AST, Action, Check, Color, Debug, Doc, Format, Write

Constant Summary collapse

HELP =

The help message displayed if the input arguments are not correctly ordered or formatted.

<<~HELP
  stree MODE FILE

  MODE: ast | check | debug | doc | format | write
  FILE: one or more paths to files to parse
HELP

Class Method Summary collapse

Class Method Details

.run(argv) ⇒ Object

Run the CLI over the given array of strings that make up the arguments passed to the invocation.



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/syntax_tree/cli.rb', line 147

def run(argv)
  if argv.length < 2
    warn(HELP)
    return 1
  end

  arg, *patterns = argv
  action =
    case arg
    when "a", "ast"
      AST.new
    when "c", "check"
      Check.new
    when "debug"
      Debug.new
    when "doc"
      Doc.new
    when "f", "format"
      Format.new
    when "w", "write"
      Write.new
    else
      warn(HELP)
      return 1
    end

  errored = false
  patterns.each do |pattern|
    Dir.glob(pattern).each do |filepath|
      next unless File.file?(filepath)
      source = SyntaxTree.read(filepath)

      begin
        action.run(filepath, source)
      rescue ParseError => error
        warn("Error: #{error.message}")

        if error.lineno
          highlight_error(error, source)
        else
          warn(error.message)
          warn(error.backtrace)
        end

        errored = true
      rescue Check::UnformattedError, Debug::NonIdempotentFormatError
        errored = true
      rescue => error
        warn(error.message)
        warn(error.backtrace)
        errored = true
      end
    end
  end

  if errored
    action.failure
    1
  else
    action.success
    0
  end
end