Skip to content

Commit 37ffdc6

Browse files
authored
Warn users about errors in loading RC files (#817)
1. Because `IRB.rc_file` always generates an rc file name, even if the file doesn't exist, we should check the file exists before trying to load it. 2. If any type of errors occur while loading the rc file, we should warn the user about it.
1 parent 1138e96 commit 37ffdc6

2 files changed

Lines changed: 48 additions & 10 deletions

File tree

lib/irb/init.rb

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -389,18 +389,16 @@ def IRB.parse_opts(argv: ::ARGV)
389389
$LOAD_PATH.unshift(*load_path)
390390
end
391391

392-
# running config
392+
# Run the config file
393393
def IRB.run_config
394394
if @CONF[:RC]
395395
begin
396-
load rc_file
397-
rescue LoadError, Errno::ENOENT
398-
rescue # StandardError, ScriptError
399-
print "load error: #{rc_file}\n"
400-
print $!.class, ": ", $!, "\n"
401-
for err in $@[0, $@.size - 2]
402-
print "\t", err, "\n"
403-
end
396+
file = rc_file
397+
# Because rc_file always returns `HOME/.irbrc` even if no rc file is present, we can't warn users about missing rc files.
398+
# Otherwise, it'd be very noisy.
399+
load file if File.exist?(file)
400+
rescue StandardError, ScriptError => e
401+
warn "Error loading RC file '#{file}':\n#{e.full_message(highlight: false)}"
404402
end
405403
end
406404
end
@@ -418,7 +416,7 @@ def IRB.rc_file(ext = IRBRC_EXT)
418416
end
419417
case rc_file = @CONF[:RC_NAME_GENERATOR].call(ext)
420418
when String
421-
return rc_file
419+
rc_file
422420
else
423421
fail IllegalRCNameGenerator
424422
end

test/irb/test_init.rb

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,4 +218,44 @@ def with_argv(argv)
218218
ARGV.replace(orig)
219219
end
220220
end
221+
222+
class InitIntegrationTest < IntegrationTestCase
223+
def test_load_error_in_rc_file_is_warned
224+
write_rc <<~'IRBRC'
225+
require "file_that_does_not_exist"
226+
IRBRC
227+
228+
write_ruby <<~'RUBY'
229+
binding.irb
230+
RUBY
231+
232+
output = run_ruby_file do
233+
type "'foobar'"
234+
type "exit"
235+
end
236+
237+
# IRB session should still be started
238+
assert_includes output, "foobar"
239+
assert_includes output, 'cannot load such file -- file_that_does_not_exist (LoadError)'
240+
end
241+
242+
def test_normal_errors_in_rc_file_is_warned
243+
write_rc <<~'IRBRC'
244+
raise "I'm an error"
245+
IRBRC
246+
247+
write_ruby <<~'RUBY'
248+
binding.irb
249+
RUBY
250+
251+
output = run_ruby_file do
252+
type "'foobar'"
253+
type "exit"
254+
end
255+
256+
# IRB session should still be started
257+
assert_includes output, "foobar"
258+
assert_includes output, 'I\'m an error (RuntimeError)'
259+
end
260+
end
221261
end

0 commit comments

Comments
 (0)