11class Thor
2+ Correctable =
3+ begin
4+ require 'did_you_mean'
5+
6+ module DidYouMean
7+ # In order to support versions of Ruby that don't have keyword
8+ # arguments, we need our own spell checker class that doesn't take key
9+ # words. Even though this code wouldn't be hit because of the check
10+ # above, it's still necessary because the interpreter would otherwise be
11+ # unable to parse the file.
12+ class NoKwargSpellChecker < SpellChecker
13+ def initialize ( dictionary )
14+ @dictionary = dictionary
15+ end
16+ end
17+ end
18+
19+ DidYouMean ::Correctable
20+ rescue LoadError
21+ end
22+
223 # Thor::Error is raised when it's caused by wrong usage of thor classes. Those
324 # errors have their backtrace suppressed and are nicely shown to the user.
425 #
@@ -10,6 +31,35 @@ class Error < StandardError
1031
1132 # Raised when a command was not found.
1233 class UndefinedCommandError < Error
34+ class SpellChecker
35+ attr_reader :error
36+
37+ def initialize ( error )
38+ @error = error
39+ end
40+
41+ def corrections
42+ @corrections ||= spell_checker . correct ( error . command ) . map ( &:inspect )
43+ end
44+
45+ def spell_checker
46+ DidYouMean ::NoKwargSpellChecker . new ( error . all_commands )
47+ end
48+ end
49+
50+ attr_reader :command , :all_commands
51+
52+ def initialize ( command , all_commands , namespace )
53+ @command = command
54+ @all_commands = all_commands
55+
56+ message = "Could not find command #{ command . inspect } "
57+ message = namespace ? "#{ message } in #{ namespace . inspect } namespace." : "#{ message } ."
58+
59+ super ( message )
60+ end
61+
62+ prepend Correctable if Correctable
1363 end
1464 UndefinedTaskError = UndefinedCommandError
1565
@@ -22,11 +72,46 @@ class InvocationError < Error
2272 end
2373
2474 class UnknownArgumentError < Error
75+ class SpellChecker
76+ attr_reader :error
77+
78+ def initialize ( error )
79+ @error = error
80+ end
81+
82+ def corrections
83+ @corrections ||=
84+ error . unknown . flat_map { |unknown | spell_checker . correct ( unknown ) } . uniq . map ( &:inspect )
85+ end
86+
87+ def spell_checker
88+ @spell_checker ||=
89+ DidYouMean ::NoKwargSpellChecker . new ( error . switches )
90+ end
91+ end
92+
93+ attr_reader :switches , :unknown
94+
95+ def initialize ( switches , unknown )
96+ @switches = switches
97+ @unknown = unknown
98+
99+ super ( "Unknown switches #{ unknown . map ( &:inspect ) . join ( ', ' ) } " )
100+ end
101+
102+ prepend Correctable if Correctable
25103 end
26104
27105 class RequiredArgumentMissingError < InvocationError
28106 end
29107
30108 class MalformattedArgumentError < InvocationError
31109 end
110+
111+ if Correctable
112+ DidYouMean ::SPELL_CHECKERS . merge! (
113+ 'Thor::UndefinedCommandError' => UndefinedCommandError ::SpellChecker ,
114+ 'Thor::UnknownArgumentError' => UnknownArgumentError ::SpellChecker
115+ )
116+ end
32117end
0 commit comments