Skip to content

Commit 60bda03

Browse files
committed
Add safe invocation CLI syntax
SUch syntax is useful for projects like buildpacks and other automated CI/CD tools. It would allow these tools to very easily invoke a task if it exists, without failing if it doesn't.
1 parent c2eeae2 commit 60bda03

File tree

2 files changed

+28
-6
lines changed

2 files changed

+28
-6
lines changed

lib/rake/application.rb

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -155,19 +155,21 @@ def thread_pool # :nodoc:
155155

156156
# Invokes a task with arguments that are extracted from +task_string+
157157
def invoke_task(task_string) # :nodoc:
158-
name, args = parse_task_string(task_string)
158+
name, args, safe_call = parse_task_string(task_string)
159+
return if safe_call && !lookup(name)
160+
159161
t = self[name]
160162
t.invoke(*args)
161163
end
162164

163165
def parse_task_string(string) # :nodoc:
164-
/^([^\[]+)(?:\[(.*)\])$/ =~ string.to_s
165-
166+
/^([^\[]+)(?:\[(.*)\])(\?)?$/ =~ string.to_s
166167
name = $1
167168
remaining_args = $2
169+
safe_call = $~ && !!$~.begin(3)
168170

169-
return string, [] unless name
170-
return name, [] if remaining_args.empty?
171+
return string, [], safe_call unless name
172+
return name, [], safe_call if remaining_args.empty?
171173

172174
args = []
173175

@@ -178,7 +180,7 @@ def parse_task_string(string) # :nodoc:
178180
args << $1.gsub(/\\(.)/, '\1')
179181
end while remaining_args
180182

181-
return name, args
183+
return name, args, safe_call
182184
end
183185

184186
# Provide standard exception handling for the given block.

test/test_rake_application.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,26 @@ def test_good_run
439439
assert_equal "DEFAULT\n", out
440440
end
441441

442+
def test_safe_run
443+
ran = false
444+
445+
@app.options.silent = true
446+
447+
@app.instance_eval do
448+
intern(Rake::Task, "default").enhance { ran = true }
449+
end
450+
451+
rakefile_default
452+
453+
out, err = capture_io do
454+
@app.run %w[--rakelib="" default missing?]
455+
end
456+
457+
assert ran
458+
assert_empty err
459+
assert_equal "DEFAULT\n", out
460+
end
461+
442462
def test_display_task_run
443463
ran = false
444464
@app.last_description = "COMMENT"

0 commit comments

Comments
 (0)