Skip to content

Commit 00c4939

Browse files
committed
Verify that the commit(s) passed to git diff do not resemble a command-line option
1 parent a08f89b commit 00c4939

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

lib/git/lib.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -526,7 +526,24 @@ def grep(string, opts = {})
526526
hsh
527527
end
528528

529+
# Validate that the given arguments cannot be mistaken for a command-line option
530+
#
531+
# @param arg_name [String] the name of the arguments to mention in the error message
532+
# @param args [Array<String, nil>] the arguments to validate
533+
#
534+
# @raise [ArgumentError] if any of the parameters are a string starting with a hyphen
535+
# @return [void]
536+
#
537+
def validate_no_options(arg_name, *args)
538+
invalid_args = args.select { |arg| arg&.start_with?('-') }
539+
if invalid_args.any?
540+
raise ArgumentError, "Invalid #{arg_name}: '#{invalid_args.join("', '")}'"
541+
end
542+
end
543+
529544
def diff_full(obj1 = 'HEAD', obj2 = nil, opts = {})
545+
validate_no_options('commit or commit range', obj1, obj2)
546+
530547
diff_opts = ['-p']
531548
diff_opts << obj1
532549
diff_opts << obj2 if obj2.is_a?(String)
@@ -536,6 +553,8 @@ def diff_full(obj1 = 'HEAD', obj2 = nil, opts = {})
536553
end
537554

538555
def diff_stats(obj1 = 'HEAD', obj2 = nil, opts = {})
556+
validate_no_options('commit or commit range', obj1, obj2)
557+
539558
diff_opts = ['--numstat']
540559
diff_opts << obj1
541560
diff_opts << obj2 if obj2.is_a?(String)
@@ -556,6 +575,8 @@ def diff_stats(obj1 = 'HEAD', obj2 = nil, opts = {})
556575
end
557576

558577
def diff_name_status(reference1 = nil, reference2 = nil, opts = {})
578+
validate_no_options('commit or commit range', reference1, reference2)
579+
559580
opts_arr = ['--name-status']
560581
opts_arr << reference1 if reference1
561582
opts_arr << reference2 if reference2

tests/units/test_diff.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,5 +118,25 @@ def test_diff_each
118118
assert_equal(160, files['scott/newfile'].patch.size)
119119
end
120120

121+
def test_diff_patch_with_bad_commit
122+
assert_raise(ArgumentError) do
123+
@git.diff('-s').patch
124+
end
121125

126+
assert_raise(ArgumentError) do
127+
@git.diff('gitsearch1', '-s').patch
128+
end
129+
end
130+
131+
def test_diff_name_status_with_bad_commit
132+
assert_raise(ArgumentError) do
133+
@git.diff('-s').name_status
134+
end
135+
end
136+
137+
def test_diff_stats_with_bad_commit
138+
assert_raise(ArgumentError) do
139+
@git.diff('-s').stats
140+
end
141+
end
122142
end

0 commit comments

Comments
 (0)