Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add -t and --trace to Command's default flags #19

Merged
merged 1 commit into from
Feb 20, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions examples/trace.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#!/usr/bin/env ruby

$:.unshift File.join(File.dirname(__FILE__), *%w{ .. lib })

require "mercenary"

# This example sets the logging mode of mercenary to
# debug. Logging messages from "p.logger.debug" will
# be output to STDOUT.

Mercenary.program(:trace) do |p|

p.version "2.0.1"
p.description 'An example of traces in Mercenary'
p.syntax 'trace <subcommand>'

p.action do |_, _|
raise ArgumentError.new("YOU DID SOMETHING TERRIBLE YOU BUFFOON")
end

end
20 changes: 13 additions & 7 deletions lib/mercenary/command.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ class Command
attr_accessor :actions
attr_reader :map
attr_accessor :parent
attr_reader :trace

# Public: Creates a new Command
#
Expand All @@ -17,12 +18,13 @@ class Command
#
# Returns nothing
def initialize(name, parent = nil)
@name = name
@options = []
@commands = {}
@actions = []
@map = {}
@parent = parent
@name = name
@options = []
@commands = {}
@actions = []
@map = {}
@parent = parent
@trace = false
end

# Public: Sets or gets the command version
Expand Down Expand Up @@ -133,7 +135,7 @@ def logger(level = nil)
@logger = Logger.new(STDOUT)
@logger.level = level || Logger::INFO
@logger.formatter = proc do |severity, datetime, progname, msg|
"#{ident} (#{severity}): #{msg}\n"
"#{identity} (#{severity}): #{msg}\n"
end
end

Expand Down Expand Up @@ -191,6 +193,10 @@ def add_default_options(opts)
abort
end

opts.on('-t', '--trace', 'Show full backtrace if an error occurs') do
@trace = true
end

opts.on_tail("-h", "--help", "Show this message") do
puts self
exit
Expand Down
11 changes: 10 additions & 1 deletion lib/mercenary/program.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,16 @@ def go(argv)

logger.debug("Parsed config: #{@config.inspect}")

cmd.execute(argv, @config)
begin
cmd.execute(argv, @config)
rescue => e
if cmd.trace
raise e
else
logger.error e.message
abort
end
end
end
end
end