diff --no-index: support limiting by pathspec

The --no-index option of git-diff enables using the diff machinery from git while operating outside of a repository. This mode of git diff is able to compare directories and produce a diff of their contents. When operating git diff in a repository, git has the notion of "pathspecs" which can specify which files to compare. In particular, when using git to diff two trees, you might invoke: $ git diff-tree -r <treeish1> <treeish2>. where the treeish could point to a subdirectory of the repository. When invoked this way, users can limit the selected paths of the tree by using a pathspec. Either by providing some list of paths to accept, or by removing paths via a negative refspec. The git diff --no-index mode does not support pathspecs, and cannot limit the diff output in this way. Other diff programs such as GNU difftools have options for excluding paths based on a pattern match. However, using git diff as a diff replacement has several advantages over many popular diff tools, including coloring moved lines, rename detections, and similar. Teach git diff --no-index how to handle pathspecs to limit the comparisons. This will only be supported if both provided paths are directories. For comparisons where one path isn't a directory, the --no-index mode already has some DWIM shortcuts implemented in the fixup_paths() function. Modify the fixup_paths function to return 1 if both paths are directories. If this is the case, interpret any extra arguments to git diff as pathspecs via parse_pathspec. Use parse_pathspec to load the remaining arguments (if any) to git diff --no-index as pathspec items. Disable PATHSPEC_ATTR support since we do not have a repository to do attribute lookup. Disable PATHSPEC_FROMTOP since we do not have a repository root. All pathspecs are treated as rooted at the provided comparison paths. After loading the pathspec data, calculate skip offsets for skipping past the root portion of the paths. This is required to ensure that pathspecs start matching from the provided path, rather than matching from the absolute path. We could instead pass the paths as prefix values to parse_pathspec. This is slightly problematic because the paths come from the command line and don't necessarily have the proper trailing slash. Additionally, that would require parsing pathspecs multiple times. Pass the pathspec object and the skip offsets into queue_diff, which in-turn must pass them along to read_directory_contents. Modify read_directory_contents to check against the pathspecs when scanning the directory. Use the skip offset to skip past the initial root of the path, and only match against portions that are below the intended directory structure being compared. The search algorithm for finding paths is recursive with read_dir. To make pathspec matching work properly, we must set both DO_MATCH_DIRECTORY and DO_MATCH_LEADING_PATHSPEC. Without DO_MATCH_DIRECTORY, paths like "a/b/c/d" will not match against pathspecs like "a/b/c". This is usually achieved by setting the is_dir parameter of match_pathspec. Without DO_MATCH_LEADING_PATHSPEC, paths like "a/b/c" would not match against pathspecs like "a/b/c/d". This is crucial because we recursively iterate down the directories. We could simply avoid checking pathspecs at subdirectories, but this would force recursion down directories which would simply be skipped. If we always passed DO_MATCH_LEADING_PATHSPEC, then we will incorrectly match in certain cases such as matching 'a/c' against ':(glob)**/d'. The match logic will see that a matches the leading part of the **/ and accept this even tho c doesn't match. To avoid this, use the match_leading_pathspec() variant recently introduced. This sets both flags when is_dir is set, but leaves them both cleared when is_dir is 0. Add test cases and documentation covering the new functionality. Note for the documentation I opted not to move the placement of '--' which is sometimes used to disambiguate arguments. The diff --no-index mode requires exactly 2 arguments determining what to compare. Any additional arguments are interpreted as pathspecs and must come afterwards. Use of '--' would not actually disambiguate anything, since there will never be ambiguity over which arguments represent paths or pathspecs. Signed-off-by: Jacob Keller <jacob.keller@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Jacob Keller committed May 21, 2025 at 16:29 UTC 09fb155f11128b505c227aae673de957c9388240
4 files changed +150 -20
Documentation/git-diff.adoc
+7 -3
@@ -14,7 +14,7 @@ git diff [<options>] --cached [--merge-base] [<commit>] [--] [<path>...]
14 git diff [<options>] [--merge-base] <commit> [<commit>...] <commit> [--] [<path>...]
15 git diff [<options>] <commit>...<commit> [--] [<path>...]
16 git diff [<options>] <blob> <blob>
17 -git diff [<options>] --no-index [--] <path> <path>
17 +git diff [<options>] --no-index [--] <path> <path> [<pathspec>...]
18
19 DESCRIPTION
20 -----------
@@ -31,14 +31,18 @@ files on disk.
31 further add to the index but you still haven't. You can
32 stage these changes by using linkgit:git-add[1].
33
34 -`git diff [<options>] --no-index [--] <path> <path>`::
34 +`git diff [<options>] --no-index [--] <path> <path> [<pathspec>...]`::
35
36 This form is to compare the given two paths on the
37 filesystem. You can omit the `--no-index` option when
38 running the command in a working tree controlled by Git and
39 at least one of the paths points outside the working tree,
40 or when running the command outside a working tree
41 - controlled by Git. This form implies `--exit-code`.
41 + controlled by Git. This form implies `--exit-code`. If both
42 + paths point to directories, additional pathspecs may be
43 + provided. These will limit the files included in the
44 + difference. All such pathspecs must be relative as they
45 + apply to both sides of the diff.
46
47 `git diff [<options>] --cached [--merge-base] [<commit>] [--] [<path>...]`::
48
builtin/diff.c
+1 -1
@@ -35,7 +35,7 @@ static const char builtin_diff_usage[] =
35 " or: git diff [<options>] [--merge-base] <commit> [<commit>...] <commit> [--] [<path>...]\n"
36 " or: git diff [<options>] <commit>...<commit> [--] [<path>...]\n"
37 " or: git diff [<options>] <blob> <blob>\n"
38 -" or: git diff [<options>] --no-index [--] <path> <path>"
38 +" or: git diff [<options>] --no-index [--] <path> <path> [<pathspec>...]"
39 "\n"
40 COMMON_DIFF_OPTIONS_HELP;
41
diff-no-index.c
+67 -16
@@ -15,20 +15,45 @@
15 #include "gettext.h"
16 #include "revision.h"
17 #include "parse-options.h"
18 +#include "pathspec.h"
19 #include "string-list.h"
20 #include "dir.h"
21
21 -static int read_directory_contents(const char *path, struct string_list *list)
22 +static int read_directory_contents(const char *path, struct string_list *list,
23 + const struct pathspec *pathspec,
24 + int skip)
25 {
26 + struct strbuf match = STRBUF_INIT;
27 + int len;
28 DIR *dir;
29 struct dirent *e;
30
31 if (!(dir = opendir(path)))
32 return error("Could not open directory %s", path);
33
29 - while ((e = readdir_skip_dot_and_dotdot(dir)))
34 + if (pathspec) {
35 + strbuf_addstr(&match, path);
36 + strbuf_complete(&match, '/');
37 + strbuf_remove(&match, 0, skip);
38 +
39 + len = match.len;
40 + }
41 +
42 + while ((e = readdir_skip_dot_and_dotdot(dir))) {
43 + if (pathspec) {
44 + strbuf_setlen(&match, len);
45 + strbuf_addstr(&match, e->d_name);
46 +
47 + if (!match_leading_pathspec(NULL, pathspec,
48 + match.buf, match.len,
49 + 0, NULL, e->d_type == DT_DIR ? 1 : 0))
50 + continue;
51 + }
52 +
53 string_list_insert(list, e->d_name);
54 + }
55
56 + strbuf_release(&match);
57 closedir(dir);
58 return 0;
59 }
@@ -131,7 +156,8 @@ static struct diff_filespec *noindex_filespec(const struct git_hash_algo *algop,
156 }
157
158 static int queue_diff(struct diff_options *o, const struct git_hash_algo *algop,
134 - const char *name1, const char *name2, int recursing)
159 + const char *name1, const char *name2, int recursing,
160 + const struct pathspec *ps, int skip1, int skip2)
161 {
162 int mode1 = 0, mode2 = 0;
163 enum special special1 = SPECIAL_NONE, special2 = SPECIAL_NONE;
@@ -171,9 +197,9 @@ static int queue_diff(struct diff_options *o, const struct git_hash_algo *algop,
197 int i1, i2, ret = 0;
198 size_t len1 = 0, len2 = 0;
199
174 - if (name1 && read_directory_contents(name1, &p1))
200 + if (name1 && read_directory_contents(name1, &p1, ps, skip1))
201 return -1;
176 - if (name2 && read_directory_contents(name2, &p2)) {
202 + if (name2 && read_directory_contents(name2, &p2, ps, skip2)) {
203 string_list_clear(&p1, 0);
204 return -1;
205 }
@@ -218,7 +244,7 @@ static int queue_diff(struct diff_options *o, const struct git_hash_algo *algop,
244 n2 = buffer2.buf;
245 }
246
221 - ret = queue_diff(o, algop, n1, n2, 1);
247 + ret = queue_diff(o, algop, n1, n2, 1, ps, skip1, skip2);
248 }
249 string_list_clear(&p1, 0);
250 string_list_clear(&p2, 0);
@@ -258,8 +284,10 @@ static void append_basename(struct strbuf *path, const char *dir, const char *fi
284 * DWIM "diff D F" into "diff D/F F" and "diff F D" into "diff F D/F"
285 * Note that we append the basename of F to D/, so "diff a/b/file D"
286 * becomes "diff a/b/file D/file", not "diff a/b/file D/a/b/file".
287 + *
288 + * Return 1 if both paths are directories, 0 otherwise.
289 */
262 -static void fixup_paths(const char **path, struct strbuf *replacement)
290 +static int fixup_paths(const char **path, struct strbuf *replacement)
291 {
292 struct stat st;
293 unsigned int isdir0 = 0, isdir1 = 0;
@@ -282,26 +310,31 @@ static void fixup_paths(const char **path, struct strbuf *replacement)
310 if ((isdir0 && ispipe1) || (ispipe0 && isdir1))
311 die(_("cannot compare a named pipe to a directory"));
312
285 - if (isdir0 == isdir1)
286 - return;
313 + /* if both paths are directories, we will enable pathspecs */
314 + if (isdir0 && isdir1)
315 + return 1;
316 +
317 if (isdir0) {
318 append_basename(replacement, path[0], path[1]);
319 path[0] = replacement->buf;
290 - } else {
320 + } else if (isdir1) {
321 append_basename(replacement, path[1], path[0]);
322 path[1] = replacement->buf;
323 }
324 +
325 + return 0;
326 }
327
328 static const char * const diff_no_index_usage[] = {
297 - N_("git diff --no-index [<options>] <path> <path>"),
329 + N_("git diff --no-index [<options>] <path> <path> [<pathspec>...]"),
330 NULL
331 };
332
333 int diff_no_index(struct rev_info *revs, const struct git_hash_algo *algop,
334 int implicit_no_index, int argc, const char **argv)
335 {
304 - int i, no_index;
336 + struct pathspec pathspec, *ps = NULL;
337 + int i, no_index, skip1 = 0, skip2 = 0;
338 int ret = 1;
339 const char *paths[2];
340 char *to_free[ARRAY_SIZE(paths)] = { 0 };
@@ -317,13 +350,12 @@ int diff_no_index(struct rev_info *revs, const struct git_hash_algo *algop,
350 options = add_diff_options(no_index_options, &revs->diffopt);
351 argc = parse_options(argc, argv, revs->prefix, options,
352 diff_no_index_usage, 0);
320 - if (argc != 2) {
353 + if (argc < 2) {
354 if (implicit_no_index)
355 warning(_("Not a git repository. Use --no-index to "
356 "compare two paths outside a working tree"));
357 usage_with_options(diff_no_index_usage, options);
358 }
326 - FREE_AND_NULL(options);
359 for (i = 0; i < 2; i++) {
360 const char *p = argv[i];
361 if (!strcmp(p, "-"))
@@ -337,7 +369,23 @@ int diff_no_index(struct rev_info *revs, const struct git_hash_algo *algop,
369 paths[i] = p;
370 }
371
340 - fixup_paths(paths, &replacement);
372 + if (fixup_paths(paths, &replacement)) {
373 + parse_pathspec(&pathspec, PATHSPEC_FROMTOP | PATHSPEC_ATTR,
374 + PATHSPEC_PREFER_FULL | PATHSPEC_NO_REPOSITORY,
375 + NULL, &argv[2]);
376 + if (pathspec.nr)
377 + ps = &pathspec;
378 +
379 + skip1 = strlen(paths[0]);
380 + skip1 += paths[0][skip1] == '/' ? 0 : 1;
381 + skip2 = strlen(paths[1]);
382 + skip2 += paths[1][skip2] == '/' ? 0 : 1;
383 + } else if (argc > 2) {
384 + warning(_("Limiting comparison with pathspecs is only "
385 + "supported if both paths are directories."));
386 + usage_with_options(diff_no_index_usage, options);
387 + }
388 + FREE_AND_NULL(options);
389
390 revs->diffopt.skip_stat_unmatch = 1;
391 if (!revs->diffopt.output_format)
@@ -354,7 +402,8 @@ int diff_no_index(struct rev_info *revs, const struct git_hash_algo *algop,
402 setup_diff_pager(&revs->diffopt);
403 revs->diffopt.flags.exit_with_status = 1;
404
357 - if (queue_diff(&revs->diffopt, algop, paths[0], paths[1], 0))
405 + if (queue_diff(&revs->diffopt, algop, paths[0], paths[1], 0, ps,
406 + skip1, skip2))
407 goto out;
408 diff_set_mnemonic_prefix(&revs->diffopt, "1/", "2/");
409 diffcore_std(&revs->diffopt);
@@ -370,5 +419,7 @@ out:
419 for (i = 0; i < ARRAY_SIZE(to_free); i++)
420 free(to_free[i]);
421 strbuf_release(&replacement);
422 + if (ps)
423 + clear_pathspec(ps);
424 return ret;
425 }
t/t4053-diff-no-index.sh
+75
@@ -295,4 +295,79 @@ test_expect_success PIPE,SYMLINKS 'diff --no-index reads from pipes' '
295 test_cmp expect actual
296 '
297
298 +test_expect_success 'diff --no-index F F rejects pathspecs' '
299 + test_must_fail git diff --no-index -- a/1 a/2 a 2>actual.err &&
300 + test_grep "usage: git diff --no-index" actual.err
301 +'
302 +
303 +test_expect_success 'diff --no-index D F rejects pathspecs' '
304 + test_must_fail git diff --no-index -- a a/2 a 2>actual.err &&
305 + test_grep "usage: git diff --no-index" actual.err
306 +'
307 +
308 +test_expect_success 'diff --no-index F D rejects pathspecs' '
309 + test_must_fail git diff --no-index -- a/1 b b 2>actual.err &&
310 + test_grep "usage: git diff --no-index" actual.err
311 +'
312 +
313 +test_expect_success 'diff --no-index rejects absolute pathspec' '
314 + test_must_fail git diff --no-index -- a b $(pwd)/a/1
315 +'
316 +
317 +test_expect_success 'diff --no-index with pathspec' '
318 + test_expect_code 1 git diff --name-status --no-index a b 1 >actual &&
319 + cat >expect <<-EOF &&
320 + D a/1
321 + EOF
322 + test_cmp expect actual
323 +'
324 +
325 +test_expect_success 'diff --no-index with pathspec no matches' '
326 + test_expect_code 0 git diff --name-status --no-index a b missing
327 +'
328 +
329 +test_expect_success 'diff --no-index with negative pathspec' '
330 + test_expect_code 1 git diff --name-status --no-index a b ":!2" >actual &&
331 + cat >expect <<-EOF &&
332 + D a/1
333 + EOF
334 + test_cmp expect actual
335 +'
336 +
337 +test_expect_success 'setup nested' '
338 + mkdir -p c/1/2 &&
339 + mkdir -p d/1/2 &&
340 + echo 1 >c/1/2/a &&
341 + echo 2 >c/1/2/b
342 +'
343 +
344 +test_expect_success 'diff --no-index with pathspec nested negative pathspec' '
345 + test_expect_code 0 git diff --no-index c d ":!1"
346 +'
347 +
348 +test_expect_success 'diff --no-index with pathspec nested pathspec' '
349 + test_expect_code 1 git diff --name-status --no-index c d 1/2 >actual &&
350 + cat >expect <<-EOF &&
351 + D c/1/2/a
352 + D c/1/2/b
353 + EOF
354 + test_cmp expect actual
355 +'
356 +
357 +test_expect_success 'diff --no-index with pathspec glob' '
358 + test_expect_code 1 git diff --name-status --no-index c d ":(glob)**/a" >actual &&
359 + cat >expect <<-EOF &&
360 + D c/1/2/a
361 + EOF
362 + test_cmp expect actual
363 +'
364 +
365 +test_expect_success 'diff --no-index with pathspec glob and exclude' '
366 + test_expect_code 1 git diff --name-status --no-index c d ":(glob,exclude)**/a" >actual &&
367 + cat >expect <<-EOF &&
368 + D c/1/2/b
369 + EOF
370 + test_cmp expect actual
371 +'
372 +
373 test_done