Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit e438697

Browse files
committed
Better handling for formatting files with errors
1 parent 62121c1 commit e438697

File tree

2 files changed

+36
-18
lines changed

2 files changed

+36
-18
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) a
66

77
## [Unreleased]
88

9+
### Added
10+
11+
- Better handling for formatting files with errors.
12+
913
## [1.0.0]
1014

1115
### Added

lib/syntax_tree/cli.rb

Lines changed: 32 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,9 @@ def run(filepath, source)
126126
delta = ((Time.now - start) * 1000).round
127127

128128
puts "\r#{color} #{delta}ms"
129+
rescue
130+
puts "\r#{filepath}"
131+
raise
129132
end
130133
end
131134

@@ -177,25 +180,12 @@ def run(argv)
177180
action.run(filepath, source)
178181
rescue ParseError => error
179182
warn("Error: #{error.message}")
180-
lines = source.lines
181-
182-
maximum = [error.lineno + 3, lines.length].min
183-
digits = Math.log10(maximum).ceil
184-
185-
([error.lineno - 3, 0].max...maximum).each do |line_index|
186-
line_number = line_index + 1
187183

188-
if line_number == error.lineno
189-
part1 = Color.red(">")
190-
part2 = Color.gray("%#{digits}d |" % line_number)
191-
warn("#{part1} #{part2} #{lines[line_index]}")
192-
193-
part3 = Color.gray(" %#{digits}s |" % " ")
194-
warn("#{part3} #{" " * error.column}#{Color.red("^")}")
195-
else
196-
prefix = Color.gray(" %#{digits}d |" % line_number)
197-
warn("#{prefix} #{lines[line_index]}")
198-
end
184+
if error.lineno
185+
highlight_error(error, source)
186+
else
187+
warn(error.message)
188+
warn(error.backtrace)
199189
end
200190

201191
errored = true
@@ -232,6 +222,30 @@ def source_for(filepath)
232222

233223
File.read(filepath, encoding: encoding)
234224
end
225+
226+
# Highlights a snippet from a source and parse error.
227+
def highlight_error(error, source)
228+
lines = source.lines
229+
230+
maximum = [error.lineno + 3, lines.length].min
231+
digits = Math.log10(maximum).ceil
232+
233+
([error.lineno - 3, 0].max...maximum).each do |line_index|
234+
line_number = line_index + 1
235+
236+
if line_number == error.lineno
237+
part1 = Color.red(">")
238+
part2 = Color.gray("%#{digits}d |" % line_number)
239+
warn("#{part1} #{part2} #{lines[line_index]}")
240+
241+
part3 = Color.gray(" %#{digits}s |" % " ")
242+
warn("#{part3} #{" " * error.column}#{Color.red("^")}")
243+
else
244+
prefix = Color.gray(" %#{digits}d |" % line_number)
245+
warn("#{prefix} #{lines[line_index]}")
246+
end
247+
end
248+
end
235249
end
236250
end
237251
end

0 commit comments

Comments
 (0)