diff --no-index: refuse to compare stdin to a directory

When the user runs git diff --no-index file directory we follow the behavior of POSIX diff and rewrite the arguments as git diff --no-index file directory/file Doing that when "file" is "-" (which means "read from stdin") does not make sense so we should error out if the user asks us to compare "-" to a directory. This matches the behavior of GNU diff and diff on *BSD. Signed-off-by: Phillip Wood <phillip.wood@dunelm.org.uk> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Phillip Wood committed Jul 5, 2023 at 20:49 UTC 498198453dbb8ae46becbc83a1ef0979a0eb805d
2 files changed +12 -5
diff-no-index.c
+7 -5
@@ -218,11 +218,13 @@ static void fixup_paths(const char **path, struct strbuf *replacement)
218 {
219 unsigned int isdir0, isdir1;
220
221 - if (path[0] == file_from_standard_input ||
222 - path[1] == file_from_standard_input)
223 - return;
224 - isdir0 = is_directory(path[0]);
225 - isdir1 = is_directory(path[1]);
221 + isdir0 = path[0] != file_from_standard_input && is_directory(path[0]);
222 + isdir1 = path[1] != file_from_standard_input && is_directory(path[1]);
223 +
224 + if ((path[0] == file_from_standard_input && isdir1) ||
225 + (isdir0 && path[1] == file_from_standard_input))
226 + die(_("cannot compare stdin to a directory"));
227 +
228 if (isdir0 == isdir1)
229 return;
230 if (isdir0) {
t/t4053-diff-no-index.sh
+5
@@ -205,4 +205,9 @@ test_expect_success POSIXPERM,SYMLINKS 'diff --no-index normalizes: mode not lik
205 test_cmp expected actual
206 '
207
208 +test_expect_success 'diff --no-index refuses to diff stdin and a directory' '
209 + test_must_fail git diff --no-index -- - a </dev/null 2>err &&
210 + grep "fatal: cannot compare stdin to a directory" err
211 +'
212 +
213 test_done