Skip to content

Commit

Permalink
Gracefully handle incorrect command aliases
Browse files Browse the repository at this point in the history
Even if the aliased target is a helper method or does not exist, IRB
should not crash.

This commit warns users in such cases and treat the input as normal expression.
  • Loading branch information
st0012 committed Jan 3, 2025
1 parent 3e6c12b commit 9eb8bf1
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 5 deletions.
16 changes: 11 additions & 5 deletions lib/irb.rb
Original file line number Diff line number Diff line change
Expand Up @@ -281,13 +281,19 @@ def build_statement(code)
end

code = code.dup.force_encoding(@context.io.encoding)

if (command, arg = @context.parse_command(code))
command_class = Command.load_command(command)
Statement::Command.new(code, command_class, arg)
else
is_assignment_expression = @scanner.assignment_expression?(code, local_variables: @context.local_variables)
Statement::Expression.new(code, is_assignment_expression)
if (command_class = Command.load_command(command))
return Statement::Command.new(code, command_class, arg)
elsif (helper_class = HelperMethod.helper_methods[command])
warn "Using command alias for helper method '#{command}' is not supported"
else
warn "Command '#{command}' does not exist"
end
end

is_assignment_expression = @scanner.assignment_expression?(code, local_variables: @context.local_variables)
Statement::Expression.new(code, is_assignment_expression)
end

def command?(code)
Expand Down
40 changes: 40 additions & 0 deletions test/irb/command/test_command_aliasing.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# frozen_string_literal: true

require "tempfile"
require_relative "../helper"

module TestIRB
class CommandAliasingTest < IntegrationTestCase
def setup
super
write_rc <<~RUBY
IRB.conf[:COMMAND_ALIASES] = {
:c => :conf, # alias to helper method
:f => :foo
}
RUBY

write_ruby <<~'RUBY'
binding.irb
RUBY
end

def test_aliasing_to_helper_method_triggers_warning
out = run_ruby_file do
type "c"
type "exit"
end
assert_include(out, "Using command alias for helper method 'conf' is not supported")
assert_not_include(out, "Maybe IRB bug!")
end

def test_incorrect_alias_triggers_warning
out = run_ruby_file do
type "f"
type "exit"
end
assert_include(out, "Command 'foo' does not exist")
assert_not_include(out, "Maybe IRB bug!")
end
end
end

0 comments on commit 9eb8bf1

Please sign in to comment.