rm: skip sparse paths with missing SKIP_WORKTREE

If a path does not match the sparse-checkout cone but is somehow missing the SKIP_WORKTREE bit, then 'git rm' currently succeeds in removing the file. One reason a user might be in this situation is a merge conflict outside of the sparse-checkout cone. Removing such a file might be problematic for users who are not sure what they are doing. Add a check to path_in_sparse_checkout() when 'git rm' is checking if a path should be considered for deletion. Of course, this check is ignored if the '--sparse' option is specified, allowing users who accept the risks to continue with the removal. This also removes a confusing behavior where a user asks for a directory to be removed, but only the entries that are within the sparse-checkout definition are removed. Now, 'git rm <dir>' will fail without '--sparse' and will succeed in removing all contained paths with '--sparse'. Signed-off-by: Derrick Stolee <dstolee@microsoft.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Derrick Stolee committed Sep 24, 2021 at 15:39 UTC d7c4415e554ac62e49c9616bca5087b4b1310e5a
2 files changed +20 -3
builtin/rm.c
+3 -1
@@ -301,7 +301,9 @@ int cmd_rm(int argc, const char **argv, const char *prefix)
301 for (i = 0; i < active_nr; i++) {
302 const struct cache_entry *ce = active_cache[i];
303
304 - if (!include_sparse && ce_skip_worktree(ce))
304 + if (!include_sparse &&
305 + (ce_skip_worktree(ce) ||
306 + !path_in_sparse_checkout(ce->name, &the_index)))
307 continue;
308 if (!ce_path_match(&the_index, ce, &pathspec, seen))
309 continue;
t/t3602-rm-sparse-checkout.sh
+17 -2
@@ -37,9 +37,13 @@ done
37 test_expect_success 'recursive rm does not remove sparse entries' '
38 git reset --hard &&
39 git sparse-checkout set sub/dir &&
40 - git rm -r sub &&
40 + test_must_fail git rm -r sub &&
41 + git rm --sparse -r sub &&
42 git status --porcelain -uno >actual &&
42 - echo "D sub/dir/e" >expected &&
43 + cat >expected <<-\EOF &&
44 + D sub/d
45 + D sub/dir/e
46 + EOF
47 test_cmp expected actual
48 '
49
@@ -87,4 +91,15 @@ test_expect_success 'do not warn about sparse entries with --ignore-unmatch' '
91 git ls-files --error-unmatch b
92 '
93
94 +test_expect_success 'refuse to rm a non-skip-worktree path outside sparse cone' '
95 + git reset --hard &&
96 + git sparse-checkout set a &&
97 + git update-index --no-skip-worktree b &&
98 + test_must_fail git rm b 2>stderr &&
99 + test_cmp b_error_and_hint stderr &&
100 + git rm --sparse b 2>stderr &&
101 + test_must_be_empty stderr &&
102 + test_path_is_missing b
103 +'
104 +
105 test_done