Skip to content

Commit 6d7ff96

Browse files
authored
Show-source should not raise error even if line_no is wrong (#1145)
Fix SourceFinder to handle wrong line_no case, such as: - line_no passed to eval is wrong - File edited after load
1 parent feeb7be commit 6d7ff96

File tree

2 files changed

+24
-4
lines changed

2 files changed

+24
-4
lines changed

lib/irb/source_finder.rb

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,13 @@ def file_content
2929

3030
def colorized_content
3131
if !binary_file? && file_exist?
32-
end_line = find_end
3332
# To correctly colorize, we need to colorize full content and extract the relevant lines.
34-
colored = IRB::Color.colorize_code(file_content)
35-
colored.lines[@line - 1...end_line].join
33+
colored_lines = IRB::Color.colorize_code(file_content).lines
34+
35+
# Handle wrong line number case: line_no passed to eval is wrong, file is edited after load, etc
36+
return if colored_lines.size < @line
37+
38+
colored_lines[@line - 1...find_end].join
3639
elsif @ast_source
3740
IRB::Color.colorize_code(@ast_source)
3841
end

test/irb/command/test_show_source.rb

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -376,7 +376,7 @@ def test_show_source_shows_binary_source
376376
assert_match(%r[Defined in binary file:.+io/console], out)
377377
end
378378

379-
def test_show_source_method_overrided
379+
def test_show_source_method_overridden
380380
write_ruby <<~RUBY
381381
class Request
382382
def method; 'POST'; end
@@ -393,6 +393,23 @@ def path; '/'; end
393393
assert_match(%r[#{@ruby_file.to_path}:3\s+def path; '/'; end], out)
394394
end
395395

396+
def test_show_source_with_wrong_line
397+
write_ruby <<~RUBY.chomp
398+
eval 'def foo; end', binding, __FILE__, 4 # Line 4 doesn't exist
399+
binding.irb if
400+
def bar; end # Line 3
401+
RUBY
402+
403+
out = run_ruby_file do
404+
type "show_source foo"
405+
type "show_source bar"
406+
type "exit"
407+
end
408+
409+
assert_match(%r[#{@ruby_file.to_path}:4\s+Source not available], out)
410+
assert_match(%r[#{@ruby_file.to_path}:3\s+def bar; end], out)
411+
end
412+
396413
def test_show_source_with_constant_lookup
397414
write_ruby <<~RUBY
398415
X = 1

0 commit comments

Comments
 (0)