基于 bundler 的解决方案(非常感谢@fontno),以及我这边的更多调查,这里有一个 hack,以便让它与普通 shell 一起工作。警告:它不优雅,打印出异常堆栈废话,但我认为这有效(请不要犹豫告诉我)。
class Thorough < Thor
ENV["THOR_DEBUG"] = "1"
check_unknown_options!
private
def subcommand(*_) super subcommand(*_)
rescue Thor::Error => e
$stderr.puts e.message
exit 1
end
end
class Test < Thor#ough
desc "example", "an example task"
def example
puts "I'm a thor task!"
end
end
如上所写,它的行为与以前相同(我相信)。现在,在删除#
from之后Thor#ough
,如果 Thor 提出了 an ,它应该以状态 1 退出Error
,从而允许从例如非 ruby shell 进行一些控制。
eruve>thor test:example badarg; echo $?
/Users/eruve/.rvm/gems/ruby-2.0.0-p195/gems/thor-0.18.1/lib/thor/base.rb:482:in `handle_argument_error': ERROR: thor example was called with arguments ["badarg"] (Thor::InvocationError)
Usage: "thor test:example".
from /Users/eruve/.rvm/gems/ruby-2.0.0-p195/gems/thor-0.18.1/lib/thor/command.rb:35:in `rescue in run'
from /Users/eruve/.rvm/gems/ruby-2.0.0-p195/gems/thor-0.18.1/lib/thor/command.rb:21:in `run'
from /Users/eruve/.rvm/gems/ruby-2.0.0-p195/gems/thor-0.18.1/lib/thor/invocation.rb:120:in `invoke_command'
from /Users/eruve/.rvm/gems/ruby-2.0.0-p195/gems/thor-0.18.1/lib/thor.rb:363:in `dispatch'
from /Users/eruve/.rvm/gems/ruby-2.0.0-p195/gems/thor-0.18.1/lib/thor/base.rb:439:in `start'
from /Users/eruve/.rvm/gems/ruby-2.0.0-p195/gems/thor-0.18.1/lib/thor/runner.rb:36:in `method_missing'
from /Users/eruve/.rvm/gems/ruby-2.0.0-p195/gems/thor-0.18.1/lib/thor/command.rb:29:in `run'
from /Users/eruve/.rvm/gems/ruby-2.0.0-p195/gems/thor-0.18.1/lib/thor/command.rb:128:in `run'
from /Users/eruve/.rvm/gems/ruby-2.0.0-p195/gems/thor-0.18.1/lib/thor/invocation.rb:120:in `invoke_command'
from /Users/eruve/.rvm/gems/ruby-2.0.0-p195/gems/thor-0.18.1/lib/thor.rb:363:in `dispatch'
from /Users/eruve/.rvm/gems/ruby-2.0.0-p195/gems/thor-0.18.1/lib/thor/base.rb:439:in `start'
from /Users/eruve/.rvm/gems/ruby-2.0.0-p195/gems/thor-0.18.1/bin/thor:6:in `<top (required)>'
from /Users/eruve/.rvm/gems/ruby-2.0.0-p195/bin/thor:23:in `load'
from /Users/eruve/.rvm/gems/ruby-2.0.0-p195/bin/thor:23:in `<main>'
from /Users/eruve/.rvm/gems/ruby-2.0.0-p195/bin/ruby_noexec_wrapper:14:in `eval'
from /Users/eruve/.rvm/gems/ruby-2.0.0-p195/bin/ruby_noexec_wrapper:14:in `<main>'
1
eruve>thor test:example; echo $?
I'm a thor task!
0
eruve>thor test:example badarg 2>/dev/null; echo $?
1
干杯。PS:我想知道,雷神有很多这样的陷阱吗?如果这是一种预期的行为,那么它的目的/理念与我的项目需求不兼容......黑客不是一个可靠的解决方案。