Skip to content

Commit af45776

Browse files
committed
Merge pull request #7 from jekyll/default_command
Add ability to specify command
2 parents 7eac80f + 28a4201 commit af45776

File tree

3 files changed

+40
-3
lines changed

3 files changed

+40
-3
lines changed

lib/mercenary/command.rb

+24-1
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,25 @@ def description(desc = nil)
4545
@description
4646
end
4747

48+
# Public: Sets the default command
49+
#
50+
# command_name - the command name to be executed in the event no args are
51+
# present
52+
#
53+
# Returns the default command if there is one, `nil` otherwise
54+
def default_command(command_name = nil)
55+
if command_name
56+
if commands.has_key?(command_name)
57+
@default_command = commands[command_name] if command_name
58+
@default_command
59+
else
60+
raise ArgumentError.new("'#{command_name}' couldn't be found in this command's list of commands.")
61+
end
62+
else
63+
@default_command
64+
end
65+
end
66+
4867
# Public: Adds an option switch
4968
#
5069
# sym - the variable key which is used to identify the value of the switch
@@ -148,7 +167,11 @@ def process_options(opts, config)
148167
#
149168
# Returns nothing
150169
def execute(argv = [], config = {})
151-
actions.each { |a| a.call(argv, config) }
170+
if actions.empty? && !default_command.nil?
171+
default_command.execute
172+
else
173+
actions.each { |a| a.call(argv, config) }
174+
end
152175
end
153176

154177
# Public: Check if this command has a subcommand

lib/mercenary/program.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def go(argv)
4646

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

49-
cmd.actions.each { |a| a.call(argv, @config) }
49+
cmd.execute(argv, @config)
5050
end
5151
end
5252
end

spec/command_spec.rb

+15-1
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,18 @@
44

55
context "a basic command" do
66
let(:command) { Mercenary::Command.new(:my_name) }
7+
let(:parent) { Mercenary::Command.new(:my_parent) }
8+
let(:with_sub) do
9+
c = Mercenary::Command.new(:i_have_subcommand)
10+
add_sub.call(c)
11+
c
12+
end
713
let(:command_with_parent) do
814
Mercenary::Command.new(
915
:i_have_parent,
1016
parent
1117
)
1218
end
13-
let(:parent) { Mercenary::Command.new(:my_parent) }
1419
let(:add_sub) do
1520
Proc.new do |c|
1621
c.command(:sub_command) { |p| }
@@ -50,6 +55,15 @@
5055
expect(command.options).to eq([opt])
5156
expect(command.map).to include({opt.first => name})
5257
end
58+
59+
it "raises an ArgumentError if I specify a default_command that isn't there" do
60+
c = command # some weird NameError with the block below?
61+
expect { c.default_command(:nope) }.to raise_error(ArgumentError)
62+
end
63+
64+
it "sets the default_command" do
65+
expect(with_sub.default_command(:sub_command).name).to eq(:sub_command)
66+
end
5367
end
5468

5569
end

0 commit comments

Comments
 (0)