# [PATCH v3 1/5] doc: grep: unify info on configuration variables

31 messages from 2020-05-28 to 2020-09-01. Participants: Matheus Tavares, Elijah Newren, Matheus Tavares Bernardino, Jonathan Nieder.
Thread: https://gitlist.dev/t/53568

## Matheus Tavares, 2020-05-28 01:12

Subject: [PATCH v3 1/5] doc: grep: unify info on configuration variables
Message-ID: <63c195d737dea1dbdc44294483d11a8400f608cc.1590627264.git.matheus.bernardino@usp.br>
URL: https://gitlist.dev/e/63c195d737dea1dbdc44294483d11a8400f608cc.1590627264.git.matheus.bernardino%40usp.br
In-Reply-To: <cover.1590627264.git.matheus.bernardino@usp.br>

```
Explanations about the configuration variables for git-grep are
duplicated in "Documentation/git-grep.txt" and
"Documentation/config/grep.txt", which can make maintenance difficult.
The first also contains a definition not present in the latter
(grep.fullName). To avoid problems like this, let's unify the
information in the second file and include it in the first.

Signed-off-by: Matheus Tavares <matheus.bernardino@usp.br>
---
 Documentation/config/grep.txt | 10 ++++++++--
 Documentation/git-grep.txt    | 36 ++++++-----------------------------
 2 files changed, 14 insertions(+), 32 deletions(-)

diff --git a/Documentation/config/grep.txt b/Documentation/config/grep.txt
index 44abe45a7c..dd51db38e1 100644
--- a/Documentation/config/grep.txt
+++ b/Documentation/config/grep.txt
@@ -16,8 +16,14 @@ grep.extendedRegexp::
 	other than 'default'.
 
 grep.threads::
-	Number of grep worker threads to use.
-	See `grep.threads` in linkgit:git-grep[1] for more information.
+	Number of grep worker threads to use. See `--threads`
+ifndef::git-grep[]
+	in linkgit:git-grep[1]
+endif::git-grep[]
+	for more information.
+
+grep.fullName::
+	If set to true, enable `--full-name` option by default.
 
 grep.fallbackToNoIndex::
 	If set to true, fall back to git grep --no-index if git grep
diff --git a/Documentation/git-grep.txt b/Documentation/git-grep.txt
index a7f9bc99ea..9bdf807584 100644
--- a/Documentation/git-grep.txt
+++ b/Documentation/git-grep.txt
@@ -41,34 +41,8 @@ characters.  An empty string as search expression matches all lines.
 CONFIGURATION
 -------------
 
-grep.lineNumber::
-	If set to true, enable `-n` option by default.
-
-grep.column::
-	If set to true, enable the `--column` option by default.
-
-grep.patternType::
-	Set the default matching behavior. Using a value of 'basic', 'extended',
-	'fixed', or 'perl' will enable the `--basic-regexp`, `--extended-regexp`,
-	`--fixed-strings`, or `--perl-regexp` option accordingly, while the
-	value 'default' will return to the default matching behavior.
-
-grep.extendedRegexp::
-	If set to true, enable `--extended-regexp` option by default. This
-	option is ignored when the `grep.patternType` option is set to a value
-	other than 'default'.
-
-grep.threads::
-	Number of grep worker threads to use. If unset (or set to 0), Git will
-	use as many threads as the number of logical cores available.
-
-grep.fullName::
-	If set to true, enable `--full-name` option by default.
-
-grep.fallbackToNoIndex::
-	If set to true, fall back to git grep --no-index if git grep
-	is executed outside of a git repository.  Defaults to false.
-
+:git-grep: 1
+include::config/grep.txt[]
 
 OPTIONS
 -------
@@ -269,8 +243,10 @@ providing this option will cause it to die.
 	found.
 
 --threads <num>::
-	Number of grep worker threads to use.
-	See `grep.threads` in 'CONFIGURATION' for more information.
+	Number of grep worker threads to use. If not provided (or set to
+	0), Git will use as many worker threads as the number of logical
+	cores available. The default value can also be set with the
+	`grep.threads` configuration.
 
 -f <file>::
 	Read patterns from <file>, one per line.
-- 
2.26.2


```

## Matheus Tavares, 2020-05-28 01:12

Subject: [PATCH v3 0/5] grep: honor sparse checkout and add option to ignore it
Message-ID: <cover.1590627264.git.matheus.bernardino@usp.br>
URL: https://gitlist.dev/e/cover.1590627264.git.matheus.bernardino%40usp.br
In-Reply-To: <cover.1589058209.git.matheus.bernardino@usp.br>

```
This series is based on the discussions in [1]. The idea is to make
git-grep (and other commands, in the future) be able to restrict their
output to the sparsity patterns, when requested by the user.

[1]: https://lore.kernel.org/git/CAHd-oW7e5qCuxZLBeVDq+Th3E+E4+P8=WzJfK8WcG2yz=n_nag@mail.gmail.com/t/#u


Note on tests:

In the previous iteration, the setup test in t7817 (patch 4), used the
following command to set sparse-checkout up:

    git sparse-checkout set "/*" "!b" "!/*/" "/sub"

In this iteration, though, I had to change "/sub" to "sub" (which is not
the same, but should produce the same results in t1787). Using the
previous format, the test failed on Windows because git grep
--recurse-submodules did not recurse into "/sub" (a submodule). I used
[2] to investigate and noticed that sub indeed had the SKIP_WORKTREE bit
set on the repo created by the test on Windows. And the sparse-checkout
file contained the following:

/*
!b
!/*/
C:/Users/<path_to_the_Git_for_Windows_SDK_installation>/sub

I wasn't expecting the conversion from "/sub" to the path above. But I'm
not very familiar with the Git for Windows SDK, so is this conversion
expected? 

Furthermore, `pwd` would output:

    /usr/src/git/t/trash directory.t7817-grep-sparse-checkout

So I think that would explain why the converted path for the "/sub" rule
didn't match sub. Could this be a bug in `git sparse-checkout set`? Or
am I missing something?

[2]: https://github.com/sbp/gin


Main changes since v2:

Added patch 2.

Patch 3:
- Fix reading of extensions.worktreeConfig value in do_git_config_sequence(), to
  get the one from the given git_dir, not the_repository.
- Add --submodule option to test-config helper and regression test for the fixes
  in do_git_config_sequence().

Patch 4:
- Reword commit message to remove snippet about --untracked and --no-index
  respecting the sparsity patterns.
- Don't grep submodules that are excluded by the sparsity patterns.
- Add tests to ensure that submodules (and other paths) that are excluded by the
  sparsity patterns, but present in the working tree, are not grepped.
- Some minor variable renames in tests, for better readability.

Patch 5:
- Mention in sparse config docs that --[no-]restrict-to-sparse-paths won't
  affect writting commands.
- die() in grep when --[no-]restrict-to-sparse-paths is used with --no-index
  or --untracked, and add test for this behavior.
- Use test_when_finished and test_config, when possible, to avoid breaking next
  test cases on a test error.
- Adjust the behavior of --[no-]restrict-to-sparse-paths to follow the ideas
  proposed by Elijah in [3] and [4]. Also add more tests for the different
  cases where this option is relevant and improve docs at
  Documentation/config/sparse.txt.

[3]: https://lore.kernel.org/git/CABPp-BE6M9ATDYuQh8f_r3S00dM2Cv9vM3T5j5W_odbVzhC-5A@mail.gmail.com/
[4]: https://lore.kernel.org/git/CABPp-BGEPU49yRN2FRtwhYn6Uh+scGKEFYP4G2GH6=uBTN1SCw@mail.gmail.com/

CI: https://github.com/matheustavares/git/actions/runs/117388742

Matheus Tavares (5):
  doc: grep: unify info on configuration variables
  t/helper/test-config: return exit codes consistently
  config: correctly read worktree configs in submodules
  grep: honor sparse checkout patterns
  config: add setting to ignore sparsity patterns in some cmds

 Documentation/config.txt               |   2 +
 Documentation/config/grep.txt          |  10 +-
 Documentation/config/sparse.txt        |  24 ++
 Documentation/git-grep.txt             |  37 +--
 Documentation/git.txt                  |   4 +
 Makefile                               |   1 +
 builtin/grep.c                         | 134 ++++++++++-
 config.c                               |  21 +-
 contrib/completion/git-completion.bash |   2 +
 git.c                                  |   6 +
 sparse-checkout.c                      |  16 ++
 sparse-checkout.h                      |  11 +
 t/helper/test-config.c                 | 183 +++++++++------
 t/t2404-worktree-config.sh             |  16 ++
 t/t7011-skip-worktree-reading.sh       |   9 -
 t/t7817-grep-sparse-checkout.sh        | 300 +++++++++++++++++++++++++
 t/t9902-completion.sh                  |   4 +-
 17 files changed, 663 insertions(+), 117 deletions(-)
 create mode 100644 Documentation/config/sparse.txt
 create mode 100644 sparse-checkout.c
 create mode 100644 sparse-checkout.h
 create mode 100755 t/t7817-grep-sparse-checkout.sh

Range-diff against v2:
1:  c344d22313 = 1:  63c195d737 doc: grep: unify info on configuration variables
2:  882310b69f < -:  ---------- config: load the correct config.worktree file
-:  ---------- > 2:  43402007ad t/helper/test-config: return exit codes consistently
-:  ---------- > 3:  448e0efffd config: correctly read worktree configs in submodules
3:  e00674c727 ! 4:  5ddac81818 grep: honor sparse checkout patterns
    @@ Commit message
         git-grep currently ignores the sparsity patterns and report all matches
         found outside this subset, which kind of goes in the opposite direction.
         Let's fix that, making it honor the sparsity boundaries for every
    -    grepping case:
    +    grepping case where this is relevant:
     
         - git grep in worktree
         - git grep --cached
         - git grep $REVISION
    -    - git grep --untracked and git grep --no-index (which already respect
    -      sparse checkout boundaries)
     
    -    This is also what some users reported[1] they would want as the default
    -    behavior.
    +    For the worktree case, we will not grep paths that have the
    +    SKIP_WORKTREE bit set, even if they are present for some reason (e.g.
    +    manually created after `git sparse-checkout init`). But the next patch
    +    will add an option to do so. (See 'Note' below.)
     
    -    Note: for `git grep $REVISION`, we will choose to honor the sparsity
    -    patterns only when $REVISION is a commit-ish object. The reason is that,
    -    for a tree, we don't know whether it represents the root of a
    -    repository or a subtree. So we wouldn't be able to correctly match it
    -    against the sparsity patterns. E.g. suppose we have a repository with
    -    these two sparsity rules: "/*" and "!/a"; and the following structure:
    +    For `git grep $REVISION`, we will choose to honor the sparsity patterns
    +    only when $REVISION is a commit-ish object. The reason is that, for a
    +    tree, we don't know whether it represents the root of a repository or a
    +    subtree. So we wouldn't be able to correctly match it against the
    +    sparsity patterns. E.g. suppose we have a repository with these two
    +    sparsity rules: "/*" and "!/a"; and the following structure:
     
         /
         | - a (file)
    @@ Commit message
         therefore it would wrongly match the pattern "!/a". Furthermore, for a
         search in a blob object, we wouldn't even have a path to check the
         patterns against. So, let's ignore the sparsity patterns when grepping
    -    non-commit-ish objects (tags to commits should be fine).
    +    non-commit-ish objects.
     
    -    Finally, the old behavior may still be desirable for some use cases. So
    -    the next patch will add an option to allow restoring it when needed.
    +    Note: The behavior introduced in this patch is what some users have
    +    reported[1] that they would like by default. But the old behavior is
    +    still desirable for some use cases. Therefore, the next patch will add
    +    an option to allow restoring it when needed.
     
         [1]: https://lore.kernel.org/git/CABPp-BGuFhDwWZBRaD3nA8ui46wor-4=Ha1G1oApsfF8KNpfGQ@mail.gmail.com/
     
    @@ builtin/grep.c: static int grep_cache(struct grep_opt *opt,
      	for (nr = 0; nr < repo->index->cache_nr; nr++) {
      		const struct cache_entry *ce = repo->index->cache[nr];
     +
    -+		if (ce_skip_worktree(ce) && !S_ISGITLINK(ce->ce_mode))
    ++		if (ce_skip_worktree(ce))
     +			continue;
     +
      		strbuf_setlen(&name, name_base_len);
    @@ builtin/grep.c: static int grep_cache(struct grep_opt *opt,
     +			      enum pattern_match_result *match)
     +{
     +	int dtype = DT_UNKNOWN;
    -+
    -+	if (S_ISGITLINK(entry_mode))
    -+		return 1;
    ++	int is_dir = S_ISDIR(entry_mode);
     +
     +	if (parent_match == MATCHED_RECURSIVE) {
     +		*match = parent_match;
     +		return 1;
     +	}
     +
    -+	if (S_ISDIR(entry_mode) && !is_dir_sep(path->buf[path->len - 1]))
    ++	if (is_dir && !is_dir_sep(path->buf[path->len - 1]))
     +		strbuf_addch(path, '/');
     +
     +	*match = path_matches_pattern_list(path->buf, path->len,
    @@ builtin/grep.c: static int grep_cache(struct grep_opt *opt,
     +	if (*match == UNDECIDED)
     +		*match = parent_match;
     +
    -+	if (S_ISDIR(entry_mode))
    ++	if (is_dir)
     +		strbuf_trim_trailing_dir_sep(path);
     +
    -+	if (*match == NOT_MATCHED && (S_ISREG(entry_mode) ||
    -+	    (S_ISDIR(entry_mode) && sparsity->use_cone_patterns)))
    -+		return 0;
    ++	if (*match == NOT_MATCHED &&
    ++		(!is_dir || (is_dir && sparsity->use_cone_patterns)))
    ++	     return 0;
     +
     +	return 1;
     +}
    @@ t/t7817-grep-sparse-checkout.sh (new)
     +|-- b
     +|-- dir
     +|   `-- c
    -+`-- sub
    -+    |-- A
    -+    |   `-- a
    -+    `-- B
    -+	`-- b
    -+
    -+Where . has non-cone mode sparsity patterns and sub is a submodule with cone
    -+mode sparsity patterns. The resulting sparse-checkout should leave the following
    -+structure:
    ++|-- sub
    ++|   |-- A
    ++|   |   `-- a
    ++|   `-- B
    ++|       `-- b
    ++`-- sub2
    ++    `-- a
    ++
    ++Where . has non-cone mode sparsity patterns, sub is a submodule with cone mode
    ++sparsity patterns and sub2 is a submodule that is excluded by the superproject
    ++sparsity patterns. The resulting sparse checkout should leave the following
    ++structure on the working tree:
     +
     +.
     +|-- a
    -+`-- sub
    -+    `-- B
    -+	`-- b
    ++|-- sub
    ++|   `-- B
    ++|       `-- b
    ++`-- sub2
    ++    `-- a
    ++
    ++But note that sub2 should have the SKIP_WORKTREE bit set.
     +'
     +
     +. ./test-lib.sh
    @@ t/t7817-grep-sparse-checkout.sh (new)
     +		git sparse-checkout set B
     +	) &&
     +
    ++	git init sub2 &&
    ++	(
    ++		cd sub2 &&
    ++		echo "text" >a &&
    ++		git add a &&
    ++		git commit -m sub2
    ++	) &&
    ++
     +	git submodule add ./sub &&
    ++	git submodule add ./sub2 &&
     +	git add a b dir &&
     +	git commit -m super &&
     +	git sparse-checkout init --no-cone &&
    -+	git sparse-checkout set "/*" "!b" "!/*/" &&
    ++	git sparse-checkout set "/*" "!b" "!/*/" "sub" &&
     +
    -+	git tag -am t-commit t-commit HEAD &&
    ++	git tag -am tag-to-commit tag-to-commit HEAD &&
     +	tree=$(git rev-parse HEAD^{tree}) &&
    -+	git tag -am t-tree t-tree $tree &&
    ++	git tag -am tag-to-tree tag-to-tree $tree &&
     +
     +	test_path_is_missing b &&
     +	test_path_is_missing dir &&
     +	test_path_is_missing sub/A &&
     +	test_path_is_file a &&
    -+	test_path_is_file sub/B/b
    ++	test_path_is_file sub/B/b &&
    ++	test_path_is_file sub2/a
     +'
     +
    ++# The test bellow checks a special case: the sparsity patterns exclude '/b'
    ++# and sparse checkout is enable, but the path exists on the working tree (e.g.
    ++# manually created after `git sparse-checkout init`). In this case, grep should
    ++# skip it.
     +test_expect_success 'grep in working tree should honor sparse checkout' '
     +	cat >expect <<-EOF &&
     +	a:text
     +	EOF
    ++	echo "new-text" >b &&
    ++	test_when_finished "rm b" &&
     +	git grep "text" >actual &&
     +	test_cmp expect actual
     +'
    @@ t/t7817-grep-sparse-checkout.sh (new)
     +	cat >expect_commit <<-EOF &&
     +	$commit:a:text
     +	EOF
    -+	cat >expect_t-commit <<-EOF &&
    -+	t-commit:a:text
    ++	cat >expect_tag-to-commit <<-EOF &&
    ++	tag-to-commit:a:text
     +	EOF
     +	git grep "text" $commit >actual_commit &&
     +	test_cmp expect_commit actual_commit &&
    -+	git grep "text" t-commit >actual_t-commit &&
    -+	test_cmp expect_t-commit actual_t-commit
    ++	git grep "text" tag-to-commit >actual_tag-to-commit &&
    ++	test_cmp expect_tag-to-commit actual_tag-to-commit
     +'
     +
     +test_expect_success 'grep <tree-ish> should ignore sparsity patterns' '
    @@ t/t7817-grep-sparse-checkout.sh (new)
     +	$tree:b:text
     +	$tree:dir/c:text
     +	EOF
    -+	cat >expect_t-tree <<-EOF &&
    -+	t-tree:a:text
    -+	t-tree:b:text
    -+	t-tree:dir/c:text
    ++	cat >expect_tag-to-tree <<-EOF &&
    ++	tag-to-tree:a:text
    ++	tag-to-tree:b:text
    ++	tag-to-tree:dir/c:text
     +	EOF
     +	git grep "text" $tree >actual_tree &&
     +	test_cmp expect_tree actual_tree &&
    -+	git grep "text" t-tree >actual_t-tree &&
    -+	test_cmp expect_t-tree actual_t-tree
    ++	git grep "text" tag-to-tree >actual_tag-to-tree &&
    ++	test_cmp expect_tag-to-tree actual_tag-to-tree
    ++'
    ++
    ++# Note that sub2/ is present in the worktree but it is excluded by the sparsity
    ++# patterns, so grep should not recurse into it.
    ++test_expect_success 'grep --recurse-submodules should honor sparse checkout in submodule' '
    ++	cat >expect <<-EOF &&
    ++	a:text
    ++	sub/B/b:text
    ++	EOF
    ++	git grep --recurse-submodules "text" >actual &&
    ++	test_cmp expect actual
     +'
     +
     +test_expect_success 'grep --recurse-submodules --cached should honor sparse checkout in submodule' '
    @@ t/t7817-grep-sparse-checkout.sh (new)
     +	$commit:a:text
     +	$commit:sub/B/b:text
     +	EOF
    -+	cat >expect_t-commit <<-EOF &&
    -+	t-commit:a:text
    -+	t-commit:sub/B/b:text
    ++	cat >expect_tag-to-commit <<-EOF &&
    ++	tag-to-commit:a:text
    ++	tag-to-commit:sub/B/b:text
     +	EOF
     +	git grep --recurse-submodules "text" $commit >actual_commit &&
     +	test_cmp expect_commit actual_commit &&
    -+	git grep --recurse-submodules "text" t-commit >actual_t-commit &&
    -+	test_cmp expect_t-commit actual_t-commit
    ++	git grep --recurse-submodules "text" tag-to-commit >actual_tag-to-commit &&
    ++	test_cmp expect_tag-to-commit actual_tag-to-commit
     +'
     +
     +test_done
4:  3e9e906249 ! 5:  748b1e955c config: add setting to ignore sparsity patterns in some cmds
    @@ Commit message
         subset of files in which they are interested; and allow some commands to
         possibly perform better, by not considering uninteresting paths. For
         this reason, we taught grep to honor the sparsity patterns, in the
    -    previous commit. But, on the other hand, allowing grep and the other
    +    previous patch. But, on the other hand, allowing grep and the other
         commands mentioned to optionally ignore the patterns also make for some
         interesting use cases. E.g. using grep to search for a function
    -    definition that resides outside the sparse checkout.
    +    documentation that resides outside the sparse checkout.
     
         In any case, there is no current way for users to configure the behavior
         they want for these commands. Aiming to provide this flexibility, let's
    @@ Documentation/config/sparse.txt (new)
     ++
     +When this option is true (default), some git commands may limit their behavior
     +to the paths specified by the sparsity patterns, or to the intersection of
    -+those paths and any (like `*.c) that the user might also specify on the command
    -+line. When false, the affected commands will work on full trees, ignoring the
    -+sparsity patterns. For now, only git-grep honors this setting. In this command,
    -+the restriction becomes relevant in one of these three cases: with --cached;
    -+when a commit-ish is given; when searching a working tree that contains paths
    -+previously excluded by the sparsity patterns.
    ++those paths and any (like `*.c`) that the user might also specify on the
    ++command line. When false, the affected commands will work on full trees,
    ++ignoring the sparsity patterns. For now, only git-grep honors this setting. In
    ++this command, the restriction takes effect in three cases: with --cached; when
    ++a commit-ish is given; when searching a working tree where some paths excluded
    ++by the sparsity patterns are present (e.g. manually created paths or not
    ++removed submodules).
     ++
     +Note: commands which export, integrity check, or create history will always
     +operate on full trees (e.g. fast-export, format-patch, fsck, commit, etc.),
    -+unaffected by any sparsity patterns.
    ++unaffected by any sparsity patterns. Also, writting commands such as
    ++sparse-checkout and read-tree will not be affected by this configuration.
     
      ## Documentation/git-grep.txt ##
     @@ Documentation/git-grep.txt: characters.  An empty string as search expression matches all lines.
    @@ builtin/grep.c: static int grep_cache(struct grep_opt *opt,
      	for (nr = 0; nr < repo->index->cache_nr; nr++) {
      		const struct cache_entry *ce = repo->index->cache[nr];
      
    --		if (ce_skip_worktree(ce) && !S_ISGITLINK(ce->ce_mode))
    -+		if (sparse_paths_only && ce_skip_worktree(ce) &&
    -+		    !S_ISGITLINK(ce->ce_mode))
    +-		if (ce_skip_worktree(ce))
    ++		if (sparse_paths_only && ce_skip_worktree(ce))
      			continue;
      
      		strbuf_setlen(&name, name_base_len);
    @@ builtin/grep.c: int cmd_grep(int argc, const char **argv, const char *prefix)
      		int use_exclude = (opt_exclude < 0) ? use_index : !!opt_exclude;
     +
     +		if (opt_restrict_to_sparse_paths >= 0) {
    -+			warning(_("--[no-]restrict-to-sparse-paths is ignored"
    -+				  " with --no-index or --untracked"));
    ++			die(_("--[no-]restrict-to-sparse-paths is incompatible"
    ++				  " with --no-index and --untracked"));
     +		}
     +
      		hit = grep_directory(&opt, &pathspec, use_exclude, use_index);
    @@ sparse-checkout.h (new)
     
      ## t/t7817-grep-sparse-checkout.sh ##
     @@ t/t7817-grep-sparse-checkout.sh: test_expect_success 'setup' '
    - 	test_path_is_file sub/B/b
    + 	test_path_is_file sub2/a
      '
      
    +-# The test bellow checks a special case: the sparsity patterns exclude '/b'
     +# The two tests bellow check a special case: the sparsity patterns exclude '/b'
    -+# and sparse checkout is enable, but the path exists on the working tree (e.g.
    -+# manually created after `git sparse-checkout init`). In this case, grep should
    -+# honor --restrict-to-sparse-paths.
    + # and sparse checkout is enable, but the path exists on the working tree (e.g.
    + # manually created after `git sparse-checkout init`). In this case, grep should
    +-# skip it.
    ++# skip the file by default, but not with --no-restrict-to-sparse-paths.
      test_expect_success 'grep in working tree should honor sparse checkout' '
      	cat >expect <<-EOF &&
      	a:text
    - 	EOF
    -+	echo newtext >b &&
    +@@ t/t7817-grep-sparse-checkout.sh: test_expect_success 'grep in working tree should honor sparse checkout' '
      	git grep "text" >actual &&
    --	test_cmp expect actual
    -+	test_cmp expect actual &&
    -+	rm b
    -+'
    + 	test_cmp expect actual
    + '
     +test_expect_success 'grep w/ --no-restrict-to-sparse-paths for sparsely excluded but present paths' '
     +	cat >expect <<-EOF &&
     +	a:text
    -+	b:newtext
    ++	b:new-text
     +	EOF
    -+	echo newtext >b &&
    ++	echo "new-text" >b &&
    ++	test_when_finished "rm b" &&
     +	git --no-restrict-to-sparse-paths grep "text" >actual &&
    -+	test_cmp expect actual &&
    -+	rm b
    - '
    ++	test_cmp expect actual
    ++'
      
      test_expect_success 'grep --cached should honor sparse checkout' '
    + 	cat >expect <<-EOF &&
    +@@ t/t7817-grep-sparse-checkout.sh: test_expect_success 'grep <tree-ish> should ignore sparsity patterns' '
    + '
    + 
    + # Note that sub2/ is present in the worktree but it is excluded by the sparsity
    +-# patterns, so grep should not recurse into it.
    ++# patterns, so grep should only recurse into it with --no-restrict-to-sparse-paths.
    + test_expect_success 'grep --recurse-submodules should honor sparse checkout in submodule' '
    + 	cat >expect <<-EOF &&
    + 	a:text
    +@@ t/t7817-grep-sparse-checkout.sh: test_expect_success 'grep --recurse-submodules should honor sparse checkout in s
    + 	git grep --recurse-submodules "text" >actual &&
    + 	test_cmp expect actual
    + '
    ++test_expect_success 'grep --recurse-submodules should search in excluded submodules w/ --no-restrict-to-sparse-paths' '
    ++	cat >expect <<-EOF &&
    ++	a:text
    ++	sub/B/b:text
    ++	sub2/a:text
    ++	EOF
    ++	git --no-restrict-to-sparse-paths grep --recurse-submodules "text" >actual &&
    ++	test_cmp expect actual
    ++'
    + 
    + test_expect_success 'grep --recurse-submodules --cached should honor sparse checkout in submodule' '
    + 	cat >expect <<-EOF &&
     @@ t/t7817-grep-sparse-checkout.sh: test_expect_success 'grep --recurse-submodules <commit-ish> should honor sparse
    - 	test_cmp expect_t-commit actual_t-commit
    + 	test_cmp expect_tag-to-commit actual_tag-to-commit
      '
      
     +for cmd in 'git --no-restrict-to-sparse-paths grep' \
    @@ t/t7817-grep-sparse-checkout.sh: test_expect_success 'grep --recurse-submodules
     +		$commit:b:text
     +		$commit:dir/c:text
     +		EOF
    -+		cat >expect_t-commit <<-EOF &&
    -+		t-commit:a:text
    -+		t-commit:b:text
    -+		t-commit:dir/c:text
    ++		cat >expect_tag-to-commit <<-EOF &&
    ++		tag-to-commit:a:text
    ++		tag-to-commit:b:text
    ++		tag-to-commit:dir/c:text
     +		EOF
     +		$cmd "text" $commit >actual_commit &&
     +		test_cmp expect_commit actual_commit &&
    -+		$cmd "text" t-commit >actual_t-commit &&
    -+		test_cmp expect_t-commit actual_t-commit
    ++		$cmd "text" tag-to-commit >actual_tag-to-commit &&
    ++		test_cmp expect_tag-to-commit actual_tag-to-commit
     +	'
     +done
     +
    ++test_expect_success 'grep --recurse-submodules --cached \w --no-restrict-to-sparse-paths' '
    ++	cat >expect <<-EOF &&
    ++	a:text
    ++	b:text
    ++	dir/c:text
    ++	sub/A/a:text
    ++	sub/B/b:text
    ++	sub2/a:text
    ++	EOF
    ++	git --no-restrict-to-sparse-paths grep --recurse-submodules --cached \
    ++		"text" >actual &&
    ++	test_cmp expect actual
    ++'
    ++
    ++test_expect_success 'grep --recurse-submodules <commit-ish> \w --no-restrict-to-sparse-paths' '
    ++	commit=$(git rev-parse HEAD) &&
    ++	cat >expect_commit <<-EOF &&
    ++	$commit:a:text
    ++	$commit:b:text
    ++	$commit:dir/c:text
    ++	$commit:sub/A/a:text
    ++	$commit:sub/B/b:text
    ++	$commit:sub2/a:text
    ++	EOF
    ++	cat >expect_tag-to-commit <<-EOF &&
    ++	tag-to-commit:a:text
    ++	tag-to-commit:b:text
    ++	tag-to-commit:dir/c:text
    ++	tag-to-commit:sub/A/a:text
    ++	tag-to-commit:sub/B/b:text
    ++	tag-to-commit:sub2/a:text
    ++	EOF
    ++	git --no-restrict-to-sparse-paths grep --recurse-submodules "text" \
    ++		$commit >actual_commit &&
    ++	test_cmp expect_commit actual_commit &&
    ++	git --no-restrict-to-sparse-paths grep --recurse-submodules "text" \
    ++		tag-to-commit >actual_tag-to-commit &&
    ++	test_cmp expect_tag-to-commit actual_tag-to-commit
    ++'
    ++
     +test_expect_success 'should respect the sparse.restrictCmds values from submodules' '
     +	cat >expect <<-EOF &&
     +	a:text
     +	sub/A/a:text
     +	sub/B/b:text
     +	EOF
    -+	git -C sub config sparse.restrictCmds false &&
    ++	test_config -C sub sparse.restrictCmds false &&
     +	git grep --cached --recurse-submodules "text" >actual &&
    -+	test_cmp expect actual &&
    -+	git -C sub config --unset sparse.restrictCmds
    ++	test_cmp expect actual
     +'
     +
     +test_expect_success 'should propagate --[no]-restrict-to-sparse-paths to submodules' '
    @@ t/t7817-grep-sparse-checkout.sh: test_expect_success 'grep --recurse-submodules
     +	dir/c:text
     +	sub/A/a:text
     +	sub/B/b:text
    ++	sub2/a:text
     +	EOF
    -+	git -C sub config sparse.restrictCmds true &&
    ++	test_config -C sub sparse.restrictCmds true &&
     +	git --no-restrict-to-sparse-paths grep --cached --recurse-submodules "text" >actual &&
    -+	test_cmp expect actual &&
    -+	git -C sub config --unset sparse.restrictCmds
    ++	test_cmp expect actual
     +'
    ++
    ++for opt in '--untracked' '--no-index'
    ++do
    ++	test_expect_success "--[no]-restrict-to-sparse-paths and $opt are incompatible" "
    ++		test_must_fail git --restrict-to-sparse-paths grep $opt . 2>actual &&
    ++		test_i18ngrep 'restrict-to-sparse-paths is incompatible with' actual
    ++	"
    ++done
     +
      test_done
     
-- 
2.26.2


```

## Matheus Tavares, 2020-05-28 01:13

Subject: [PATCH v3 3/5] config: correctly read worktree configs in submodules
Message-ID: <448e0efffd0bbc89d8ea891923f242b5123c5826.1590627264.git.matheus.bernardino@usp.br>
URL: https://gitlist.dev/e/448e0efffd0bbc89d8ea891923f242b5123c5826.1590627264.git.matheus.bernardino%40usp.br
In-Reply-To: <cover.1590627264.git.matheus.bernardino@usp.br>

```
One of the steps in do_git_config_sequence() is to load the
worktree-specific config file. Although the function receives a git_dir
string, it relies on git_pathdup(), which uses the_repository->git_dir,
to make the path to the file. Furthermore, it also checks that
extensions.worktreeConfig is set through the
repository_format_worktree_config variable, which refers to
the_repository only. Thus, when a submodule has worktree settings, a
command executed in the superproject that recurses into the submodule
won't find the said settings.

Such a scenario might not be needed now, but it will be in the following
patch. git-grep will learn to honor sparse checkouts and, when running
with --recurse-submodules, the submodule's sparse checkout settings must
be loaded. As these settings are stored in the config.worktree file,
they would be ignored without this patch. So let's fix this by reading
the right config.worktree file and extensions.worktreeConfig setting,
based on the git_dir and commondir paths given to
do_git_config_sequence(). Also add a test to avoid any regressions.

Signed-off-by: Matheus Tavares <matheus.bernardino@usp.br>
---
 config.c                   |  21 +++++--
 t/helper/test-config.c     | 119 +++++++++++++++++++++++++++----------
 t/t2404-worktree-config.sh |  16 +++++
 3 files changed, 118 insertions(+), 38 deletions(-)

diff --git a/config.c b/config.c
index 8db9c77098..c2d56309dc 100644
--- a/config.c
+++ b/config.c
@@ -1747,11 +1747,22 @@ static int do_git_config_sequence(const struct config_options *opts,
 		ret += git_config_from_file(fn, repo_config, data);
 
 	current_parsing_scope = CONFIG_SCOPE_WORKTREE;
-	if (!opts->ignore_worktree && repository_format_worktree_config) {
-		char *path = git_pathdup("config.worktree");
-		if (!access_or_die(path, R_OK, 0))
-			ret += git_config_from_file(fn, path, data);
-		free(path);
+	if (!opts->ignore_worktree && repo_config && opts->git_dir) {
+		struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
+		struct strbuf buf = STRBUF_INIT;
+
+		read_repository_format(&repo_fmt, repo_config);
+
+		if (!verify_repository_format(&repo_fmt, &buf) &&
+		    repo_fmt.worktree_config) {
+			char *path = mkpathdup("%s/config.worktree", opts->git_dir);
+			if (!access_or_die(path, R_OK, 0))
+				ret += git_config_from_file(fn, path, data);
+			free(path);
+		}
+
+		strbuf_release(&buf);
+		clear_repository_format(&repo_fmt);
 	}
 
 	current_parsing_scope = CONFIG_SCOPE_COMMAND;
diff --git a/t/helper/test-config.c b/t/helper/test-config.c
index 1c8e965840..284f83a921 100644
--- a/t/helper/test-config.c
+++ b/t/helper/test-config.c
@@ -2,12 +2,19 @@
 #include "cache.h"
 #include "config.h"
 #include "string-list.h"
+#include "submodule-config.h"
 
 /*
  * This program exposes the C API of the configuration mechanism
  * as a set of simple commands in order to facilitate testing.
  *
- * Reads stdin and prints result of command to stdout:
+ * Usage: test-tool config [--submodule=<path>] <cmd> [<args>]
+ *
+ * If --submodule=<path> is given, <cmd> will operate on the submodule at the
+ * given <path>. This option is not valid for the commands: read_early_config,
+ * configset_get_value and configset_get_value_multi.
+ *
+ * Possible cmds are:
  *
  * get_value -> prints the value with highest priority for the entered key
  *
@@ -84,33 +91,63 @@ int cmd__config(int argc, const char **argv)
 	int i, val;
 	const char *v;
 	const struct string_list *strptr;
-	struct config_set cs;
+	struct config_set cs = { .hash_initialized = 0 };
 	enum test_config_exit_code ret = TC_SUCCESS;
+	struct repository *repo = the_repository;
+	const char *subrepo_path = NULL;
+
+	argc--; /* skip over "config" */
+	argv++;
+
+	if (argc == 0)
+		goto print_usage_error;
+
+	if (skip_prefix(*argv, "--submodule=", &subrepo_path)) {
+		argc--;
+		argv++;
+		if (argc == 0)
+			goto print_usage_error;
+	}
 
-	if (argc == 3 && !strcmp(argv[1], "read_early_config")) {
-		read_early_config(early_config_cb, (void *)argv[2]);
+	if (argc == 2 && !strcmp(argv[0], "read_early_config")) {
+		if (subrepo_path) {
+			fprintf(stderr, "Cannot use --submodule with read_early_config\n");
+			return TC_USAGE_ERROR;
+		}
+		read_early_config(early_config_cb, (void *)argv[1]);
 		return TC_SUCCESS;
 	}
 
 	setup_git_directory();
-
 	git_configset_init(&cs);
 
-	if (argc < 2)
-		goto print_usage_error;
+	if (subrepo_path) {
+		const struct submodule *sub;
+		struct repository *subrepo = xcalloc(1, sizeof(*repo));
+
+		sub = submodule_from_path(the_repository, &null_oid, subrepo_path);
+		if (!sub || repo_submodule_init(subrepo, the_repository, sub)) {
+			fprintf(stderr, "Invalid argument to --submodule: '%s'\n",
+				subrepo_path);
+			free(subrepo);
+			ret = TC_USAGE_ERROR;
+			goto out;
+		}
+		repo = subrepo;
+	}
 
-	if (argc == 3 && !strcmp(argv[1], "get_value")) {
-		if (!git_config_get_value(argv[2], &v)) {
+	if (argc == 2 && !strcmp(argv[0], "get_value")) {
+		if (!repo_config_get_value(repo, argv[1], &v)) {
 			if (!v)
 				printf("(NULL)\n");
 			else
 				printf("%s\n", v);
 		} else {
-			printf("Value not found for \"%s\"\n", argv[2]);
+			printf("Value not found for \"%s\"\n", argv[1]);
 			ret = TC_VALUE_NOT_FOUND;
 		}
-	} else if (argc == 3 && !strcmp(argv[1], "get_value_multi")) {
-		strptr = git_config_get_value_multi(argv[2]);
+	} else if (argc == 2 && !strcmp(argv[0], "get_value_multi")) {
+		strptr = repo_config_get_value_multi(repo, argv[1]);
 		if (strptr) {
 			for (i = 0; i < strptr->nr; i++) {
 				v = strptr->items[i].string;
@@ -120,32 +157,38 @@ int cmd__config(int argc, const char **argv)
 					printf("%s\n", v);
 			}
 		} else {
-			printf("Value not found for \"%s\"\n", argv[2]);
+			printf("Value not found for \"%s\"\n", argv[1]);
 			ret = TC_VALUE_NOT_FOUND;
 		}
-	} else if (argc == 3 && !strcmp(argv[1], "get_int")) {
-		if (!git_config_get_int(argv[2], &val)) {
+	} else if (argc == 2 && !strcmp(argv[0], "get_int")) {
+		if (!repo_config_get_int(repo, argv[1], &val)) {
 			printf("%d\n", val);
 		} else {
-			printf("Value not found for \"%s\"\n", argv[2]);
+			printf("Value not found for \"%s\"\n", argv[1]);
 			ret = TC_VALUE_NOT_FOUND;
 		}
-	} else if (argc == 3 && !strcmp(argv[1], "get_bool")) {
-		if (!git_config_get_bool(argv[2], &val)) {
+	} else if (argc == 2 && !strcmp(argv[0], "get_bool")) {
+		if (!repo_config_get_bool(repo, argv[1], &val)) {
 			printf("%d\n", val);
 		} else {
-			printf("Value not found for \"%s\"\n", argv[2]);
+
+			printf("Value not found for \"%s\"\n", argv[1]);
 			ret = TC_VALUE_NOT_FOUND;
 		}
-	} else if (argc == 3 && !strcmp(argv[1], "get_string")) {
-		if (!git_config_get_string_const(argv[2], &v)) {
+	} else if (argc == 2 && !strcmp(argv[0], "get_string")) {
+		if (!repo_config_get_string_const(repo, argv[1], &v)) {
 			printf("%s\n", v);
 		} else {
-			printf("Value not found for \"%s\"\n", argv[2]);
+			printf("Value not found for \"%s\"\n", argv[1]);
 			ret = TC_VALUE_NOT_FOUND;
 		}
-	} else if (argc >= 3 && !strcmp(argv[1], "configset_get_value")) {
-		for (i = 3; i < argc; i++) {
+	} else if (argc >= 2 && !strcmp(argv[0], "configset_get_value")) {
+		if (subrepo_path) {
+			fprintf(stderr, "Cannot use --submodule with configset_get_value\n");
+			ret = TC_USAGE_ERROR;
+			goto out;
+		}
+		for (i = 2; i < argc; i++) {
 			int err;
 			if ((err = git_configset_add_file(&cs, argv[i]))) {
 				fprintf(stderr, "Error (%d) reading configuration file %s.\n", err, argv[i]);
@@ -153,17 +196,22 @@ int cmd__config(int argc, const char **argv)
 				goto out;
 			}
 		}
-		if (!git_configset_get_value(&cs, argv[2], &v)) {
+		if (!git_configset_get_value(&cs, argv[1], &v)) {
 			if (!v)
 				printf("(NULL)\n");
 			else
 				printf("%s\n", v);
 		} else {
-			printf("Value not found for \"%s\"\n", argv[2]);
+			printf("Value not found for \"%s\"\n", argv[1]);
 			ret = TC_VALUE_NOT_FOUND;
 		}
-	} else if (argc >= 3 && !strcmp(argv[1], "configset_get_value_multi")) {
-		for (i = 3; i < argc; i++) {
+	} else if (argc >= 2 && !strcmp(argv[0], "configset_get_value_multi")) {
+		if (subrepo_path) {
+			fprintf(stderr, "Cannot use --submodule with configset_get_value_multi\n");
+			ret = TC_USAGE_ERROR;
+			goto out;
+		}
+		for (i = 2; i < argc; i++) {
 			int err;
 			if ((err = git_configset_add_file(&cs, argv[i]))) {
 				fprintf(stderr, "Error (%d) reading configuration file %s.\n", err, argv[i]);
@@ -171,7 +219,7 @@ int cmd__config(int argc, const char **argv)
 				goto out;
 			}
 		}
-		strptr = git_configset_get_value_multi(&cs, argv[2]);
+		strptr = git_configset_get_value_multi(&cs, argv[1]);
 		if (strptr) {
 			for (i = 0; i < strptr->nr; i++) {
 				v = strptr->items[i].string;
@@ -181,18 +229,23 @@ int cmd__config(int argc, const char **argv)
 					printf("%s\n", v);
 			}
 		} else {
-			printf("Value not found for \"%s\"\n", argv[2]);
+			printf("Value not found for \"%s\"\n", argv[1]);
 			ret = TC_VALUE_NOT_FOUND;
 		}
-	} else if (!strcmp(argv[1], "iterate")) {
-		git_config(iterate_cb, NULL);
+	} else if (!strcmp(argv[0], "iterate")) {
+		repo_config(repo, iterate_cb, NULL);
 	} else {
 print_usage_error:
-		fprintf(stderr, "Invalid syntax. Usage: test-tool config <cmd> [args]\n");
+		fprintf(stderr, "Invalid syntax. Usage: test-tool config"
+				" [--submodule=<path>] <cmd> [args]\n");
 		ret = TC_USAGE_ERROR;
 	}
 
 out:
 	git_configset_clear(&cs);
+	if (repo != the_repository) {
+		repo_clear(repo);
+		free(repo);
+	}
 	return ret;
 }
diff --git a/t/t2404-worktree-config.sh b/t/t2404-worktree-config.sh
index 286121d8de..b6ab793203 100755
--- a/t/t2404-worktree-config.sh
+++ b/t/t2404-worktree-config.sh
@@ -76,4 +76,20 @@ test_expect_success 'config.worktree no longer read without extension' '
 	test_cmp_config -C wt2 shared this.is
 '
 
+test_expect_success 'correctly read config.worktree from submodules' '
+	test_unconfig extensions.worktreeConfig &&
+	git init sub &&
+	(
+		cd sub &&
+		test_commit A &&
+		git config extensions.worktreeConfig true &&
+		git config --worktree wtconfig.sub test-value
+	) &&
+	git submodule add ./sub &&
+	git commit -m "add sub" &&
+	echo test-value >expect &&
+	test-tool config --submodule=sub get_value wtconfig.sub >actual &&
+	test_cmp expect actual
+'
+
 test_done
-- 
2.26.2


```

## Matheus Tavares, 2020-05-28 01:13

Subject: [PATCH v3 2/5] t/helper/test-config: return exit codes consistently
Message-ID: <43402007adb0916846f92c3e4ff86d4131056ce0.1590627264.git.matheus.bernardino@usp.br>
URL: https://gitlist.dev/e/43402007adb0916846f92c3e4ff86d4131056ce0.1590627264.git.matheus.bernardino%40usp.br
In-Reply-To: <cover.1590627264.git.matheus.bernardino@usp.br>

```
The test-config helper may exit with a variety of at least four
different codes, to reflect the status of the requested operations.
These codes are sometimes checked in the tests, but not all of the codes
are returned consistently by the helper: 1 will usually refer to a
"value not found", but usage errors can also return 1 or 128. The latter
is also expected on errors within the configset functions. These
inconsistent uses of the exit codes can lead to false positives in the
tests. Although all tests that currently check the helper's exit code,
on errors, do also check the output, it's still better to standardize
the exit codes and avoid future problems in new tests. While we are
here, let's also check that we have the expected argc for
configset_get_value and configset_get_value_multi, before trying to use
argv.

Note: this change is implemented with the unification of the exit
labels. This might seem unnecessary, for now, but it will benefit the
next patch, which will increase the cleanup section.

Signed-off-by: Matheus Tavares <matheus.bernardino@usp.br>
---
 t/helper/test-config.c | 76 ++++++++++++++++++++++--------------------
 1 file changed, 40 insertions(+), 36 deletions(-)

diff --git a/t/helper/test-config.c b/t/helper/test-config.c
index 234c722b48..1c8e965840 100644
--- a/t/helper/test-config.c
+++ b/t/helper/test-config.c
@@ -30,6 +30,14 @@
  * iterate -> iterate over all values using git_config(), and print some
  *            data for each
  *
+ * Exit codes:
+ *     0:   success
+ *     1:   value not found for the given config key
+ *     2:   config file path given as argument is inaccessible or doesn't exist
+ *     129: test-config usage error
+ *
+ * Note: tests may also expect 128 for die() calls in the config machinery.
+ *
  * Examples:
  *
  * To print the value with highest priority for key "foo.bAr Baz.rock":
@@ -64,35 +72,42 @@ static int early_config_cb(const char *var, const char *value, void *vdata)
 	return 0;
 }
 
+enum test_config_exit_code {
+	TC_SUCCESS = 0,
+	TC_VALUE_NOT_FOUND = 1,
+	TC_CONFIG_FILE_ERROR = 2,
+	TC_USAGE_ERROR = 129,
+};
+
 int cmd__config(int argc, const char **argv)
 {
 	int i, val;
 	const char *v;
 	const struct string_list *strptr;
 	struct config_set cs;
+	enum test_config_exit_code ret = TC_SUCCESS;
 
 	if (argc == 3 && !strcmp(argv[1], "read_early_config")) {
 		read_early_config(early_config_cb, (void *)argv[2]);
-		return 0;
+		return TC_SUCCESS;
 	}
 
 	setup_git_directory();
 
 	git_configset_init(&cs);
 
-	if (argc < 2) {
-		fprintf(stderr, "Please, provide a command name on the command-line\n");
-		goto exit1;
-	} else if (argc == 3 && !strcmp(argv[1], "get_value")) {
+	if (argc < 2)
+		goto print_usage_error;
+
+	if (argc == 3 && !strcmp(argv[1], "get_value")) {
 		if (!git_config_get_value(argv[2], &v)) {
 			if (!v)
 				printf("(NULL)\n");
 			else
 				printf("%s\n", v);
-			goto exit0;
 		} else {
 			printf("Value not found for \"%s\"\n", argv[2]);
-			goto exit1;
+			ret = TC_VALUE_NOT_FOUND;
 		}
 	} else if (argc == 3 && !strcmp(argv[1], "get_value_multi")) {
 		strptr = git_config_get_value_multi(argv[2]);
@@ -104,41 +119,38 @@ int cmd__config(int argc, const char **argv)
 				else
 					printf("%s\n", v);
 			}
-			goto exit0;
 		} else {
 			printf("Value not found for \"%s\"\n", argv[2]);
-			goto exit1;
+			ret = TC_VALUE_NOT_FOUND;
 		}
 	} else if (argc == 3 && !strcmp(argv[1], "get_int")) {
 		if (!git_config_get_int(argv[2], &val)) {
 			printf("%d\n", val);
-			goto exit0;
 		} else {
 			printf("Value not found for \"%s\"\n", argv[2]);
-			goto exit1;
+			ret = TC_VALUE_NOT_FOUND;
 		}
 	} else if (argc == 3 && !strcmp(argv[1], "get_bool")) {
 		if (!git_config_get_bool(argv[2], &val)) {
 			printf("%d\n", val);
-			goto exit0;
 		} else {
 			printf("Value not found for \"%s\"\n", argv[2]);
-			goto exit1;
+			ret = TC_VALUE_NOT_FOUND;
 		}
 	} else if (argc == 3 && !strcmp(argv[1], "get_string")) {
 		if (!git_config_get_string_const(argv[2], &v)) {
 			printf("%s\n", v);
-			goto exit0;
 		} else {
 			printf("Value not found for \"%s\"\n", argv[2]);
-			goto exit1;
+			ret = TC_VALUE_NOT_FOUND;
 		}
-	} else if (!strcmp(argv[1], "configset_get_value")) {
+	} else if (argc >= 3 && !strcmp(argv[1], "configset_get_value")) {
 		for (i = 3; i < argc; i++) {
 			int err;
 			if ((err = git_configset_add_file(&cs, argv[i]))) {
 				fprintf(stderr, "Error (%d) reading configuration file %s.\n", err, argv[i]);
-				goto exit2;
+				ret = TC_CONFIG_FILE_ERROR;
+				goto out;
 			}
 		}
 		if (!git_configset_get_value(&cs, argv[2], &v)) {
@@ -146,17 +158,17 @@ int cmd__config(int argc, const char **argv)
 				printf("(NULL)\n");
 			else
 				printf("%s\n", v);
-			goto exit0;
 		} else {
 			printf("Value not found for \"%s\"\n", argv[2]);
-			goto exit1;
+			ret = TC_VALUE_NOT_FOUND;
 		}
-	} else if (!strcmp(argv[1], "configset_get_value_multi")) {
+	} else if (argc >= 3 && !strcmp(argv[1], "configset_get_value_multi")) {
 		for (i = 3; i < argc; i++) {
 			int err;
 			if ((err = git_configset_add_file(&cs, argv[i]))) {
 				fprintf(stderr, "Error (%d) reading configuration file %s.\n", err, argv[i]);
-				goto exit2;
+				ret = TC_CONFIG_FILE_ERROR;
+				goto out;
 			}
 		}
 		strptr = git_configset_get_value_multi(&cs, argv[2]);
@@ -168,27 +180,19 @@ int cmd__config(int argc, const char **argv)
 				else
 					printf("%s\n", v);
 			}
-			goto exit0;
 		} else {
 			printf("Value not found for \"%s\"\n", argv[2]);
-			goto exit1;
+			ret = TC_VALUE_NOT_FOUND;
 		}
 	} else if (!strcmp(argv[1], "iterate")) {
 		git_config(iterate_cb, NULL);
-		goto exit0;
+	} else {
+print_usage_error:
+		fprintf(stderr, "Invalid syntax. Usage: test-tool config <cmd> [args]\n");
+		ret = TC_USAGE_ERROR;
 	}
 
-	die("%s: Please check the syntax and the function name", argv[0]);
-
-exit0:
-	git_configset_clear(&cs);
-	return 0;
-
-exit1:
-	git_configset_clear(&cs);
-	return 1;
-
-exit2:
+out:
 	git_configset_clear(&cs);
-	return 2;
+	return ret;
 }
-- 
2.26.2


```

## Matheus Tavares, 2020-05-28 01:13

Subject: [PATCH v3 4/5] grep: honor sparse checkout patterns
Message-ID: <5ddac818185d316cd5ad9576105f0e4e695b9456.1590627264.git.matheus.bernardino@usp.br>
URL: https://gitlist.dev/e/5ddac818185d316cd5ad9576105f0e4e695b9456.1590627264.git.matheus.bernardino%40usp.br
In-Reply-To: <cover.1590627264.git.matheus.bernardino@usp.br>

```
One of the main uses for a sparse checkout is to allow users to focus on
the subset of files in a repository in which they are interested. But
git-grep currently ignores the sparsity patterns and report all matches
found outside this subset, which kind of goes in the opposite direction.
Let's fix that, making it honor the sparsity boundaries for every
grepping case where this is relevant:

- git grep in worktree
- git grep --cached
- git grep $REVISION

For the worktree case, we will not grep paths that have the
SKIP_WORKTREE bit set, even if they are present for some reason (e.g.
manually created after `git sparse-checkout init`). But the next patch
will add an option to do so. (See 'Note' below.)

For `git grep $REVISION`, we will choose to honor the sparsity patterns
only when $REVISION is a commit-ish object. The reason is that, for a
tree, we don't know whether it represents the root of a repository or a
subtree. So we wouldn't be able to correctly match it against the
sparsity patterns. E.g. suppose we have a repository with these two
sparsity rules: "/*" and "!/a"; and the following structure:

/
| - a (file)
| - d (dir)
    | - a (file)

If `git grep $REVISION` were to honor the sparsity patterns for every
object type, when grepping the /d tree, we would wrongly ignore the /d/a
file. This happens because we wouldn't know it resides in /d and
therefore it would wrongly match the pattern "!/a". Furthermore, for a
search in a blob object, we wouldn't even have a path to check the
patterns against. So, let's ignore the sparsity patterns when grepping
non-commit-ish objects.

Note: The behavior introduced in this patch is what some users have
reported[1] that they would like by default. But the old behavior is
still desirable for some use cases. Therefore, the next patch will add
an option to allow restoring it when needed.

[1]: https://lore.kernel.org/git/CABPp-BGuFhDwWZBRaD3nA8ui46wor-4=Ha1G1oApsfF8KNpfGQ@mail.gmail.com/

Signed-off-by: Matheus Tavares <matheus.bernardino@usp.br>
---
 builtin/grep.c                   | 125 ++++++++++++++++++++--
 t/t7011-skip-worktree-reading.sh |   9 --
 t/t7817-grep-sparse-checkout.sh  | 174 +++++++++++++++++++++++++++++++
 3 files changed, 291 insertions(+), 17 deletions(-)
 create mode 100755 t/t7817-grep-sparse-checkout.sh

diff --git a/builtin/grep.c b/builtin/grep.c
index a5056f395a..11e33b8aee 100644
--- a/builtin/grep.c
+++ b/builtin/grep.c
@@ -410,7 +410,7 @@ static int grep_cache(struct grep_opt *opt,
 		      const struct pathspec *pathspec, int cached);
 static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
 		     struct tree_desc *tree, struct strbuf *base, int tn_len,
-		     int check_attr);
+		     int is_root_tree);
 
 static int grep_submodule(struct grep_opt *opt,
 			  const struct pathspec *pathspec,
@@ -508,6 +508,10 @@ static int grep_cache(struct grep_opt *opt,
 
 	for (nr = 0; nr < repo->index->cache_nr; nr++) {
 		const struct cache_entry *ce = repo->index->cache[nr];
+
+		if (ce_skip_worktree(ce))
+			continue;
+
 		strbuf_setlen(&name, name_base_len);
 		strbuf_addstr(&name, ce->name);
 
@@ -520,8 +524,7 @@ static int grep_cache(struct grep_opt *opt,
 			 * cache entry are identical, even if worktree file has
 			 * been modified, so use cache version instead
 			 */
-			if (cached || (ce->ce_flags & CE_VALID) ||
-			    ce_skip_worktree(ce)) {
+			if (cached || (ce->ce_flags & CE_VALID)) {
 				if (ce_stage(ce) || ce_intent_to_add(ce))
 					continue;
 				hit |= grep_oid(opt, &ce->oid, name.buf,
@@ -552,9 +555,76 @@ static int grep_cache(struct grep_opt *opt,
 	return hit;
 }
 
-static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
-		     struct tree_desc *tree, struct strbuf *base, int tn_len,
-		     int check_attr)
+static struct pattern_list *get_sparsity_patterns(struct repository *repo)
+{
+	struct pattern_list *patterns;
+	char *sparse_file;
+	int sparse_config, cone_config;
+
+	if (repo_config_get_bool(repo, "core.sparsecheckout", &sparse_config) ||
+	    !sparse_config) {
+		return NULL;
+	}
+
+	sparse_file = repo_git_path(repo, "info/sparse-checkout");
+	patterns = xcalloc(1, sizeof(*patterns));
+
+	if (repo_config_get_bool(repo, "core.sparsecheckoutcone", &cone_config))
+		cone_config = 0;
+	patterns->use_cone_patterns = cone_config;
+
+	if (add_patterns_from_file_to_list(sparse_file, "", 0, patterns, NULL)) {
+		if (file_exists(sparse_file)) {
+			warning(_("failed to load sparse-checkout file: '%s'"),
+				sparse_file);
+		}
+		free(sparse_file);
+		free(patterns);
+		return NULL;
+	}
+
+	free(sparse_file);
+	return patterns;
+}
+
+static int in_sparse_checkout(struct strbuf *path, int prefix_len,
+			      unsigned int entry_mode,
+			      struct index_state *istate,
+			      struct pattern_list *sparsity,
+			      enum pattern_match_result parent_match,
+			      enum pattern_match_result *match)
+{
+	int dtype = DT_UNKNOWN;
+	int is_dir = S_ISDIR(entry_mode);
+
+	if (parent_match == MATCHED_RECURSIVE) {
+		*match = parent_match;
+		return 1;
+	}
+
+	if (is_dir && !is_dir_sep(path->buf[path->len - 1]))
+		strbuf_addch(path, '/');
+
+	*match = path_matches_pattern_list(path->buf, path->len,
+					   path->buf + prefix_len, &dtype,
+					   sparsity, istate);
+	if (*match == UNDECIDED)
+		*match = parent_match;
+
+	if (is_dir)
+		strbuf_trim_trailing_dir_sep(path);
+
+	if (*match == NOT_MATCHED &&
+		(!is_dir || (is_dir && sparsity->use_cone_patterns)))
+	     return 0;
+
+	return 1;
+}
+
+static int do_grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
+			struct tree_desc *tree, struct strbuf *base, int tn_len,
+			int check_attr, struct pattern_list *sparsity,
+			enum pattern_match_result default_sparsity_match)
 {
 	struct repository *repo = opt->repo;
 	int hit = 0;
@@ -570,6 +640,7 @@ static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
 
 	while (tree_entry(tree, &entry)) {
 		int te_len = tree_entry_len(&entry);
+		enum pattern_match_result sparsity_match = 0;
 
 		if (match != all_entries_interesting) {
 			strbuf_addstr(&name, base->buf + tn_len);
@@ -586,6 +657,19 @@ static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
 
 		strbuf_add(base, entry.path, te_len);
 
+		if (sparsity) {
+			struct strbuf path = STRBUF_INIT;
+			strbuf_addstr(&path, base->buf + tn_len);
+
+			if (!in_sparse_checkout(&path, old_baselen - tn_len,
+						entry.mode, repo->index,
+						sparsity, default_sparsity_match,
+						&sparsity_match)) {
+				strbuf_setlen(base, old_baselen);
+				continue;
+			}
+		}
+
 		if (S_ISREG(entry.mode)) {
 			hit |= grep_oid(opt, &entry.oid, base->buf, tn_len,
 					 check_attr ? base->buf + tn_len : NULL);
@@ -602,8 +686,8 @@ static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
 
 			strbuf_addch(base, '/');
 			init_tree_desc(&sub, data, size);
-			hit |= grep_tree(opt, pathspec, &sub, base, tn_len,
-					 check_attr);
+			hit |= do_grep_tree(opt, pathspec, &sub, base, tn_len,
+					    check_attr, sparsity, sparsity_match);
 			free(data);
 		} else if (recurse_submodules && S_ISGITLINK(entry.mode)) {
 			hit |= grep_submodule(opt, pathspec, &entry.oid,
@@ -621,6 +705,31 @@ static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
 	return hit;
 }
 
+/*
+ * Note: sparsity patterns and paths' attributes will only be considered if
+ * is_root_tree has true value. (Otherwise, we cannot properly perform pattern
+ * matching on paths.)
+ */
+static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
+		     struct tree_desc *tree, struct strbuf *base, int tn_len,
+		     int is_root_tree)
+{
+	struct pattern_list *patterns = NULL;
+	int ret;
+
+	if (is_root_tree)
+		patterns = get_sparsity_patterns(opt->repo);
+
+	ret = do_grep_tree(opt, pathspec, tree, base, tn_len, is_root_tree,
+			   patterns, 0);
+
+	if (patterns) {
+		clear_pattern_list(patterns);
+		free(patterns);
+	}
+	return ret;
+}
+
 static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
 		       struct object *obj, const char *name, const char *path)
 {
diff --git a/t/t7011-skip-worktree-reading.sh b/t/t7011-skip-worktree-reading.sh
index 37525cae3a..26852586ac 100755
--- a/t/t7011-skip-worktree-reading.sh
+++ b/t/t7011-skip-worktree-reading.sh
@@ -109,15 +109,6 @@ test_expect_success 'ls-files --modified' '
 	test -z "$(git ls-files -m)"
 '
 
-test_expect_success 'grep with skip-worktree file' '
-	git update-index --no-skip-worktree 1 &&
-	echo test > 1 &&
-	git update-index 1 &&
-	git update-index --skip-worktree 1 &&
-	rm 1 &&
-	test "$(git grep --no-ext-grep test)" = "1:test"
-'
-
 echo ":000000 100644 $ZERO_OID $EMPTY_BLOB A	1" > expected
 test_expect_success 'diff-index does not examine skip-worktree absent entries' '
 	setup_absent &&
diff --git a/t/t7817-grep-sparse-checkout.sh b/t/t7817-grep-sparse-checkout.sh
new file mode 100755
index 0000000000..ce080cf572
--- /dev/null
+++ b/t/t7817-grep-sparse-checkout.sh
@@ -0,0 +1,174 @@
+#!/bin/sh
+
+test_description='grep in sparse checkout
+
+This test creates a repo with the following structure:
+
+.
+|-- a
+|-- b
+|-- dir
+|   `-- c
+|-- sub
+|   |-- A
+|   |   `-- a
+|   `-- B
+|       `-- b
+`-- sub2
+    `-- a
+
+Where . has non-cone mode sparsity patterns, sub is a submodule with cone mode
+sparsity patterns and sub2 is a submodule that is excluded by the superproject
+sparsity patterns. The resulting sparse checkout should leave the following
+structure on the working tree:
+
+.
+|-- a
+|-- sub
+|   `-- B
+|       `-- b
+`-- sub2
+    `-- a
+
+But note that sub2 should have the SKIP_WORKTREE bit set.
+'
+
+. ./test-lib.sh
+
+test_expect_success 'setup' '
+	echo "text" >a &&
+	echo "text" >b &&
+	mkdir dir &&
+	echo "text" >dir/c &&
+
+	git init sub &&
+	(
+		cd sub &&
+		mkdir A B &&
+		echo "text" >A/a &&
+		echo "text" >B/b &&
+		git add A B &&
+		git commit -m sub &&
+		git sparse-checkout init --cone &&
+		git sparse-checkout set B
+	) &&
+
+	git init sub2 &&
+	(
+		cd sub2 &&
+		echo "text" >a &&
+		git add a &&
+		git commit -m sub2
+	) &&
+
+	git submodule add ./sub &&
+	git submodule add ./sub2 &&
+	git add a b dir &&
+	git commit -m super &&
+	git sparse-checkout init --no-cone &&
+	git sparse-checkout set "/*" "!b" "!/*/" "sub" &&
+
+	git tag -am tag-to-commit tag-to-commit HEAD &&
+	tree=$(git rev-parse HEAD^{tree}) &&
+	git tag -am tag-to-tree tag-to-tree $tree &&
+
+	test_path_is_missing b &&
+	test_path_is_missing dir &&
+	test_path_is_missing sub/A &&
+	test_path_is_file a &&
+	test_path_is_file sub/B/b &&
+	test_path_is_file sub2/a
+'
+
+# The test bellow checks a special case: the sparsity patterns exclude '/b'
+# and sparse checkout is enable, but the path exists on the working tree (e.g.
+# manually created after `git sparse-checkout init`). In this case, grep should
+# skip it.
+test_expect_success 'grep in working tree should honor sparse checkout' '
+	cat >expect <<-EOF &&
+	a:text
+	EOF
+	echo "new-text" >b &&
+	test_when_finished "rm b" &&
+	git grep "text" >actual &&
+	test_cmp expect actual
+'
+
+test_expect_success 'grep --cached should honor sparse checkout' '
+	cat >expect <<-EOF &&
+	a:text
+	EOF
+	git grep --cached "text" >actual &&
+	test_cmp expect actual
+'
+
+test_expect_success 'grep <commit-ish> should honor sparse checkout' '
+	commit=$(git rev-parse HEAD) &&
+	cat >expect_commit <<-EOF &&
+	$commit:a:text
+	EOF
+	cat >expect_tag-to-commit <<-EOF &&
+	tag-to-commit:a:text
+	EOF
+	git grep "text" $commit >actual_commit &&
+	test_cmp expect_commit actual_commit &&
+	git grep "text" tag-to-commit >actual_tag-to-commit &&
+	test_cmp expect_tag-to-commit actual_tag-to-commit
+'
+
+test_expect_success 'grep <tree-ish> should ignore sparsity patterns' '
+	commit=$(git rev-parse HEAD) &&
+	tree=$(git rev-parse HEAD^{tree}) &&
+	cat >expect_tree <<-EOF &&
+	$tree:a:text
+	$tree:b:text
+	$tree:dir/c:text
+	EOF
+	cat >expect_tag-to-tree <<-EOF &&
+	tag-to-tree:a:text
+	tag-to-tree:b:text
+	tag-to-tree:dir/c:text
+	EOF
+	git grep "text" $tree >actual_tree &&
+	test_cmp expect_tree actual_tree &&
+	git grep "text" tag-to-tree >actual_tag-to-tree &&
+	test_cmp expect_tag-to-tree actual_tag-to-tree
+'
+
+# Note that sub2/ is present in the worktree but it is excluded by the sparsity
+# patterns, so grep should not recurse into it.
+test_expect_success 'grep --recurse-submodules should honor sparse checkout in submodule' '
+	cat >expect <<-EOF &&
+	a:text
+	sub/B/b:text
+	EOF
+	git grep --recurse-submodules "text" >actual &&
+	test_cmp expect actual
+'
+
+test_expect_success 'grep --recurse-submodules --cached should honor sparse checkout in submodule' '
+	cat >expect <<-EOF &&
+	a:text
+	sub/B/b:text
+	EOF
+	git grep --recurse-submodules --cached "text" >actual &&
+	test_cmp expect actual
+'
+
+test_expect_success 'grep --recurse-submodules <commit-ish> should honor sparse checkout in submodule' '
+	commit=$(git rev-parse HEAD) &&
+	cat >expect_commit <<-EOF &&
+	$commit:a:text
+	$commit:sub/B/b:text
+	EOF
+	cat >expect_tag-to-commit <<-EOF &&
+	tag-to-commit:a:text
+	tag-to-commit:sub/B/b:text
+	EOF
+	git grep --recurse-submodules "text" $commit >actual_commit &&
+	test_cmp expect_commit actual_commit &&
+	git grep --recurse-submodules "text" tag-to-commit >actual_tag-to-commit &&
+	test_cmp expect_tag-to-commit actual_tag-to-commit
+'
+
+test_done
-- 
2.26.2


```

## Matheus Tavares, 2020-05-28 01:13

Subject: [PATCH v3 5/5] config: add setting to ignore sparsity patterns in some cmds
Message-ID: <748b1e955ccdcf7cd897a180f4b4fe82d7bfcf00.1590627264.git.matheus.bernardino@usp.br>
URL: https://gitlist.dev/e/748b1e955ccdcf7cd897a180f4b4fe82d7bfcf00.1590627264.git.matheus.bernardino%40usp.br
In-Reply-To: <cover.1590627264.git.matheus.bernardino@usp.br>

```
When sparse checkout is enabled, some users expect the output of certain
commands (such as grep, diff, and log) to be also restricted within the
sparsity patterns. This would allow them to effectively work only on the
subset of files in which they are interested; and allow some commands to
possibly perform better, by not considering uninteresting paths. For
this reason, we taught grep to honor the sparsity patterns, in the
previous patch. But, on the other hand, allowing grep and the other
commands mentioned to optionally ignore the patterns also make for some
interesting use cases. E.g. using grep to search for a function
documentation that resides outside the sparse checkout.

In any case, there is no current way for users to configure the behavior
they want for these commands. Aiming to provide this flexibility, let's
introduce the sparse.restrictCmds setting (and the analogous
--[no]-restrict-to-sparse-paths global option). The default value is
true. For now, grep is the only one affected by this setting, but the
goal is to have support for more commands, in the future.

Helped-by: Elijah Newren <newren@gmail.com>
Signed-off-by: Matheus Tavares <matheus.bernardino@usp.br>
---
 Documentation/config.txt               |   2 +
 Documentation/config/sparse.txt        |  24 +++++
 Documentation/git-grep.txt             |   3 +
 Documentation/git.txt                  |   4 +
 Makefile                               |   1 +
 builtin/grep.c                         |  13 ++-
 contrib/completion/git-completion.bash |   2 +
 git.c                                  |   6 ++
 sparse-checkout.c                      |  16 +++
 sparse-checkout.h                      |  11 +++
 t/t7817-grep-sparse-checkout.sh        | 132 ++++++++++++++++++++++++-
 t/t9902-completion.sh                  |   4 +-
 12 files changed, 212 insertions(+), 6 deletions(-)
 create mode 100644 Documentation/config/sparse.txt
 create mode 100644 sparse-checkout.c
 create mode 100644 sparse-checkout.h

diff --git a/Documentation/config.txt b/Documentation/config.txt
index ef0768b91a..fd74b80302 100644
--- a/Documentation/config.txt
+++ b/Documentation/config.txt
@@ -436,6 +436,8 @@ include::config/sequencer.txt[]
 
 include::config/showbranch.txt[]
 
+include::config/sparse.txt[]
+
 include::config/splitindex.txt[]
 
 include::config/ssh.txt[]
diff --git a/Documentation/config/sparse.txt b/Documentation/config/sparse.txt
new file mode 100644
index 0000000000..2a25b4b8ef
--- /dev/null
+++ b/Documentation/config/sparse.txt
@@ -0,0 +1,24 @@
+sparse.restrictCmds::
+	Only meaningful in conjunction with core.sparseCheckout. This option
+	extends sparse checkouts (which limit which paths are written to the
+	working tree), so that output and operations are also limited to the
+	sparsity paths where possible and implemented. The purpose of this
+	option is to (1) focus output for the user on the portion of the
+	repository that is of interest to them, and (2) enable potentially
+	dramatic performance improvements, especially in conjunction with
+	partial clones.
++
+When this option is true (default), some git commands may limit their behavior
+to the paths specified by the sparsity patterns, or to the intersection of
+those paths and any (like `*.c`) that the user might also specify on the
+command line. When false, the affected commands will work on full trees,
+ignoring the sparsity patterns. For now, only git-grep honors this setting. In
+this command, the restriction takes effect in three cases: with --cached; when
+a commit-ish is given; when searching a working tree where some paths excluded
+by the sparsity patterns are present (e.g. manually created paths or not
+removed submodules).
++
+Note: commands which export, integrity check, or create history will always
+operate on full trees (e.g. fast-export, format-patch, fsck, commit, etc.),
+unaffected by any sparsity patterns. Also, writting commands such as
+sparse-checkout and read-tree will not be affected by this configuration.
diff --git a/Documentation/git-grep.txt b/Documentation/git-grep.txt
index 9bdf807584..abbf100109 100644
--- a/Documentation/git-grep.txt
+++ b/Documentation/git-grep.txt
@@ -41,6 +41,9 @@ characters.  An empty string as search expression matches all lines.
 CONFIGURATION
 -------------
 
+git-grep honors the sparse.restrictCmds setting. See its definition in
+linkgit:git-config[1].
+
 :git-grep: 1
 include::config/grep.txt[]
 
diff --git a/Documentation/git.txt b/Documentation/git.txt
index 9d6769e95a..5e107c6246 100644
--- a/Documentation/git.txt
+++ b/Documentation/git.txt
@@ -180,6 +180,10 @@ If you just want to run git as if it was started in `<path>` then use
 	Do not perform optional operations that require locks. This is
 	equivalent to setting the `GIT_OPTIONAL_LOCKS` to `0`.
 
+--[no-]restrict-to-sparse-paths::
+	Overrides the sparse.restrictCmds configuration (see
+	linkgit:git-config[1]) for this execution.
+
 --list-cmds=group[,group...]::
 	List commands by group. This is an internal/experimental
 	option and may change or be removed in the future. Supported
diff --git a/Makefile b/Makefile
index 90aa329eb7..0c0013b32c 100644
--- a/Makefile
+++ b/Makefile
@@ -983,6 +983,7 @@ LIB_OBJS += sha1-name.o
 LIB_OBJS += shallow.o
 LIB_OBJS += sideband.o
 LIB_OBJS += sigchain.o
+LIB_OBJS += sparse-checkout.o
 LIB_OBJS += split-index.o
 LIB_OBJS += stable-qsort.o
 LIB_OBJS += strbuf.o
diff --git a/builtin/grep.c b/builtin/grep.c
index 11e33b8aee..cc696dab4a 100644
--- a/builtin/grep.c
+++ b/builtin/grep.c
@@ -25,6 +25,7 @@
 #include "submodule-config.h"
 #include "object-store.h"
 #include "packfile.h"
+#include "sparse-checkout.h"
 
 static char const * const grep_usage[] = {
 	N_("git grep [<options>] [-e] <pattern> [<rev>...] [[--] <path>...]"),
@@ -498,6 +499,7 @@ static int grep_cache(struct grep_opt *opt,
 	int nr;
 	struct strbuf name = STRBUF_INIT;
 	int name_base_len = 0;
+	int sparse_paths_only =	restrict_to_sparse_paths(repo);
 	if (repo->submodule_prefix) {
 		name_base_len = strlen(repo->submodule_prefix);
 		strbuf_addstr(&name, repo->submodule_prefix);
@@ -509,7 +511,7 @@ static int grep_cache(struct grep_opt *opt,
 	for (nr = 0; nr < repo->index->cache_nr; nr++) {
 		const struct cache_entry *ce = repo->index->cache[nr];
 
-		if (ce_skip_worktree(ce))
+		if (sparse_paths_only && ce_skip_worktree(ce))
 			continue;
 
 		strbuf_setlen(&name, name_base_len);
@@ -715,9 +717,10 @@ static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
 		     int is_root_tree)
 {
 	struct pattern_list *patterns = NULL;
+	int sparse_paths_only = restrict_to_sparse_paths(opt->repo);
 	int ret;
 
-	if (is_root_tree)
+	if (is_root_tree && sparse_paths_only)
 		patterns = get_sparsity_patterns(opt->repo);
 
 	ret = do_grep_tree(opt, pathspec, tree, base, tn_len, is_root_tree,
@@ -1257,6 +1260,12 @@ int cmd_grep(int argc, const char **argv, const char *prefix)
 
 	if (!use_index || untracked) {
 		int use_exclude = (opt_exclude < 0) ? use_index : !!opt_exclude;
+
+		if (opt_restrict_to_sparse_paths >= 0) {
+			die(_("--[no-]restrict-to-sparse-paths is incompatible"
+				  " with --no-index and --untracked"));
+		}
+
 		hit = grep_directory(&opt, &pathspec, use_exclude, use_index);
 	} else if (0 <= opt_exclude) {
 		die(_("--[no-]exclude-standard cannot be used for tracked contents"));
diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
index 70ad04e1b2..71956f7313 100644
--- a/contrib/completion/git-completion.bash
+++ b/contrib/completion/git-completion.bash
@@ -3208,6 +3208,8 @@ __git_main ()
 			--namespace=
 			--no-replace-objects
 			--help
+			--restrict-to-sparse-paths
+			--no-restrict-to-sparse-paths
 			"
 			;;
 		*)
diff --git a/git.c b/git.c
index a2d337eed7..6db1382ae4 100644
--- a/git.c
+++ b/git.c
@@ -38,6 +38,7 @@ const char git_more_info_string[] =
 	   "See 'git help git' for an overview of the system.");
 
 static int use_pager = -1;
+int opt_restrict_to_sparse_paths = -1;
 
 static void list_builtins(struct string_list *list, unsigned int exclude_option);
 
@@ -311,6 +312,10 @@ static int handle_options(const char ***argv, int *argc, int *envchanged)
 			} else {
 				exit(list_cmds(cmd));
 			}
+		} else if (!strcmp(cmd, "--restrict-to-sparse-paths")) {
+			opt_restrict_to_sparse_paths = 1;
+		} else if (!strcmp(cmd, "--no-restrict-to-sparse-paths")) {
+			opt_restrict_to_sparse_paths = 0;
 		} else {
 			fprintf(stderr, _("unknown option: %s\n"), cmd);
 			usage(git_usage_string);
@@ -319,6 +324,7 @@ static int handle_options(const char ***argv, int *argc, int *envchanged)
 		(*argv)++;
 		(*argc)--;
 	}
+
 	return (*argv) - orig_argv;
 }
 
diff --git a/sparse-checkout.c b/sparse-checkout.c
new file mode 100644
index 0000000000..9a9e50fd29
--- /dev/null
+++ b/sparse-checkout.c
@@ -0,0 +1,16 @@
+#include "cache.h"
+#include "config.h"
+#include "sparse-checkout.h"
+
+int restrict_to_sparse_paths(struct repository *repo)
+{
+	int ret;
+
+	if (opt_restrict_to_sparse_paths >= 0)
+		return opt_restrict_to_sparse_paths;
+
+	if (repo_config_get_bool(repo, "sparse.restrictcmds", &ret))
+		ret = 1;
+
+	return ret;
+}
diff --git a/sparse-checkout.h b/sparse-checkout.h
new file mode 100644
index 0000000000..1de3b588d8
--- /dev/null
+++ b/sparse-checkout.h
@@ -0,0 +1,11 @@
+#ifndef SPARSE_CHECKOUT_H
+#define SPARSE_CHECKOUT_H
+
+struct repository;
+
+extern int opt_restrict_to_sparse_paths; /* from git.c */
+
+/* Whether or not cmds should restrict behavior on sparse paths, in this repo */
+int restrict_to_sparse_paths(struct repository *repo);
+
+#endif /* SPARSE_CHECKOUT_H */
diff --git a/t/t7817-grep-sparse-checkout.sh b/t/t7817-grep-sparse-checkout.sh
index ce080cf572..1aef084186 100755
--- a/t/t7817-grep-sparse-checkout.sh
+++ b/t/t7817-grep-sparse-checkout.sh
@@ -80,10 +80,10 @@ test_expect_success 'setup' '
 	test_path_is_file sub2/a
 '
 
-# The test bellow checks a special case: the sparsity patterns exclude '/b'
+# The two tests bellow check a special case: the sparsity patterns exclude '/b'
 # and sparse checkout is enable, but the path exists on the working tree (e.g.
 # manually created after `git sparse-checkout init`). In this case, grep should
-# skip it.
+# skip the file by default, but not with --no-restrict-to-sparse-paths.
 test_expect_success 'grep in working tree should honor sparse checkout' '
 	cat >expect <<-EOF &&
 	a:text
@@ -93,6 +93,16 @@ test_expect_success 'grep in working tree should honor sparse checkout' '
 	git grep "text" >actual &&
 	test_cmp expect actual
 '
+test_expect_success 'grep w/ --no-restrict-to-sparse-paths for sparsely excluded but present paths' '
+	cat >expect <<-EOF &&
+	a:text
+	b:new-text
+	EOF
+	echo "new-text" >b &&
+	test_when_finished "rm b" &&
+	git --no-restrict-to-sparse-paths grep "text" >actual &&
+	test_cmp expect actual
+'
 
 test_expect_success 'grep --cached should honor sparse checkout' '
 	cat >expect <<-EOF &&
@@ -136,7 +146,7 @@ test_expect_success 'grep <tree-ish> should ignore sparsity patterns' '
 '
 
 # Note that sub2/ is present in the worktree but it is excluded by the sparsity
-# patterns, so grep should not recurse into it.
+# patterns, so grep should only recurse into it with --no-restrict-to-sparse-paths.
 test_expect_success 'grep --recurse-submodules should honor sparse checkout in submodule' '
 	cat >expect <<-EOF &&
 	a:text
@@ -145,6 +155,15 @@ test_expect_success 'grep --recurse-submodules should honor sparse checkout in s
 	git grep --recurse-submodules "text" >actual &&
 	test_cmp expect actual
 '
+test_expect_success 'grep --recurse-submodules should search in excluded submodules w/ --no-restrict-to-sparse-paths' '
+	cat >expect <<-EOF &&
+	a:text
+	sub/B/b:text
+	sub2/a:text
+	EOF
+	git --no-restrict-to-sparse-paths grep --recurse-submodules "text" >actual &&
+	test_cmp expect actual
+'
 
 test_expect_success 'grep --recurse-submodules --cached should honor sparse checkout in submodule' '
 	cat >expect <<-EOF &&
@@ -171,4 +190,111 @@ test_expect_success 'grep --recurse-submodules <commit-ish> should honor sparse
 	test_cmp expect_tag-to-commit actual_tag-to-commit
 '
 
+for cmd in 'git --no-restrict-to-sparse-paths grep' \
+	   'git -c sparse.restrictCmds=false grep' \
+	   'git -c sparse.restrictCmds=true --no-restrict-to-sparse-paths grep'
+do
+
+	test_expect_success "$cmd --cached should ignore sparsity patterns" '
+		cat >expect <<-EOF &&
+		a:text
+		b:text
+		dir/c:text
+		EOF
+		$cmd --cached "text" >actual &&
+		test_cmp expect actual
+	'
+
+	test_expect_success "$cmd <commit-ish> should ignore sparsity patterns" '
+		commit=$(git rev-parse HEAD) &&
+		cat >expect_commit <<-EOF &&
+		$commit:a:text
+		$commit:b:text
+		$commit:dir/c:text
+		EOF
+		cat >expect_tag-to-commit <<-EOF &&
+		tag-to-commit:a:text
+		tag-to-commit:b:text
+		tag-to-commit:dir/c:text
+		EOF
+		$cmd "text" $commit >actual_commit &&
+		test_cmp expect_commit actual_commit &&
+		$cmd "text" tag-to-commit >actual_tag-to-commit &&
+		test_cmp expect_tag-to-commit actual_tag-to-commit
+	'
+done
+
+test_expect_success 'grep --recurse-submodules --cached \w --no-restrict-to-sparse-paths' '
+	cat >expect <<-EOF &&
+	a:text
+	b:text
+	dir/c:text
+	sub/A/a:text
+	sub/B/b:text
+	sub2/a:text
+	EOF
+	git --no-restrict-to-sparse-paths grep --recurse-submodules --cached \
+		"text" >actual &&
+	test_cmp expect actual
+'
+
+test_expect_success 'grep --recurse-submodules <commit-ish> \w --no-restrict-to-sparse-paths' '
+	commit=$(git rev-parse HEAD) &&
+	cat >expect_commit <<-EOF &&
+	$commit:a:text
+	$commit:b:text
+	$commit:dir/c:text
+	$commit:sub/A/a:text
+	$commit:sub/B/b:text
+	$commit:sub2/a:text
+	EOF
+	cat >expect_tag-to-commit <<-EOF &&
+	tag-to-commit:a:text
+	tag-to-commit:b:text
+	tag-to-commit:dir/c:text
+	tag-to-commit:sub/A/a:text
+	tag-to-commit:sub/B/b:text
+	tag-to-commit:sub2/a:text
+	EOF
+	git --no-restrict-to-sparse-paths grep --recurse-submodules "text" \
+		$commit >actual_commit &&
+	test_cmp expect_commit actual_commit &&
+	git --no-restrict-to-sparse-paths grep --recurse-submodules "text" \
+		tag-to-commit >actual_tag-to-commit &&
+	test_cmp expect_tag-to-commit actual_tag-to-commit
+'
+
+test_expect_success 'should respect the sparse.restrictCmds values from submodules' '
+	cat >expect <<-EOF &&
+	a:text
+	sub/A/a:text
+	sub/B/b:text
+	EOF
+	test_config -C sub sparse.restrictCmds false &&
+	git grep --cached --recurse-submodules "text" >actual &&
+	test_cmp expect actual
+'
+
+test_expect_success 'should propagate --[no]-restrict-to-sparse-paths to submodules' '
+	cat >expect <<-EOF &&
+	a:text
+	b:text
+	dir/c:text
+	sub/A/a:text
+	sub/B/b:text
+	sub2/a:text
+	EOF
+	test_config -C sub sparse.restrictCmds true &&
+	git --no-restrict-to-sparse-paths grep --cached --recurse-submodules "text" >actual &&
+	test_cmp expect actual
+'
+
+for opt in '--untracked' '--no-index'
+do
+	test_expect_success "--[no]-restrict-to-sparse-paths and $opt are incompatible" "
+		test_must_fail git --restrict-to-sparse-paths grep $opt . 2>actual &&
+		test_i18ngrep 'restrict-to-sparse-paths is incompatible with' actual
+	"
+done
+
 test_done
diff --git a/t/t9902-completion.sh b/t/t9902-completion.sh
index 3c44af6940..a4a7767e06 100755
--- a/t/t9902-completion.sh
+++ b/t/t9902-completion.sh
@@ -1473,6 +1473,8 @@ test_expect_success 'double dash "git" itself' '
 	--namespace=
 	--no-replace-objects Z
 	--help Z
+	--restrict-to-sparse-paths Z
+	--no-restrict-to-sparse-paths Z
 	EOF
 '
 
@@ -1515,7 +1517,7 @@ test_expect_success 'general options' '
 	test_completion "git --nam" "--namespace=" &&
 	test_completion "git --bar" "--bare " &&
 	test_completion "git --inf" "--info-path " &&
-	test_completion "git --no-r" "--no-replace-objects "
+	test_completion "git --no-rep" "--no-replace-objects "
 '
 
 test_expect_success 'general options plus command' '
-- 
2.26.2


```

## Elijah Newren, 2020-05-30 14:29

Subject: Re: [PATCH v3 2/5] t/helper/test-config: return exit codes consistently
Message-ID: <CABPp-BHTmYy=AtXoCLG-xXQ_0EZ7=3xiMibkNMDLzsKCnHBoFw@mail.gmail.com>
URL: https://gitlist.dev/e/CABPp-BHTmYy%3DAtXoCLG-xXQ_0EZ7%3D3xiMibkNMDLzsKCnHBoFw%40mail.gmail.com
In-Reply-To: <43402007adb0916846f92c3e4ff86d4131056ce0.1590627264.git.matheus.bernardino@usp.br>

```
On Wed, May 27, 2020 at 6:13 PM Matheus Tavares
<matheus.bernardino@usp.br> wrote:
>
> The test-config helper may exit with a variety of at least four
> different codes, to reflect the status of the requested operations.
> These codes are sometimes checked in the tests, but not all of the codes
> are returned consistently by the helper: 1 will usually refer to a
> "value not found", but usage errors can also return 1 or 128. The latter

I'm not sure what "The latter" refers to here.

> is also expected on errors within the configset functions. These
> inconsistent uses of the exit codes can lead to false positives in the
> tests. Although all tests that currently check the helper's exit code,
> on errors, do also check the output, it's still better to standardize
> the exit codes and avoid future problems in new tests. While we are

That last sentence was slightly hard for me to parse.  Maybe something like:

...Although all tests which expect errors and check the helper's exit
code currently also check the output, it's still better...


> here, let's also check that we have the expected argc for
> configset_get_value and configset_get_value_multi, before trying to use
> argv.
>
> Note: this change is implemented with the unification of the exit
> labels. This might seem unnecessary, for now, but it will benefit the
> next patch, which will increase the cleanup section.
>
> Signed-off-by: Matheus Tavares <matheus.bernardino@usp.br>
> ---
>  t/helper/test-config.c | 76 ++++++++++++++++++++++--------------------
>  1 file changed, 40 insertions(+), 36 deletions(-)
>
> diff --git a/t/helper/test-config.c b/t/helper/test-config.c
> index 234c722b48..1c8e965840 100644
> --- a/t/helper/test-config.c
> +++ b/t/helper/test-config.c
> @@ -30,6 +30,14 @@
>   * iterate -> iterate over all values using git_config(), and print some
>   *            data for each
>   *
> + * Exit codes:
> + *     0:   success
> + *     1:   value not found for the given config key
> + *     2:   config file path given as argument is inaccessible or doesn't exist
> + *     129: test-config usage error
> + *
> + * Note: tests may also expect 128 for die() calls in the config machinery.
> + *
>   * Examples:
>   *
>   * To print the value with highest priority for key "foo.bAr Baz.rock":
> @@ -64,35 +72,42 @@ static int early_config_cb(const char *var, const char *value, void *vdata)
>         return 0;
>  }
>
> +enum test_config_exit_code {
> +       TC_SUCCESS = 0,
> +       TC_VALUE_NOT_FOUND = 1,
> +       TC_CONFIG_FILE_ERROR = 2,
> +       TC_USAGE_ERROR = 129,
> +};
> +
>  int cmd__config(int argc, const char **argv)
>  {
>         int i, val;
>         const char *v;
>         const struct string_list *strptr;
>         struct config_set cs;
> +       enum test_config_exit_code ret = TC_SUCCESS;
>
>         if (argc == 3 && !strcmp(argv[1], "read_early_config")) {
>                 read_early_config(early_config_cb, (void *)argv[2]);
> -               return 0;
> +               return TC_SUCCESS;
>         }
>
>         setup_git_directory();
>
>         git_configset_init(&cs);
>
> -       if (argc < 2) {
> -               fprintf(stderr, "Please, provide a command name on the command-line\n");
> -               goto exit1;
> -       } else if (argc == 3 && !strcmp(argv[1], "get_value")) {
> +       if (argc < 2)
> +               goto print_usage_error;
> +
> +       if (argc == 3 && !strcmp(argv[1], "get_value")) {
>                 if (!git_config_get_value(argv[2], &v)) {
>                         if (!v)
>                                 printf("(NULL)\n");
>                         else
>                                 printf("%s\n", v);
> -                       goto exit0;
>                 } else {
>                         printf("Value not found for \"%s\"\n", argv[2]);
> -                       goto exit1;
> +                       ret = TC_VALUE_NOT_FOUND;
>                 }
>         } else if (argc == 3 && !strcmp(argv[1], "get_value_multi")) {
>                 strptr = git_config_get_value_multi(argv[2]);
> @@ -104,41 +119,38 @@ int cmd__config(int argc, const char **argv)
>                                 else
>                                         printf("%s\n", v);
>                         }
> -                       goto exit0;
>                 } else {
>                         printf("Value not found for \"%s\"\n", argv[2]);
> -                       goto exit1;
> +                       ret = TC_VALUE_NOT_FOUND;
>                 }
>         } else if (argc == 3 && !strcmp(argv[1], "get_int")) {
>                 if (!git_config_get_int(argv[2], &val)) {
>                         printf("%d\n", val);
> -                       goto exit0;
>                 } else {
>                         printf("Value not found for \"%s\"\n", argv[2]);
> -                       goto exit1;
> +                       ret = TC_VALUE_NOT_FOUND;
>                 }
>         } else if (argc == 3 && !strcmp(argv[1], "get_bool")) {
>                 if (!git_config_get_bool(argv[2], &val)) {
>                         printf("%d\n", val);
> -                       goto exit0;
>                 } else {
>                         printf("Value not found for \"%s\"\n", argv[2]);
> -                       goto exit1;
> +                       ret = TC_VALUE_NOT_FOUND;
>                 }
>         } else if (argc == 3 && !strcmp(argv[1], "get_string")) {
>                 if (!git_config_get_string_const(argv[2], &v)) {
>                         printf("%s\n", v);
> -                       goto exit0;
>                 } else {
>                         printf("Value not found for \"%s\"\n", argv[2]);
> -                       goto exit1;
> +                       ret = TC_VALUE_NOT_FOUND;
>                 }
> -       } else if (!strcmp(argv[1], "configset_get_value")) {
> +       } else if (argc >= 3 && !strcmp(argv[1], "configset_get_value")) {
>                 for (i = 3; i < argc; i++) {
>                         int err;
>                         if ((err = git_configset_add_file(&cs, argv[i]))) {
>                                 fprintf(stderr, "Error (%d) reading configuration file %s.\n", err, argv[i]);
> -                               goto exit2;
> +                               ret = TC_CONFIG_FILE_ERROR;
> +                               goto out;
>                         }
>                 }
>                 if (!git_configset_get_value(&cs, argv[2], &v)) {
> @@ -146,17 +158,17 @@ int cmd__config(int argc, const char **argv)
>                                 printf("(NULL)\n");
>                         else
>                                 printf("%s\n", v);
> -                       goto exit0;
>                 } else {
>                         printf("Value not found for \"%s\"\n", argv[2]);
> -                       goto exit1;
> +                       ret = TC_VALUE_NOT_FOUND;
>                 }
> -       } else if (!strcmp(argv[1], "configset_get_value_multi")) {
> +       } else if (argc >= 3 && !strcmp(argv[1], "configset_get_value_multi")) {
>                 for (i = 3; i < argc; i++) {
>                         int err;
>                         if ((err = git_configset_add_file(&cs, argv[i]))) {
>                                 fprintf(stderr, "Error (%d) reading configuration file %s.\n", err, argv[i]);
> -                               goto exit2;
> +                               ret = TC_CONFIG_FILE_ERROR;
> +                               goto out;
>                         }
>                 }
>                 strptr = git_configset_get_value_multi(&cs, argv[2]);
> @@ -168,27 +180,19 @@ int cmd__config(int argc, const char **argv)
>                                 else
>                                         printf("%s\n", v);
>                         }
> -                       goto exit0;
>                 } else {
>                         printf("Value not found for \"%s\"\n", argv[2]);
> -                       goto exit1;
> +                       ret = TC_VALUE_NOT_FOUND;
>                 }
>         } else if (!strcmp(argv[1], "iterate")) {
>                 git_config(iterate_cb, NULL);
> -               goto exit0;
> +       } else {
> +print_usage_error:
> +               fprintf(stderr, "Invalid syntax. Usage: test-tool config <cmd> [args]\n");
> +               ret = TC_USAGE_ERROR;
>         }
>
> -       die("%s: Please check the syntax and the function name", argv[0]);
> -
> -exit0:
> -       git_configset_clear(&cs);
> -       return 0;
> -
> -exit1:
> -       git_configset_clear(&cs);
> -       return 1;
> -
> -exit2:
> +out:
>         git_configset_clear(&cs);
> -       return 2;
> +       return ret;
>  }
> --
> 2.26.2

So, the primary purpose of the commit is getting making the return
status clearer, but most the code changes actually center around
reducing the gotos and unification of the exit labels.  Might have
been slightly easier to read if those two issues had been split, but
the patch is small enough that it's not a big deal.  Makes sense.

```

## Elijah Newren, 2020-05-30 14:49

Subject: Re: [PATCH v3 3/5] config: correctly read worktree configs in submodules
Message-ID: <CABPp-BGVaMM9Naiu3HeO6n2aOxsHwiuc813MF-hFWezSFa9CsA@mail.gmail.com>
URL: https://gitlist.dev/e/CABPp-BGVaMM9Naiu3HeO6n2aOxsHwiuc813MF-hFWezSFa9CsA%40mail.gmail.com
In-Reply-To: <448e0efffd0bbc89d8ea891923f242b5123c5826.1590627264.git.matheus.bernardino@usp.br>

```
On Wed, May 27, 2020 at 6:13 PM Matheus Tavares
<matheus.bernardino@usp.br> wrote:
>
> One of the steps in do_git_config_sequence() is to load the
> worktree-specific config file. Although the function receives a git_dir
> string, it relies on git_pathdup(), which uses the_repository->git_dir,
> to make the path to the file. Furthermore, it also checks that
> extensions.worktreeConfig is set through the
> repository_format_worktree_config variable, which refers to
> the_repository only. Thus, when a submodule has worktree settings, a
> command executed in the superproject that recurses into the submodule
> won't find the said settings.
>
> Such a scenario might not be needed now, but it will be in the following

It's not needed?  Are there not other config values that affect grep's
behavior, such as smudge filters of the submodule that might be
important if doing a 'git grep --recurse-submodules $REVISION'?

Also, is there a similar issue here for .gitattributes?  (e.g. if the
submodule declares certain files to be binary?)

(I don't actually know if these are issues but I'm just surprised to
hear that this would be the first case that would need to look at
submodule-specific configuration.  If the current code handles these
other scenarios I bring up, then you just need to correct your commit
message.  If these aren't issues, then I'd appreciate a quick
explanation of why I'm off base.  If these are current issues and the
current code isn't handling them, I'm not saying you need to address
them in this patch series, but you might need to reword the commit
message to mention that was already an issue that has previously been
overlooked and we're starting by fixing one case.)

> patch. git-grep will learn to honor sparse checkouts and, when running
> with --recurse-submodules, the submodule's sparse checkout settings must
> be loaded. As these settings are stored in the config.worktree file,
> they would be ignored without this patch. So let's fix this by reading
> the right config.worktree file and extensions.worktreeConfig setting,
> based on the git_dir and commondir paths given to
> do_git_config_sequence(). Also add a test to avoid any regressions.
>
> Signed-off-by: Matheus Tavares <matheus.bernardino@usp.br>
> ---
>  config.c                   |  21 +++++--
>  t/helper/test-config.c     | 119 +++++++++++++++++++++++++++----------
>  t/t2404-worktree-config.sh |  16 +++++
>  3 files changed, 118 insertions(+), 38 deletions(-)
>
> diff --git a/config.c b/config.c
> index 8db9c77098..c2d56309dc 100644
> --- a/config.c
> +++ b/config.c
> @@ -1747,11 +1747,22 @@ static int do_git_config_sequence(const struct config_options *opts,
>                 ret += git_config_from_file(fn, repo_config, data);
>
>         current_parsing_scope = CONFIG_SCOPE_WORKTREE;
> -       if (!opts->ignore_worktree && repository_format_worktree_config) {
> -               char *path = git_pathdup("config.worktree");
> -               if (!access_or_die(path, R_OK, 0))
> -                       ret += git_config_from_file(fn, path, data);
> -               free(path);
> +       if (!opts->ignore_worktree && repo_config && opts->git_dir) {
> +               struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
> +               struct strbuf buf = STRBUF_INIT;
> +
> +               read_repository_format(&repo_fmt, repo_config);
> +
> +               if (!verify_repository_format(&repo_fmt, &buf) &&
> +                   repo_fmt.worktree_config) {
> +                       char *path = mkpathdup("%s/config.worktree", opts->git_dir);
> +                       if (!access_or_die(path, R_OK, 0))
> +                               ret += git_config_from_file(fn, path, data);
> +                       free(path);
> +               }
> +
> +               strbuf_release(&buf);
> +               clear_repository_format(&repo_fmt);
>         }
>
>         current_parsing_scope = CONFIG_SCOPE_COMMAND;
> diff --git a/t/helper/test-config.c b/t/helper/test-config.c
> index 1c8e965840..284f83a921 100644
> --- a/t/helper/test-config.c
> +++ b/t/helper/test-config.c
> @@ -2,12 +2,19 @@
>  #include "cache.h"
>  #include "config.h"
>  #include "string-list.h"
> +#include "submodule-config.h"
>
>  /*
>   * This program exposes the C API of the configuration mechanism
>   * as a set of simple commands in order to facilitate testing.
>   *
> - * Reads stdin and prints result of command to stdout:
> + * Usage: test-tool config [--submodule=<path>] <cmd> [<args>]
> + *
> + * If --submodule=<path> is given, <cmd> will operate on the submodule at the
> + * given <path>. This option is not valid for the commands: read_early_config,
> + * configset_get_value and configset_get_value_multi.
> + *
> + * Possible cmds are:
>   *
>   * get_value -> prints the value with highest priority for the entered key
>   *
> @@ -84,33 +91,63 @@ int cmd__config(int argc, const char **argv)
>         int i, val;
>         const char *v;
>         const struct string_list *strptr;
> -       struct config_set cs;
> +       struct config_set cs = { .hash_initialized = 0 };
>         enum test_config_exit_code ret = TC_SUCCESS;
> +       struct repository *repo = the_repository;
> +       const char *subrepo_path = NULL;
> +
> +       argc--; /* skip over "config" */

This line alone is responsible for a fairly big set of changes
throughout this file, just decrementing indices everywhere.  It might
be nice for review purposes if this and the other changes it caused
were pulled out into a separate step, so we can more easily
concentrate on the primary additions and changes you are making to
this file.  In particular, being so unfamiliar with submodules I'd
really like to try to find someone who knows them a bit better to
review all the subrepo_path related portions of this change to this
file plus the config.c changes, but I think that'd be easier if the
change were more focused.

> +       argv++;
> +
> +       if (argc == 0)
> +               goto print_usage_error;
> +
> +       if (skip_prefix(*argv, "--submodule=", &subrepo_path)) {
> +               argc--;
> +               argv++;
> +               if (argc == 0)
> +                       goto print_usage_error;
> +       }
>
> -       if (argc == 3 && !strcmp(argv[1], "read_early_config")) {
> -               read_early_config(early_config_cb, (void *)argv[2]);
> +       if (argc == 2 && !strcmp(argv[0], "read_early_config")) {
> +               if (subrepo_path) {
> +                       fprintf(stderr, "Cannot use --submodule with read_early_config\n");
> +                       return TC_USAGE_ERROR;
> +               }
> +               read_early_config(early_config_cb, (void *)argv[1]);
>                 return TC_SUCCESS;
>         }
>
>         setup_git_directory();
> -
>         git_configset_init(&cs);
>
> -       if (argc < 2)
> -               goto print_usage_error;
> +       if (subrepo_path) {
> +               const struct submodule *sub;
> +               struct repository *subrepo = xcalloc(1, sizeof(*repo));
> +
> +               sub = submodule_from_path(the_repository, &null_oid, subrepo_path);
> +               if (!sub || repo_submodule_init(subrepo, the_repository, sub)) {
> +                       fprintf(stderr, "Invalid argument to --submodule: '%s'\n",
> +                               subrepo_path);
> +                       free(subrepo);
> +                       ret = TC_USAGE_ERROR;
> +                       goto out;
> +               }
> +               repo = subrepo;
> +       }
>
> -       if (argc == 3 && !strcmp(argv[1], "get_value")) {
> -               if (!git_config_get_value(argv[2], &v)) {
> +       if (argc == 2 && !strcmp(argv[0], "get_value")) {
> +               if (!repo_config_get_value(repo, argv[1], &v)) {
>                         if (!v)
>                                 printf("(NULL)\n");
>                         else
>                                 printf("%s\n", v);
>                 } else {
> -                       printf("Value not found for \"%s\"\n", argv[2]);
> +                       printf("Value not found for \"%s\"\n", argv[1]);
>                         ret = TC_VALUE_NOT_FOUND;
>                 }
> -       } else if (argc == 3 && !strcmp(argv[1], "get_value_multi")) {
> -               strptr = git_config_get_value_multi(argv[2]);
> +       } else if (argc == 2 && !strcmp(argv[0], "get_value_multi")) {
> +               strptr = repo_config_get_value_multi(repo, argv[1]);
>                 if (strptr) {
>                         for (i = 0; i < strptr->nr; i++) {
>                                 v = strptr->items[i].string;
> @@ -120,32 +157,38 @@ int cmd__config(int argc, const char **argv)
>                                         printf("%s\n", v);
>                         }
>                 } else {
> -                       printf("Value not found for \"%s\"\n", argv[2]);
> +                       printf("Value not found for \"%s\"\n", argv[1]);
>                         ret = TC_VALUE_NOT_FOUND;
>                 }
> -       } else if (argc == 3 && !strcmp(argv[1], "get_int")) {
> -               if (!git_config_get_int(argv[2], &val)) {
> +       } else if (argc == 2 && !strcmp(argv[0], "get_int")) {
> +               if (!repo_config_get_int(repo, argv[1], &val)) {
>                         printf("%d\n", val);
>                 } else {
> -                       printf("Value not found for \"%s\"\n", argv[2]);
> +                       printf("Value not found for \"%s\"\n", argv[1]);
>                         ret = TC_VALUE_NOT_FOUND;
>                 }
> -       } else if (argc == 3 && !strcmp(argv[1], "get_bool")) {
> -               if (!git_config_get_bool(argv[2], &val)) {
> +       } else if (argc == 2 && !strcmp(argv[0], "get_bool")) {
> +               if (!repo_config_get_bool(repo, argv[1], &val)) {
>                         printf("%d\n", val);
>                 } else {
> -                       printf("Value not found for \"%s\"\n", argv[2]);
> +
> +                       printf("Value not found for \"%s\"\n", argv[1]);
>                         ret = TC_VALUE_NOT_FOUND;
>                 }
> -       } else if (argc == 3 && !strcmp(argv[1], "get_string")) {
> -               if (!git_config_get_string_const(argv[2], &v)) {
> +       } else if (argc == 2 && !strcmp(argv[0], "get_string")) {
> +               if (!repo_config_get_string_const(repo, argv[1], &v)) {
>                         printf("%s\n", v);
>                 } else {
> -                       printf("Value not found for \"%s\"\n", argv[2]);
> +                       printf("Value not found for \"%s\"\n", argv[1]);
>                         ret = TC_VALUE_NOT_FOUND;
>                 }
> -       } else if (argc >= 3 && !strcmp(argv[1], "configset_get_value")) {
> -               for (i = 3; i < argc; i++) {
> +       } else if (argc >= 2 && !strcmp(argv[0], "configset_get_value")) {
> +               if (subrepo_path) {
> +                       fprintf(stderr, "Cannot use --submodule with configset_get_value\n");
> +                       ret = TC_USAGE_ERROR;
> +                       goto out;
> +               }
> +               for (i = 2; i < argc; i++) {
>                         int err;
>                         if ((err = git_configset_add_file(&cs, argv[i]))) {
>                                 fprintf(stderr, "Error (%d) reading configuration file %s.\n", err, argv[i]);
> @@ -153,17 +196,22 @@ int cmd__config(int argc, const char **argv)
>                                 goto out;
>                         }
>                 }
> -               if (!git_configset_get_value(&cs, argv[2], &v)) {
> +               if (!git_configset_get_value(&cs, argv[1], &v)) {
>                         if (!v)
>                                 printf("(NULL)\n");
>                         else
>                                 printf("%s\n", v);
>                 } else {
> -                       printf("Value not found for \"%s\"\n", argv[2]);
> +                       printf("Value not found for \"%s\"\n", argv[1]);
>                         ret = TC_VALUE_NOT_FOUND;
>                 }
> -       } else if (argc >= 3 && !strcmp(argv[1], "configset_get_value_multi")) {
> -               for (i = 3; i < argc; i++) {
> +       } else if (argc >= 2 && !strcmp(argv[0], "configset_get_value_multi")) {
> +               if (subrepo_path) {
> +                       fprintf(stderr, "Cannot use --submodule with configset_get_value_multi\n");
> +                       ret = TC_USAGE_ERROR;
> +                       goto out;
> +               }
> +               for (i = 2; i < argc; i++) {
>                         int err;
>                         if ((err = git_configset_add_file(&cs, argv[i]))) {
>                                 fprintf(stderr, "Error (%d) reading configuration file %s.\n", err, argv[i]);
> @@ -171,7 +219,7 @@ int cmd__config(int argc, const char **argv)
>                                 goto out;
>                         }
>                 }
> -               strptr = git_configset_get_value_multi(&cs, argv[2]);
> +               strptr = git_configset_get_value_multi(&cs, argv[1]);
>                 if (strptr) {
>                         for (i = 0; i < strptr->nr; i++) {
>                                 v = strptr->items[i].string;
> @@ -181,18 +229,23 @@ int cmd__config(int argc, const char **argv)
>                                         printf("%s\n", v);
>                         }
>                 } else {
> -                       printf("Value not found for \"%s\"\n", argv[2]);
> +                       printf("Value not found for \"%s\"\n", argv[1]);
>                         ret = TC_VALUE_NOT_FOUND;
>                 }
> -       } else if (!strcmp(argv[1], "iterate")) {
> -               git_config(iterate_cb, NULL);
> +       } else if (!strcmp(argv[0], "iterate")) {
> +               repo_config(repo, iterate_cb, NULL);
>         } else {
>  print_usage_error:
> -               fprintf(stderr, "Invalid syntax. Usage: test-tool config <cmd> [args]\n");
> +               fprintf(stderr, "Invalid syntax. Usage: test-tool config"
> +                               " [--submodule=<path>] <cmd> [args]\n");
>                 ret = TC_USAGE_ERROR;
>         }
>
>  out:
>         git_configset_clear(&cs);
> +       if (repo != the_repository) {
> +               repo_clear(repo);
> +               free(repo);
> +       }
>         return ret;
>  }
> diff --git a/t/t2404-worktree-config.sh b/t/t2404-worktree-config.sh
> index 286121d8de..b6ab793203 100755
> --- a/t/t2404-worktree-config.sh
> +++ b/t/t2404-worktree-config.sh
> @@ -76,4 +76,20 @@ test_expect_success 'config.worktree no longer read without extension' '
>         test_cmp_config -C wt2 shared this.is
>  '
>
> +test_expect_success 'correctly read config.worktree from submodules' '
> +       test_unconfig extensions.worktreeConfig &&
> +       git init sub &&
> +       (
> +               cd sub &&
> +               test_commit A &&
> +               git config extensions.worktreeConfig true &&
> +               git config --worktree wtconfig.sub test-value
> +       ) &&
> +       git submodule add ./sub &&
> +       git commit -m "add sub" &&
> +       echo test-value >expect &&
> +       test-tool config --submodule=sub get_value wtconfig.sub >actual &&
> +       test_cmp expect actual
> +'
> +
>  test_done
> --
> 2.26.2

The index updates seem fine, and I like the test, and I tried to look
at the submodule and config bits but I'm quite unfamiliar with that
area of the code and I'd like to see if we can find someone who knows
submodules and/or config a bit better to review those pieces.  A split
of this patch into two in your next roll of this series would be nice
so we can ask someone to look at just the relevant bits.

```

## Elijah Newren, 2020-05-30 15:48

Subject: Re: [PATCH v3 4/5] grep: honor sparse checkout patterns
Message-ID: <CABPp-BFsCPPNOZ92JQRJeGyNd0e-TCW-LcLyr0i_+VSQJP+GCg@mail.gmail.com>
URL: https://gitlist.dev/e/CABPp-BFsCPPNOZ92JQRJeGyNd0e-TCW-LcLyr0i_%2BVSQJP%2BGCg%40mail.gmail.com
In-Reply-To: <5ddac818185d316cd5ad9576105f0e4e695b9456.1590627264.git.matheus.bernardino@usp.br>

```
On Wed, May 27, 2020 at 6:13 PM Matheus Tavares
<matheus.bernardino@usp.br> wrote:
>
> One of the main uses for a sparse checkout is to allow users to focus on
> the subset of files in a repository in which they are interested. But
> git-grep currently ignores the sparsity patterns and report all matches
> found outside this subset, which kind of goes in the opposite direction.
> Let's fix that, making it honor the sparsity boundaries for every
> grepping case where this is relevant:
>
> - git grep in worktree
> - git grep --cached
> - git grep $REVISION
>
> For the worktree case, we will not grep paths that have the
> SKIP_WORKTREE bit set, even if they are present for some reason (e.g.
> manually created after `git sparse-checkout init`).

This seems worded to rise alarm bells and make users suspect
implementation difficulties or regrets rather than desired behavior.
It would be much better to word this simply as something like:

    For the worktree and cached cases, we iterate over paths without
the SKIP_WORKTREE bit set, and limit our searches to these paths.

> But the next patch
> will add an option to do so. (See 'Note' below.)

Because this was in the same paragraph as the previous sentence, it
made it sound like you were going to provide a special worktree-only
option to search outside the SKIP_WORKTREE bits.  Very confusing.  I
think I'd combine this sentence into the very first paragraph of the
commit message and massage the wording a little.  Perhaps something
like:  ...goes in the opposite direction.  There are some usecases for
ignoring the sparsity patterns and the next commit will add an option
to obtain this behavior, but here we start by making grep honor the
sparsity boundaries for every...

> For `git grep $REVISION`, we will choose to honor the sparsity patterns
> only when $REVISION is a commit-ish object. The reason is that, for a
> tree, we don't know whether it represents the root of a repository or a
> subtree. So we wouldn't be able to correctly match it against the
> sparsity patterns. E.g. suppose we have a repository with these two
> sparsity rules: "/*" and "!/a"; and the following structure:
>
> /
> | - a (file)
> | - d (dir)
>     | - a (file)
>
> If `git grep $REVISION` were to honor the sparsity patterns for every
> object type, when grepping the /d tree, we would wrongly ignore the /d/a
> file. This happens because we wouldn't know it resides in /d and
> therefore it would wrongly match the pattern "!/a". Furthermore, for a
> search in a blob object, we wouldn't even have a path to check the
> patterns against. So, let's ignore the sparsity patterns when grepping
> non-commit-ish objects.

This doesn't actually make it clear how you handle $REVISION which is
a commit object; you focus so much on when $REVISION is just a tree
and contrasting that case that you omit the behavior for the case of
interest.  Also, $REVISION to my mind implies "commit"; if you want to
imply that a commit or tree could be used, you'd use $TREE or
$TREE_ISH or something else.  I think it'd make sense to cover all
three relevant cases into a single paragraph (thus combining with the
previous paragraph), and then add a second paragraph about the $TREE
case that streamlines the last two pargraphs above.  So, perhaps we
can your paragraphs from "For the worktree case, we will not grep
paths..." all the way to "So, let's ignore the sparsity patterns when
grepping non-commit-ish objects" (after first moving the comment about
adding an option in the next commit to some other area of the commit
message, as dicussed above) with something like the following:


    For the worktree and cached cases, we iterate over paths without
the SKIP_WORKTREE bit set, and limit our searches to these paths.  For
the $REVISION case, we limit the paths we search to those that match
the sparsity patterns.  (We do not check the SKIP_WORKTREE bit for the
$REVISION case, because $REVISION may contain paths that do not exist
in HEAD and thus for which we have no SKIP_WORKTREE bit to consult.
The sparsity patterns tell us how the SKIP_WORKTREE bit would be set
if we were to check out $REVISION, so we consult those.  Also, we
don't use the sparsity paths with the worktree or cached cases, both
because we have a bit we can check directly and more efficiently, and
because unmerged entries from a merge or a rebase could cause more
files to temporarily be present than the sparsity patterns would
normally select.)

    Note that there is a special case here: `git grep $TREE`.  In this
case we cannot know whether $TREE corresponds to the root of the
repository or some sub-tree, and thus there is no way for us to know
which sparsity patterns, if any, apply.  So the $TREE case will not
use sparsity patterns or any SKIP_WORKTREE bits and will instead
always search all files within the $TREE.

>
> Note: The behavior introduced in this patch is what some users have
> reported[1] that they would like by default. But the old behavior is
> still desirable for some use cases. Therefore, the next patch will add
> an option to allow restoring it when needed.

This paragraph duplicates information you already stated previously.
It's much clearer than what you stated before, but if you just reword
the previous comments and combine them into the first paragraph, then
we can drop this final note.


> [1]: https://lore.kernel.org/git/CABPp-BGuFhDwWZBRaD3nA8ui46wor-4=Ha1G1oApsfF8KNpfGQ@mail.gmail.com/
>
> Signed-off-by: Matheus Tavares <matheus.bernardino@usp.br>
> ---
>  builtin/grep.c                   | 125 ++++++++++++++++++++--
>  t/t7011-skip-worktree-reading.sh |   9 --
>  t/t7817-grep-sparse-checkout.sh  | 174 +++++++++++++++++++++++++++++++
>  3 files changed, 291 insertions(+), 17 deletions(-)
>  create mode 100755 t/t7817-grep-sparse-checkout.sh
>
> diff --git a/builtin/grep.c b/builtin/grep.c
> index a5056f395a..11e33b8aee 100644
> --- a/builtin/grep.c
> +++ b/builtin/grep.c
> @@ -410,7 +410,7 @@ static int grep_cache(struct grep_opt *opt,
>                       const struct pathspec *pathspec, int cached);
>  static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
>                      struct tree_desc *tree, struct strbuf *base, int tn_len,
> -                    int check_attr);
> +                    int is_root_tree);

So you modified the forward declaration of grep_tree()...

>
>  static int grep_submodule(struct grep_opt *opt,
>                           const struct pathspec *pathspec,
> @@ -508,6 +508,10 @@ static int grep_cache(struct grep_opt *opt,
>
>         for (nr = 0; nr < repo->index->cache_nr; nr++) {
>                 const struct cache_entry *ce = repo->index->cache[nr];
> +
> +               if (ce_skip_worktree(ce))
> +                       continue;
> +
>                 strbuf_setlen(&name, name_base_len);
>                 strbuf_addstr(&name, ce->name);
>
> @@ -520,8 +524,7 @@ static int grep_cache(struct grep_opt *opt,
>                          * cache entry are identical, even if worktree file has
>                          * been modified, so use cache version instead
>                          */
> -                       if (cached || (ce->ce_flags & CE_VALID) ||
> -                           ce_skip_worktree(ce)) {
> +                       if (cached || (ce->ce_flags & CE_VALID)) {
>                                 if (ce_stage(ce) || ce_intent_to_add(ce))
>                                         continue;
>                                 hit |= grep_oid(opt, &ce->oid, name.buf,
> @@ -552,9 +555,76 @@ static int grep_cache(struct grep_opt *opt,
>         return hit;
>  }
>
> -static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
> -                    struct tree_desc *tree, struct strbuf *base, int tn_len,
> -                    int check_attr)

Here the patch splits your handling of grep_tree()...

> +static struct pattern_list *get_sparsity_patterns(struct repository *repo)
> +{
> +       struct pattern_list *patterns;
> +       char *sparse_file;
> +       int sparse_config, cone_config;
> +
> +       if (repo_config_get_bool(repo, "core.sparsecheckout", &sparse_config) ||
> +           !sparse_config) {
> +               return NULL;
> +       }

Is core_apply_sparse_checkout not initialized for some reason?

> +
> +       sparse_file = repo_git_path(repo, "info/sparse-checkout");
> +       patterns = xcalloc(1, sizeof(*patterns));
> +
> +       if (repo_config_get_bool(repo, "core.sparsecheckoutcone", &cone_config))
> +               cone_config = 0;
> +       patterns->use_cone_patterns = cone_config;

Similarly, is core_sparse_checkout_cone not intialized?

> +
> +       if (add_patterns_from_file_to_list(sparse_file, "", 0, patterns, NULL)) {
> +               if (file_exists(sparse_file)) {
> +                       warning(_("failed to load sparse-checkout file: '%s'"),
> +                               sparse_file);
> +               }
> +               free(sparse_file);
> +               free(patterns);
> +               return NULL;
> +       }
> +
> +       free(sparse_file);
> +       return patterns;
> +}
> +
> +static int in_sparse_checkout(struct strbuf *path, int prefix_len,

This function name in_sparse_checkout() makes me think "Does the
working tree represent a sparse checkout?"  Perhaps we could rename it
to path_matches_sparsity_patterns() ?

Also, is there a reason we can't use dir.c's
path_matches_pattern_list() here?  How does this new function differ
in behavior from that function?

> +                             unsigned int entry_mode,
> +                             struct index_state *istate,
> +                             struct pattern_list *sparsity,
> +                             enum pattern_match_result parent_match,
> +                             enum pattern_match_result *match)
> +{
> +       int dtype = DT_UNKNOWN;
> +       int is_dir = S_ISDIR(entry_mode);
> +
> +       if (parent_match == MATCHED_RECURSIVE) {
> +               *match = parent_match;
> +               return 1;
> +       }
> +
> +       if (is_dir && !is_dir_sep(path->buf[path->len - 1]))
> +               strbuf_addch(path, '/');
> +
> +       *match = path_matches_pattern_list(path->buf, path->len,
> +                                          path->buf + prefix_len, &dtype,
> +                                          sparsity, istate);
> +       if (*match == UNDECIDED)
> +               *match = parent_match;
> +
> +       if (is_dir)
> +               strbuf_trim_trailing_dir_sep(path);
> +
> +       if (*match == NOT_MATCHED &&
> +               (!is_dir || (is_dir && sparsity->use_cone_patterns)))
> +            return 0;
> +
> +       return 1;
> +}
> +
> +static int do_grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,

I thought this meant you were renaming grep_tree() to do_grep_tree()
but it's a new function that happens to have most of the logic from
the old grep_tree() and which the new grep_tree() will call to do most
its work.

> +                       struct tree_desc *tree, struct strbuf *base, int tn_len,
> +                       int check_attr, struct pattern_list *sparsity,
> +                       enum pattern_match_result default_sparsity_match)
>  {
>         struct repository *repo = opt->repo;
>         int hit = 0;
> @@ -570,6 +640,7 @@ static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
>
>         while (tree_entry(tree, &entry)) {
>                 int te_len = tree_entry_len(&entry);
> +               enum pattern_match_result sparsity_match = 0;
>
>                 if (match != all_entries_interesting) {
>                         strbuf_addstr(&name, base->buf + tn_len);
> @@ -586,6 +657,19 @@ static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
>
>                 strbuf_add(base, entry.path, te_len);
>
> +               if (sparsity) {
> +                       struct strbuf path = STRBUF_INIT;
> +                       strbuf_addstr(&path, base->buf + tn_len);
> +
> +                       if (!in_sparse_checkout(&path, old_baselen - tn_len,
> +                                               entry.mode, repo->index,
> +                                               sparsity, default_sparsity_match,
> +                                               &sparsity_match)) {
> +                               strbuf_setlen(base, old_baselen);
> +                               continue;
> +                       }
> +               }
> +
>                 if (S_ISREG(entry.mode)) {
>                         hit |= grep_oid(opt, &entry.oid, base->buf, tn_len,
>                                          check_attr ? base->buf + tn_len : NULL);
> @@ -602,8 +686,8 @@ static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
>
>                         strbuf_addch(base, '/');
>                         init_tree_desc(&sub, data, size);
> -                       hit |= grep_tree(opt, pathspec, &sub, base, tn_len,
> -                                        check_attr);
> +                       hit |= do_grep_tree(opt, pathspec, &sub, base, tn_len,
> +                                           check_attr, sparsity, sparsity_match);
>                         free(data);
>                 } else if (recurse_submodules && S_ISGITLINK(entry.mode)) {
>                         hit |= grep_submodule(opt, pathspec, &entry.oid,
> @@ -621,6 +705,31 @@ static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
>         return hit;
>  }
>
> +/*
> + * Note: sparsity patterns and paths' attributes will only be considered if
> + * is_root_tree has true value. (Otherwise, we cannot properly perform pattern
> + * matching on paths.)
> + */
> +static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
> +                    struct tree_desc *tree, struct strbuf *base, int tn_len,
> +                    int is_root_tree)
> +{
> +       struct pattern_list *patterns = NULL;
> +       int ret;
> +
> +       if (is_root_tree)
> +               patterns = get_sparsity_patterns(opt->repo);
> +
> +       ret = do_grep_tree(opt, pathspec, tree, base, tn_len, is_root_tree,
> +                          patterns, 0);
> +
> +       if (patterns) {
> +               clear_pattern_list(patterns);
> +               free(patterns);
> +       }
> +       return ret;
> +}

Once I figured out grep_tree() was just becoming a wrapper around
do_grep_tree(), the patch made more sense; I should have scrolled to
the end quicker.  ;-)

> +
>  static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
>                        struct object *obj, const char *name, const char *path)
>  {
> diff --git a/t/t7011-skip-worktree-reading.sh b/t/t7011-skip-worktree-reading.sh
> index 37525cae3a..26852586ac 100755
> --- a/t/t7011-skip-worktree-reading.sh
> +++ b/t/t7011-skip-worktree-reading.sh
> @@ -109,15 +109,6 @@ test_expect_success 'ls-files --modified' '
>         test -z "$(git ls-files -m)"
>  '
>
> -test_expect_success 'grep with skip-worktree file' '
> -       git update-index --no-skip-worktree 1 &&
> -       echo test > 1 &&
> -       git update-index 1 &&
> -       git update-index --skip-worktree 1 &&
> -       rm 1 &&
> -       test "$(git grep --no-ext-grep test)" = "1:test"
> -'

Yaay!

> -
>  echo ":000000 100644 $ZERO_OID $EMPTY_BLOB A   1" > expected
>  test_expect_success 'diff-index does not examine skip-worktree absent entries' '
>         setup_absent &&
> diff --git a/t/t7817-grep-sparse-checkout.sh b/t/t7817-grep-sparse-checkout.sh
> new file mode 100755
> index 0000000000..ce080cf572
> --- /dev/null
> +++ b/t/t7817-grep-sparse-checkout.sh
> @@ -0,0 +1,174 @@
> +#!/bin/sh
> +
> +test_description='grep in sparse checkout
> +
> +This test creates a repo with the following structure:
> +
> +.
> +|-- a
> +|-- b
> +|-- dir
> +|   `-- c
> +|-- sub
> +|   |-- A
> +|   |   `-- a
> +|   `-- B
> +|       `-- b
> +`-- sub2
> +    `-- a
> +
> +Where . has non-cone mode sparsity patterns, sub is a submodule with cone mode

Maybe "Where the outer repository has non-code mode..."?  The use of
'.' threw me for a bit.

> +sparsity patterns and sub2 is a submodule that is excluded by the superproject
> +sparsity patterns. The resulting sparse checkout should leave the following
> +structure on the working tree:

s/on the/in the/?

> +
> +.
> +|-- a
> +|-- sub
> +|   `-- B
> +|       `-- b
> +`-- sub2
> +    `-- a
> +
> +But note that sub2 should have the SKIP_WORKTREE bit set.
> +'
> +
> +. ./test-lib.sh
> +
> +test_expect_success 'setup' '
> +       echo "text" >a &&
> +       echo "text" >b &&
> +       mkdir dir &&
> +       echo "text" >dir/c &&
> +
> +       git init sub &&
> +       (
> +               cd sub &&
> +               mkdir A B &&
> +               echo "text" >A/a &&
> +               echo "text" >B/b &&
> +               git add A B &&
> +               git commit -m sub &&
> +               git sparse-checkout init --cone &&
> +               git sparse-checkout set B
> +       ) &&
> +
> +       git init sub2 &&
> +       (
> +               cd sub2 &&
> +               echo "text" >a &&
> +               git add a &&
> +               git commit -m sub2
> +       ) &&
> +
> +       git submodule add ./sub &&
> +       git submodule add ./sub2 &&
> +       git add a b dir &&
> +       git commit -m super &&
> +       git sparse-checkout init --no-cone &&
> +       git sparse-checkout set "/*" "!b" "!/*/" "sub" &&
> +
> +       git tag -am tag-to-commit tag-to-commit HEAD &&
> +       tree=$(git rev-parse HEAD^{tree}) &&
> +       git tag -am tag-to-tree tag-to-tree $tree &&
> +
> +       test_path_is_missing b &&
> +       test_path_is_missing dir &&
> +       test_path_is_missing sub/A &&
> +       test_path_is_file a &&
> +       test_path_is_file sub/B/b &&
> +       test_path_is_file sub2/a
> +'
> +
> +# The test bellow checks a special case: the sparsity patterns exclude '/b'

s/bellow/below/

> +# and sparse checkout is enable, but the path exists on the working tree (e.g.

s/enable/enabled/, s/on/in/

> +# manually created after `git sparse-checkout init`). In this case, grep should
> +# skip it.
> +test_expect_success 'grep in working tree should honor sparse checkout' '
> +       cat >expect <<-EOF &&
> +       a:text
> +       EOF
> +       echo "new-text" >b &&
> +       test_when_finished "rm b" &&
> +       git grep "text" >actual &&
> +       test_cmp expect actual
> +'
> +
> +test_expect_success 'grep --cached should honor sparse checkout' '
> +       cat >expect <<-EOF &&
> +       a:text
> +       EOF
> +       git grep --cached "text" >actual &&
> +       test_cmp expect actual
> +'
> +
> +test_expect_success 'grep <commit-ish> should honor sparse checkout' '
> +       commit=$(git rev-parse HEAD) &&
> +       cat >expect_commit <<-EOF &&
> +       $commit:a:text
> +       EOF
> +       cat >expect_tag-to-commit <<-EOF &&
> +       tag-to-commit:a:text
> +       EOF
> +       git grep "text" $commit >actual_commit &&
> +       test_cmp expect_commit actual_commit &&
> +       git grep "text" tag-to-commit >actual_tag-to-commit &&
> +       test_cmp expect_tag-to-commit actual_tag-to-commit
> +'
> +
> +test_expect_success 'grep <tree-ish> should ignore sparsity patterns' '
> +       commit=$(git rev-parse HEAD) &&
> +       tree=$(git rev-parse HEAD^{tree}) &&
> +       cat >expect_tree <<-EOF &&
> +       $tree:a:text
> +       $tree:b:text
> +       $tree:dir/c:text
> +       EOF
> +       cat >expect_tag-to-tree <<-EOF &&
> +       tag-to-tree:a:text
> +       tag-to-tree:b:text
> +       tag-to-tree:dir/c:text
> +       EOF
> +       git grep "text" $tree >actual_tree &&
> +       test_cmp expect_tree actual_tree &&
> +       git grep "text" tag-to-tree >actual_tag-to-tree &&
> +       test_cmp expect_tag-to-tree actual_tag-to-tree
> +'
> +
> +# Note that sub2/ is present in the worktree but it is excluded by the sparsity
> +# patterns, so grep should not recurse into it.
> +test_expect_success 'grep --recurse-submodules should honor sparse checkout in submodule' '
> +       cat >expect <<-EOF &&
> +       a:text
> +       sub/B/b:text
> +       EOF
> +       git grep --recurse-submodules "text" >actual &&
> +       test_cmp expect actual
> +'
> +
> +test_expect_success 'grep --recurse-submodules --cached should honor sparse checkout in submodule' '
> +       cat >expect <<-EOF &&
> +       a:text
> +       sub/B/b:text
> +       EOF
> +       git grep --recurse-submodules --cached "text" >actual &&
> +       test_cmp expect actual
> +'
> +
> +test_expect_success 'grep --recurse-submodules <commit-ish> should honor sparse checkout in submodule' '
> +       commit=$(git rev-parse HEAD) &&
> +       cat >expect_commit <<-EOF &&
> +       $commit:a:text
> +       $commit:sub/B/b:text
> +       EOF
> +       cat >expect_tag-to-commit <<-EOF &&
> +       tag-to-commit:a:text
> +       tag-to-commit:sub/B/b:text
> +       EOF
> +       git grep --recurse-submodules "text" $commit >actual_commit &&
> +       test_cmp expect_commit actual_commit &&
> +       git grep --recurse-submodules "text" tag-to-commit >actual_tag-to-commit &&
> +       test_cmp expect_tag-to-commit actual_tag-to-commit
> +'
> +
> +test_done
> --
> 2.26.2

Looks good.  Do we want to add a testcase where a file is unmerged and
present in the working copy despite not matching the sparsity patterns
(i.e. to emulate being in the middle of a merge/rebase/cherry-pick)?

```

## Elijah Newren, 2020-05-30 16:18

Subject: Re: [PATCH v3 5/5] config: add setting to ignore sparsity patterns in some cmds
Message-ID: <CABPp-BHzHhBVGZ+vOgE4jTCT3HJzXo+gzZ+6SVGDUWWdfkL6Dw@mail.gmail.com>
URL: https://gitlist.dev/e/CABPp-BHzHhBVGZ%2BvOgE4jTCT3HJzXo%2BgzZ%2B6SVGDUWWdfkL6Dw%40mail.gmail.com
In-Reply-To: <748b1e955ccdcf7cd897a180f4b4fe82d7bfcf00.1590627264.git.matheus.bernardino@usp.br>

```
On Wed, May 27, 2020 at 6:14 PM Matheus Tavares
<matheus.bernardino@usp.br> wrote:
>
> When sparse checkout is enabled, some users expect the output of certain
> commands (such as grep, diff, and log) to be also restricted within the
> sparsity patterns. This would allow them to effectively work only on the
> subset of files in which they are interested; and allow some commands to
> possibly perform better, by not considering uninteresting paths. For
> this reason, we taught grep to honor the sparsity patterns, in the
> previous patch. But, on the other hand, allowing grep and the other
> commands mentioned to optionally ignore the patterns also make for some
> interesting use cases. E.g. using grep to search for a function
> documentation that resides outside the sparse checkout.
>
> In any case, there is no current way for users to configure the behavior
> they want for these commands. Aiming to provide this flexibility, let's
> introduce the sparse.restrictCmds setting (and the analogous
> --[no]-restrict-to-sparse-paths global option). The default value is
> true. For now, grep is the only one affected by this setting, but the
> goal is to have support for more commands, in the future.
>
> Helped-by: Elijah Newren <newren@gmail.com>
> Signed-off-by: Matheus Tavares <matheus.bernardino@usp.br>
> ---
>  Documentation/config.txt               |   2 +
>  Documentation/config/sparse.txt        |  24 +++++
>  Documentation/git-grep.txt             |   3 +
>  Documentation/git.txt                  |   4 +
>  Makefile                               |   1 +
>  builtin/grep.c                         |  13 ++-
>  contrib/completion/git-completion.bash |   2 +
>  git.c                                  |   6 ++
>  sparse-checkout.c                      |  16 +++
>  sparse-checkout.h                      |  11 +++
>  t/t7817-grep-sparse-checkout.sh        | 132 ++++++++++++++++++++++++-
>  t/t9902-completion.sh                  |   4 +-
>  12 files changed, 212 insertions(+), 6 deletions(-)
>  create mode 100644 Documentation/config/sparse.txt
>  create mode 100644 sparse-checkout.c
>  create mode 100644 sparse-checkout.h
>
> diff --git a/Documentation/config.txt b/Documentation/config.txt
> index ef0768b91a..fd74b80302 100644
> --- a/Documentation/config.txt
> +++ b/Documentation/config.txt
> @@ -436,6 +436,8 @@ include::config/sequencer.txt[]
>
>  include::config/showbranch.txt[]
>
> +include::config/sparse.txt[]
> +
>  include::config/splitindex.txt[]
>
>  include::config/ssh.txt[]
> diff --git a/Documentation/config/sparse.txt b/Documentation/config/sparse.txt
> new file mode 100644
> index 0000000000..2a25b4b8ef
> --- /dev/null
> +++ b/Documentation/config/sparse.txt
> @@ -0,0 +1,24 @@
> +sparse.restrictCmds::
> +       Only meaningful in conjunction with core.sparseCheckout. This option
> +       extends sparse checkouts (which limit which paths are written to the
> +       working tree), so that output and operations are also limited to the
> +       sparsity paths where possible and implemented. The purpose of this
> +       option is to (1) focus output for the user on the portion of the
> +       repository that is of interest to them, and (2) enable potentially
> +       dramatic performance improvements, especially in conjunction with
> +       partial clones.
> ++
> +When this option is true (default), some git commands may limit their behavior
> +to the paths specified by the sparsity patterns, or to the intersection of
> +those paths and any (like `*.c`) that the user might also specify on the
> +command line. When false, the affected commands will work on full trees,
> +ignoring the sparsity patterns. For now, only git-grep honors this setting. In
> +this command, the restriction takes effect in three cases: with --cached; when
> +a commit-ish is given; when searching a working tree where some paths excluded
> +by the sparsity patterns are present (e.g. manually created paths or not
> +removed submodules).

I think "In this command, the restriction takes effect..." to the end
of the paragraph should be removed.  I don't want every subcommand's
behavior to be specified here; it'll grow unreadably long and be more
likely to eventually go stale.

> ++
> +Note: commands which export, integrity check, or create history will always
> +operate on full trees (e.g. fast-export, format-patch, fsck, commit, etc.),
> +unaffected by any sparsity patterns. Also, writting commands such as
> +sparse-checkout and read-tree will not be affected by this configuration.

s/writting/writing/

> diff --git a/Documentation/git-grep.txt b/Documentation/git-grep.txt
> index 9bdf807584..abbf100109 100644
> --- a/Documentation/git-grep.txt
> +++ b/Documentation/git-grep.txt
> @@ -41,6 +41,9 @@ characters.  An empty string as search expression matches all lines.
>  CONFIGURATION
>  -------------
>
> +git-grep honors the sparse.restrictCmds setting. See its definition in
> +linkgit:git-config[1].
> +
>  :git-grep: 1
>  include::config/grep.txt[]
>
> diff --git a/Documentation/git.txt b/Documentation/git.txt
> index 9d6769e95a..5e107c6246 100644
> --- a/Documentation/git.txt
> +++ b/Documentation/git.txt
> @@ -180,6 +180,10 @@ If you just want to run git as if it was started in `<path>` then use
>         Do not perform optional operations that require locks. This is
>         equivalent to setting the `GIT_OPTIONAL_LOCKS` to `0`.
>
> +--[no-]restrict-to-sparse-paths::
> +       Overrides the sparse.restrictCmds configuration (see
> +       linkgit:git-config[1]) for this execution.
> +
>  --list-cmds=group[,group...]::
>         List commands by group. This is an internal/experimental
>         option and may change or be removed in the future. Supported
> diff --git a/Makefile b/Makefile
> index 90aa329eb7..0c0013b32c 100644
> --- a/Makefile
> +++ b/Makefile
> @@ -983,6 +983,7 @@ LIB_OBJS += sha1-name.o
>  LIB_OBJS += shallow.o
>  LIB_OBJS += sideband.o
>  LIB_OBJS += sigchain.o
> +LIB_OBJS += sparse-checkout.o
>  LIB_OBJS += split-index.o
>  LIB_OBJS += stable-qsort.o
>  LIB_OBJS += strbuf.o
> diff --git a/builtin/grep.c b/builtin/grep.c
> index 11e33b8aee..cc696dab4a 100644
> --- a/builtin/grep.c
> +++ b/builtin/grep.c
> @@ -25,6 +25,7 @@
>  #include "submodule-config.h"
>  #include "object-store.h"
>  #include "packfile.h"
> +#include "sparse-checkout.h"
>
>  static char const * const grep_usage[] = {
>         N_("git grep [<options>] [-e] <pattern> [<rev>...] [[--] <path>...]"),
> @@ -498,6 +499,7 @@ static int grep_cache(struct grep_opt *opt,
>         int nr;
>         struct strbuf name = STRBUF_INIT;
>         int name_base_len = 0;
> +       int sparse_paths_only = restrict_to_sparse_paths(repo);
>         if (repo->submodule_prefix) {
>                 name_base_len = strlen(repo->submodule_prefix);
>                 strbuf_addstr(&name, repo->submodule_prefix);
> @@ -509,7 +511,7 @@ static int grep_cache(struct grep_opt *opt,
>         for (nr = 0; nr < repo->index->cache_nr; nr++) {
>                 const struct cache_entry *ce = repo->index->cache[nr];
>
> -               if (ce_skip_worktree(ce))
> +               if (sparse_paths_only && ce_skip_worktree(ce))
>                         continue;
>
>                 strbuf_setlen(&name, name_base_len);
> @@ -715,9 +717,10 @@ static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
>                      int is_root_tree)
>  {
>         struct pattern_list *patterns = NULL;
> +       int sparse_paths_only = restrict_to_sparse_paths(opt->repo);
>         int ret;
>
> -       if (is_root_tree)
> +       if (is_root_tree && sparse_paths_only)
>                 patterns = get_sparsity_patterns(opt->repo);
>
>         ret = do_grep_tree(opt, pathspec, tree, base, tn_len, is_root_tree,

It's kinda nice how clean and easy it is to insert this new option
after the previous patch.

> @@ -1257,6 +1260,12 @@ int cmd_grep(int argc, const char **argv, const char *prefix)
>
>         if (!use_index || untracked) {
>                 int use_exclude = (opt_exclude < 0) ? use_index : !!opt_exclude;
> +
> +               if (opt_restrict_to_sparse_paths >= 0) {
> +                       die(_("--[no-]restrict-to-sparse-paths is incompatible"
> +                                 " with --no-index and --untracked"));
> +               }
> +
>                 hit = grep_directory(&opt, &pathspec, use_exclude, use_index);
>         } else if (0 <= opt_exclude) {
>                 die(_("--[no-]exclude-standard cannot be used for tracked contents"));
> diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
> index 70ad04e1b2..71956f7313 100644
> --- a/contrib/completion/git-completion.bash
> +++ b/contrib/completion/git-completion.bash
> @@ -3208,6 +3208,8 @@ __git_main ()
>                         --namespace=
>                         --no-replace-objects
>                         --help
> +                       --restrict-to-sparse-paths
> +                       --no-restrict-to-sparse-paths
>                         "
>                         ;;
>                 *)
> diff --git a/git.c b/git.c
> index a2d337eed7..6db1382ae4 100644
> --- a/git.c
> +++ b/git.c
> @@ -38,6 +38,7 @@ const char git_more_info_string[] =
>            "See 'git help git' for an overview of the system.");
>
>  static int use_pager = -1;
> +int opt_restrict_to_sparse_paths = -1;
>
>  static void list_builtins(struct string_list *list, unsigned int exclude_option);
>
> @@ -311,6 +312,10 @@ static int handle_options(const char ***argv, int *argc, int *envchanged)
>                         } else {
>                                 exit(list_cmds(cmd));
>                         }
> +               } else if (!strcmp(cmd, "--restrict-to-sparse-paths")) {
> +                       opt_restrict_to_sparse_paths = 1;
> +               } else if (!strcmp(cmd, "--no-restrict-to-sparse-paths")) {
> +                       opt_restrict_to_sparse_paths = 0;
>                 } else {
>                         fprintf(stderr, _("unknown option: %s\n"), cmd);
>                         usage(git_usage_string);
> @@ -319,6 +324,7 @@ static int handle_options(const char ***argv, int *argc, int *envchanged)
>                 (*argv)++;
>                 (*argc)--;
>         }
> +
>         return (*argv) - orig_argv;
>  }
>

Why the stray whitespace change?

> diff --git a/sparse-checkout.c b/sparse-checkout.c
> new file mode 100644
> index 0000000000..9a9e50fd29
> --- /dev/null
> +++ b/sparse-checkout.c
> @@ -0,0 +1,16 @@
> +#include "cache.h"
> +#include "config.h"
> +#include "sparse-checkout.h"
> +
> +int restrict_to_sparse_paths(struct repository *repo)
> +{
> +       int ret;
> +
> +       if (opt_restrict_to_sparse_paths >= 0)
> +               return opt_restrict_to_sparse_paths;
> +
> +       if (repo_config_get_bool(repo, "sparse.restrictcmds", &ret))
> +               ret = 1;
> +
> +       return ret;
> +}

Do we want to considering renaming this file to sparse.c, since it's
for sparse grep and sparse diff and etc., not just for the checkout
piece?  It would also go along well with our toplevel related config
being in the "sparse" namespace.

> diff --git a/sparse-checkout.h b/sparse-checkout.h
> new file mode 100644
> index 0000000000..1de3b588d8
> --- /dev/null
> +++ b/sparse-checkout.h
> @@ -0,0 +1,11 @@
> +#ifndef SPARSE_CHECKOUT_H
> +#define SPARSE_CHECKOUT_H
> +
> +struct repository;
> +
> +extern int opt_restrict_to_sparse_paths; /* from git.c */
> +
> +/* Whether or not cmds should restrict behavior on sparse paths, in this repo */
> +int restrict_to_sparse_paths(struct repository *repo);
> +
> +#endif /* SPARSE_CHECKOUT_H */
> diff --git a/t/t7817-grep-sparse-checkout.sh b/t/t7817-grep-sparse-checkout.sh
> index ce080cf572..1aef084186 100755
> --- a/t/t7817-grep-sparse-checkout.sh
> +++ b/t/t7817-grep-sparse-checkout.sh
> @@ -80,10 +80,10 @@ test_expect_success 'setup' '
>         test_path_is_file sub2/a
>  '
>
> -# The test bellow checks a special case: the sparsity patterns exclude '/b'
> +# The two tests bellow check a special case: the sparsity patterns exclude '/b'
>  # and sparse checkout is enable, but the path exists on the working tree (e.g.
>  # manually created after `git sparse-checkout init`). In this case, grep should
> -# skip it.
> +# skip the file by default, but not with --no-restrict-to-sparse-paths.
>  test_expect_success 'grep in working tree should honor sparse checkout' '
>         cat >expect <<-EOF &&
>         a:text
> @@ -93,6 +93,16 @@ test_expect_success 'grep in working tree should honor sparse checkout' '
>         git grep "text" >actual &&
>         test_cmp expect actual
>  '
> +test_expect_success 'grep w/ --no-restrict-to-sparse-paths for sparsely excluded but present paths' '
> +       cat >expect <<-EOF &&
> +       a:text
> +       b:new-text
> +       EOF
> +       echo "new-text" >b &&
> +       test_when_finished "rm b" &&
> +       git --no-restrict-to-sparse-paths grep "text" >actual &&
> +       test_cmp expect actual
> +'
>
>  test_expect_success 'grep --cached should honor sparse checkout' '
>         cat >expect <<-EOF &&
> @@ -136,7 +146,7 @@ test_expect_success 'grep <tree-ish> should ignore sparsity patterns' '
>  '
>
>  # Note that sub2/ is present in the worktree but it is excluded by the sparsity
> -# patterns, so grep should not recurse into it.
> +# patterns, so grep should only recurse into it with --no-restrict-to-sparse-paths.
>  test_expect_success 'grep --recurse-submodules should honor sparse checkout in submodule' '
>         cat >expect <<-EOF &&
>         a:text
> @@ -145,6 +155,15 @@ test_expect_success 'grep --recurse-submodules should honor sparse checkout in s
>         git grep --recurse-submodules "text" >actual &&
>         test_cmp expect actual
>  '
> +test_expect_success 'grep --recurse-submodules should search in excluded submodules w/ --no-restrict-to-sparse-paths' '
> +       cat >expect <<-EOF &&
> +       a:text
> +       sub/B/b:text
> +       sub2/a:text
> +       EOF
> +       git --no-restrict-to-sparse-paths grep --recurse-submodules "text" >actual &&
> +       test_cmp expect actual
> +'
>
>  test_expect_success 'grep --recurse-submodules --cached should honor sparse checkout in submodule' '
>         cat >expect <<-EOF &&
> @@ -171,4 +190,111 @@ test_expect_success 'grep --recurse-submodules <commit-ish> should honor sparse
>         test_cmp expect_tag-to-commit actual_tag-to-commit
>  '
>
> +for cmd in 'git --no-restrict-to-sparse-paths grep' \
> +          'git -c sparse.restrictCmds=false grep' \
> +          'git -c sparse.restrictCmds=true --no-restrict-to-sparse-paths grep'
> +do
> +
> +       test_expect_success "$cmd --cached should ignore sparsity patterns" '
> +               cat >expect <<-EOF &&
> +               a:text
> +               b:text
> +               dir/c:text
> +               EOF
> +               $cmd --cached "text" >actual &&
> +               test_cmp expect actual
> +       '
> +
> +       test_expect_success "$cmd <commit-ish> should ignore sparsity patterns" '
> +               commit=$(git rev-parse HEAD) &&
> +               cat >expect_commit <<-EOF &&
> +               $commit:a:text
> +               $commit:b:text
> +               $commit:dir/c:text
> +               EOF
> +               cat >expect_tag-to-commit <<-EOF &&
> +               tag-to-commit:a:text
> +               tag-to-commit:b:text
> +               tag-to-commit:dir/c:text
> +               EOF
> +               $cmd "text" $commit >actual_commit &&
> +               test_cmp expect_commit actual_commit &&
> +               $cmd "text" tag-to-commit >actual_tag-to-commit &&
> +               test_cmp expect_tag-to-commit actual_tag-to-commit
> +       '
> +done
> +
> +test_expect_success 'grep --recurse-submodules --cached \w --no-restrict-to-sparse-paths' '

s%\w%w/%, or s%\w%with%?  Same issue below too.

> +       cat >expect <<-EOF &&
> +       a:text
> +       b:text
> +       dir/c:text
> +       sub/A/a:text
> +       sub/B/b:text
> +       sub2/a:text
> +       EOF
> +       git --no-restrict-to-sparse-paths grep --recurse-submodules --cached \
> +               "text" >actual &&
> +       test_cmp expect actual
> +'
> +
> +test_expect_success 'grep --recurse-submodules <commit-ish> \w --no-restrict-to-sparse-paths' '
> +       commit=$(git rev-parse HEAD) &&
> +       cat >expect_commit <<-EOF &&
> +       $commit:a:text
> +       $commit:b:text
> +       $commit:dir/c:text
> +       $commit:sub/A/a:text
> +       $commit:sub/B/b:text
> +       $commit:sub2/a:text
> +       EOF
> +       cat >expect_tag-to-commit <<-EOF &&
> +       tag-to-commit:a:text
> +       tag-to-commit:b:text
> +       tag-to-commit:dir/c:text
> +       tag-to-commit:sub/A/a:text
> +       tag-to-commit:sub/B/b:text
> +       tag-to-commit:sub2/a:text
> +       EOF
> +       git --no-restrict-to-sparse-paths grep --recurse-submodules "text" \
> +               $commit >actual_commit &&
> +       test_cmp expect_commit actual_commit &&
> +       git --no-restrict-to-sparse-paths grep --recurse-submodules "text" \
> +               tag-to-commit >actual_tag-to-commit &&
> +       test_cmp expect_tag-to-commit actual_tag-to-commit
> +'
> +
> +test_expect_success 'should respect the sparse.restrictCmds values from submodules' '
> +       cat >expect <<-EOF &&
> +       a:text
> +       sub/A/a:text
> +       sub/B/b:text
> +       EOF
> +       test_config -C sub sparse.restrictCmds false &&
> +       git grep --cached --recurse-submodules "text" >actual &&
> +       test_cmp expect actual
> +'
> +
> +test_expect_success 'should propagate --[no]-restrict-to-sparse-paths to submodules' '
> +       cat >expect <<-EOF &&
> +       a:text
> +       b:text
> +       dir/c:text
> +       sub/A/a:text
> +       sub/B/b:text
> +       sub2/a:text
> +       EOF
> +       test_config -C sub sparse.restrictCmds true &&
> +       git --no-restrict-to-sparse-paths grep --cached --recurse-submodules "text" >actual &&
> +       test_cmp expect actual
> +'
> +
> +for opt in '--untracked' '--no-index'
> +do
> +       test_expect_success "--[no]-restrict-to-sparse-paths and $opt are incompatible" "
> +               test_must_fail git --restrict-to-sparse-paths grep $opt . 2>actual &&
> +               test_i18ngrep 'restrict-to-sparse-paths is incompatible with' actual
> +       "
> +done
> +
>  test_done
> diff --git a/t/t9902-completion.sh b/t/t9902-completion.sh
> index 3c44af6940..a4a7767e06 100755
> --- a/t/t9902-completion.sh
> +++ b/t/t9902-completion.sh
> @@ -1473,6 +1473,8 @@ test_expect_success 'double dash "git" itself' '
>         --namespace=
>         --no-replace-objects Z
>         --help Z
> +       --restrict-to-sparse-paths Z
> +       --no-restrict-to-sparse-paths Z
>         EOF
>  '
>
> @@ -1515,7 +1517,7 @@ test_expect_success 'general options' '
>         test_completion "git --nam" "--namespace=" &&
>         test_completion "git --bar" "--bare " &&
>         test_completion "git --inf" "--info-path " &&
> -       test_completion "git --no-r" "--no-replace-objects "
> +       test_completion "git --no-rep" "--no-replace-objects "
>  '

All these testcases look great (modulo the small typo I pointed out
earlier); I kept thinking "but what about case <x>?" and then I kept
reading and saw you covered it.  You even added some I wasn't thinking
about and might have overlooked but seem important.

```

## Matheus Tavares Bernardino, 2020-06-01 04:36

Subject: Re: [PATCH v3 2/5] t/helper/test-config: return exit codes consistently
Message-ID: <CAHd-oW7x+A8ZmW-2XUkCcN2T=m_mHQMvfH7GCW58Q49OHgVZJQ@mail.gmail.com>
URL: https://gitlist.dev/e/CAHd-oW7x%2BA8ZmW-2XUkCcN2T%3Dm_mHQMvfH7GCW58Q49OHgVZJQ%40mail.gmail.com
In-Reply-To: <CABPp-BHTmYy=AtXoCLG-xXQ_0EZ7=3xiMibkNMDLzsKCnHBoFw@mail.gmail.com>

```
On Sat, May 30, 2020 at 11:29 AM Elijah Newren <newren@gmail.com> wrote:
>
> On Wed, May 27, 2020 at 6:13 PM Matheus Tavares
> <matheus.bernardino@usp.br> wrote:
> >
> > The test-config helper may exit with a variety of at least four
> > different codes, to reflect the status of the requested operations.
> > These codes are sometimes checked in the tests, but not all of the codes
> > are returned consistently by the helper: 1 will usually refer to a
> > "value not found", but usage errors can also return 1 or 128. The latter
>
> I'm not sure what "The latter" refers to here.

It would be the 128 exit code. I'll try to reword that for clarity.

> > is also expected on errors within the configset functions. These
> > inconsistent uses of the exit codes can lead to false positives in the
> > tests. Although all tests that currently check the helper's exit code,
> > on errors, do also check the output, it's still better to standardize
> > the exit codes and avoid future problems in new tests. While we are
>
> That last sentence was slightly hard for me to parse.  Maybe something like:
>
> ...Although all tests which expect errors and check the helper's exit
> code currently also check the output, it's still better...

Sounds better, I will use that for the next version. Thanks.

```

## Matheus Tavares Bernardino, 2020-06-01 04:38

Subject: Re: [PATCH v3 3/5] config: correctly read worktree configs in submodules
Message-ID: <CAHd-oW7==zM5goS6ZrHNYADDgdkYdXLqZgKxCL2UwFAacvVsNg@mail.gmail.com>
URL: https://gitlist.dev/e/CAHd-oW7%3D%3DzM5goS6ZrHNYADDgdkYdXLqZgKxCL2UwFAacvVsNg%40mail.gmail.com
In-Reply-To: <CABPp-BGVaMM9Naiu3HeO6n2aOxsHwiuc813MF-hFWezSFa9CsA@mail.gmail.com>

```
On Sat, May 30, 2020 at 11:49 AM Elijah Newren <newren@gmail.com> wrote:
>
> On Wed, May 27, 2020 at 6:13 PM Matheus Tavares
> <matheus.bernardino@usp.br> wrote:
> >
> > One of the steps in do_git_config_sequence() is to load the
> > worktree-specific config file. Although the function receives a git_dir
> > string, it relies on git_pathdup(), which uses the_repository->git_dir,
> > to make the path to the file. Furthermore, it also checks that
> > extensions.worktreeConfig is set through the
> > repository_format_worktree_config variable, which refers to
> > the_repository only. Thus, when a submodule has worktree settings, a
> > command executed in the superproject that recurses into the submodule
> > won't find the said settings.
> >
> > Such a scenario might not be needed now, but it will be in the following
>
> It's not needed?  Are there not other config values that affect grep's
> behavior, such as smudge filters of the submodule that might be
> important if doing a 'git grep --recurse-submodules $REVISION'?

Hmm, I haven't used smudge filters before, but it seems to me that
`git grep $REVISION` does not honor them.

> Also, is there a similar issue here for .gitattributes?  (e.g. if the
> submodule declares certain files to be binary?)

Declaring files as binary in the submodule works fine. But I noticed
that textconv filter specifications in the submodule's config are
currently ignored. To be honest, I wasn't aware of this issue before.

> I don't actually know if these are issues but I'm just surprised to
> hear that this would be the first case that would need to look at
> submodule-specific configuration.

Hmm, not to submodule-specific configuration but to worktree-specific
configuration of a submodule, right? I.e. a config.worktree file from
within a submodule. Reconsidering this now, we could indeed have a
diff.<driver>.textconv or core.quotePath settings specified in the
worktree scope of a submodule. And we should honor them when recursing
in grep. I guess I thought the "most natural" place for these
settings, in a submodule, would be in the standard .git/config file
(as opposed to the sparse-checkout ones, which are normally at
config.worktree). That's probably why I wrote "Such scenario might not
be needed now". But we should indeed support reading
diff.<driver>.textconv from config.worktree as well (although grep
currently ignores this setting in submodules, both in the local and
worktree scopes). So the said sentence doesn't make much sense,
indeed. I will remove it. Thanks!

> > diff --git a/t/helper/test-config.c b/t/helper/test-config.c
> > index 1c8e965840..284f83a921 100644
> > --- a/t/helper/test-config.c
> > +++ b/t/helper/test-config.c
> > @@ -84,33 +91,63 @@ int cmd__config(int argc, const char **argv)
> >         int i, val;
> >         const char *v;
> >         const struct string_list *strptr;
> > -       struct config_set cs;
> > +       struct config_set cs = { .hash_initialized = 0 };
> >         enum test_config_exit_code ret = TC_SUCCESS;
> > +       struct repository *repo = the_repository;
> > +       const char *subrepo_path = NULL;
> > +
> > +       argc--; /* skip over "config" */
>
> This line alone is responsible for a fairly big set of changes
> throughout this file, just decrementing indices everywhere.  It might
> be nice for review purposes if this and the other changes it caused
> were pulled out into a separate step, so we can more easily
> concentrate on the primary additions and changes you are making to
> this file.

OK, will do.

```

## Matheus Tavares Bernardino, 2020-06-01 04:44

Subject: Re: [PATCH v3 4/5] grep: honor sparse checkout patterns
Message-ID: <CAHd-oW7JEu0rBrBMyjfFZ4WZ982+WwpGSvqg4meOwxmHjocknQ@mail.gmail.com>
URL: https://gitlist.dev/e/CAHd-oW7JEu0rBrBMyjfFZ4WZ982%2BWwpGSvqg4meOwxmHjocknQ%40mail.gmail.com
In-Reply-To: <CABPp-BFsCPPNOZ92JQRJeGyNd0e-TCW-LcLyr0i_+VSQJP+GCg@mail.gmail.com>

```
On Sat, May 30, 2020 at 12:48 PM Elijah Newren <newren@gmail.com> wrote:
>
> On Wed, May 27, 2020 at 6:13 PM Matheus Tavares
> <matheus.bernardino@usp.br> wrote:
> >
> > One of the main uses for a sparse checkout is to allow users to focus on
> > the subset of files in a repository in which they are interested. But
> > git-grep currently ignores the sparsity patterns and report all matches
> > found outside this subset, which kind of goes in the opposite direction.
> > Let's fix that, making it honor the sparsity boundaries for every
> > grepping case where this is relevant:
> >
> > - git grep in worktree
> > - git grep --cached
> > - git grep $REVISION
> >
> > For the worktree case, we will not grep paths that have the
> > SKIP_WORKTREE bit set, even if they are present for some reason (e.g.
> > manually created after `git sparse-checkout init`).
>
> This seems worded to rise alarm bells and make users suspect
> implementation difficulties or regrets rather than desired behavior.
> It would be much better to word this simply as something like:
>
>     For the worktree and cached cases, we iterate over paths without
> the SKIP_WORKTREE bit set, and limit our searches to these paths.
>
> > But the next patch
> > will add an option to do so. (See 'Note' below.)
>
> Because this was in the same paragraph as the previous sentence, it
> made it sound like you were going to provide a special worktree-only
> option to search outside the SKIP_WORKTREE bits.  Very confusing.  I
> think I'd combine this sentence into the very first paragraph of the
> commit message and massage the wording a little.  Perhaps something
> like:  ...goes in the opposite direction.  There are some usecases for
> ignoring the sparsity patterns and the next commit will add an option
> to obtain this behavior, but here we start by making grep honor the
> sparsity boundaries for every...
>
> > For `git grep $REVISION`, we will choose to honor the sparsity patterns
> > only when $REVISION is a commit-ish object. The reason is that, for a
> > tree, we don't know whether it represents the root of a repository or a
> > subtree. So we wouldn't be able to correctly match it against the
> > sparsity patterns. E.g. suppose we have a repository with these two
> > sparsity rules: "/*" and "!/a"; and the following structure:
> >
> > /
> > | - a (file)
> > | - d (dir)
> >     | - a (file)
> >
> > If `git grep $REVISION` were to honor the sparsity patterns for every
> > object type, when grepping the /d tree, we would wrongly ignore the /d/a
> > file. This happens because we wouldn't know it resides in /d and
> > therefore it would wrongly match the pattern "!/a". Furthermore, for a
> > search in a blob object, we wouldn't even have a path to check the
> > patterns against. So, let's ignore the sparsity patterns when grepping
> > non-commit-ish objects.
>
> This doesn't actually make it clear how you handle $REVISION which is
> a commit object; you focus so much on when $REVISION is just a tree
> and contrasting that case that you omit the behavior for the case of
> interest.  Also, $REVISION to my mind implies "commit"; if you want to
> imply that a commit or tree could be used, you'd use $TREE or
> $TREE_ISH or something else.  I think it'd make sense to cover all
> three relevant cases into a single paragraph (thus combining with the
> previous paragraph), and then add a second paragraph about the $TREE
> case that streamlines the last two pargraphs above.  So, perhaps we
> can your paragraphs from "For the worktree case, we will not grep
> paths..." all the way to "So, let's ignore the sparsity patterns when
> grepping non-commit-ish objects" (after first moving the comment about
> adding an option in the next commit to some other area of the commit
> message, as dicussed above) with something like the following:
>
>     For the worktree and cached cases, we iterate over paths without
> the SKIP_WORKTREE bit set, and limit our searches to these paths.  For
> the $REVISION case, we limit the paths we search to those that match
> the sparsity patterns.  (We do not check the SKIP_WORKTREE bit for the
> $REVISION case, because $REVISION may contain paths that do not exist
> in HEAD and thus for which we have no SKIP_WORKTREE bit to consult.
> The sparsity patterns tell us how the SKIP_WORKTREE bit would be set
> if we were to check out $REVISION, so we consult those.  Also, we
> don't use the sparsity paths with the worktree or cached cases, both
> because we have a bit we can check directly and more efficiently, and
> because unmerged entries from a merge or a rebase could cause more
> files to temporarily be present than the sparsity patterns would
> normally select.)
>
>     Note that there is a special case here: `git grep $TREE`.  In this
> case we cannot know whether $TREE corresponds to the root of the
> repository or some sub-tree, and thus there is no way for us to know
> which sparsity patterns, if any, apply.  So the $TREE case will not
> use sparsity patterns or any SKIP_WORKTREE bits and will instead
> always search all files within the $TREE.
>
> >
> > Note: The behavior introduced in this patch is what some users have
> > reported[1] that they would like by default. But the old behavior is
> > still desirable for some use cases. Therefore, the next patch will add
> > an option to allow restoring it when needed.
>
> This paragraph duplicates information you already stated previously.
> It's much clearer than what you stated before, but if you just reword
> the previous comments and combine them into the first paragraph, then
> we can drop this final note.

All great suggestions! I will amend the commit message using your
proposed paragraphs. Thanks!

> >
> > Signed-off-by: Matheus Tavares <matheus.bernardino@usp.br>
> > ---
> >  builtin/grep.c                   | 125 ++++++++++++++++++++--
> >  t/t7011-skip-worktree-reading.sh |   9 --
> >  t/t7817-grep-sparse-checkout.sh  | 174 +++++++++++++++++++++++++++++++
[...]
> > +static struct pattern_list *get_sparsity_patterns(struct repository *repo)
> > +{
> > +       struct pattern_list *patterns;
> > +       char *sparse_file;
> > +       int sparse_config, cone_config;
> > +
> > +       if (repo_config_get_bool(repo, "core.sparsecheckout", &sparse_config) ||
> > +           !sparse_config) {
> > +               return NULL;
> > +       }
>
> Is core_apply_sparse_checkout not initialized for some reason?

It should be already initialized, yes. But we cannot rely on that as
`repo` might be a submodule, and core_apply_sparse_checkout holds the
configuration's value for `the_repository`.

> > +static int in_sparse_checkout(struct strbuf *path, int prefix_len,
>
> This function name in_sparse_checkout() makes me think "Does the
> working tree represent a sparse checkout?"  Perhaps we could rename it
> to path_matches_sparsity_patterns() ?
>
> Also, is there a reason we can't use dir.c's
> path_matches_pattern_list() here?

Oh, we do use path_matches_pattern_list() inside:

> > +       *match = path_matches_pattern_list(path->buf, path->len,
> > +                                          path->buf + prefix_len, &dtype,
> > +                                          sparsity, istate);
> > +       if (*match == UNDECIDED)
> > +               *match = parent_match;

> How does this new function differ
> in behavior from that function?

The idea of in_sparse_checkout() is to implement a logic closer to
what we have in clear_ce_flags_1(). Here, it is effectively a wrapper
to path_matches_pattern_list() but with some extra logic to decide
whether grep should search in a given entry, based on its mode, the
match result against the sparsity patterns, and the result from the
parent dir.

> > diff --git a/t/t7817-grep-sparse-checkout.sh b/t/t7817-grep-sparse-checkout.sh
> > new file mode 100755
> > index 0000000000..ce080cf572
> > --- /dev/null
> > +++ b/t/t7817-grep-sparse-checkout.sh
> > @@ -0,0 +1,174 @@
> > +#!/bin/sh
> > +
> > +test_description='grep in sparse checkout
> > +
> > +This test creates a repo with the following structure:
> > +
> > +.
> > +|-- a
> > +|-- b
> > +|-- dir
> > +|   `-- c
> > +|-- sub
> > +|   |-- A
> > +|   |   `-- a
> > +|   `-- B
> > +|       `-- b
> > +`-- sub2
> > +    `-- a
> > +
> > +Where . has non-cone mode sparsity patterns, sub is a submodule with cone mode
>
> Maybe "Where the outer repository has non-code mode..."?  The use of
> '.' threw me for a bit.

Sure!

> > +test_done
> > --
> > 2.26.2
>
> Looks good.  Do we want to add a testcase where a file is unmerged and
> present in the working copy despite not matching the sparsity patterns
> (i.e. to emulate being in the middle of a merge/rebase/cherry-pick)?

Sure, I can add that. But after a quick test here, it seems that the
unmerged path doesn't have the SKIP_WORKTREE bit set. Is this how it
should be?

```

## Matheus Tavares Bernardino, 2020-06-01 04:45

Subject: Re: [PATCH v3 5/5] config: add setting to ignore sparsity patterns in some cmds
Message-ID: <CAHd-oW7b41hqfPXm_GL_sth+QRfx56ceMr4VM9B9xhj3_P9iGQ@mail.gmail.com>
URL: https://gitlist.dev/e/CAHd-oW7b41hqfPXm_GL_sth%2BQRfx56ceMr4VM9B9xhj3_P9iGQ%40mail.gmail.com
In-Reply-To: <CABPp-BHzHhBVGZ+vOgE4jTCT3HJzXo+gzZ+6SVGDUWWdfkL6Dw@mail.gmail.com>

```
On Sat, May 30, 2020 at 1:18 PM Elijah Newren <newren@gmail.com> wrote:
>
> On Wed, May 27, 2020 at 6:14 PM Matheus Tavares
> <matheus.bernardino@usp.br> wrote:
> > diff --git a/Documentation/config/sparse.txt b/Documentation/config/sparse.txt
> > new file mode 100644
> > index 0000000000..2a25b4b8ef
> > --- /dev/null
> > +++ b/Documentation/config/sparse.txt
> > @@ -0,0 +1,24 @@
> > +sparse.restrictCmds::
> > +       Only meaningful in conjunction with core.sparseCheckout. This option
> > +       extends sparse checkouts (which limit which paths are written to the
> > +       working tree), so that output and operations are also limited to the
> > +       sparsity paths where possible and implemented. The purpose of this
> > +       option is to (1) focus output for the user on the portion of the
> > +       repository that is of interest to them, and (2) enable potentially
> > +       dramatic performance improvements, especially in conjunction with
> > +       partial clones.
> > ++
> > +When this option is true (default), some git commands may limit their behavior
> > +to the paths specified by the sparsity patterns, or to the intersection of
> > +those paths and any (like `*.c`) that the user might also specify on the
> > +command line. When false, the affected commands will work on full trees,
> > +ignoring the sparsity patterns. For now, only git-grep honors this setting. In
> > +this command, the restriction takes effect in three cases: with --cached; when
> > +a commit-ish is given; when searching a working tree where some paths excluded
> > +by the sparsity patterns are present (e.g. manually created paths or not
> > +removed submodules).
>
> I think "In this command, the restriction takes effect..." to the end
> of the paragraph should be removed.  I don't want every subcommand's
> behavior to be specified here; it'll grow unreadably long and be more
> likely to eventually go stale.

Yeah, I was also concerned about that. But wouldn't it be important to
inform the users how the setting takes place in grep (specially with
the corner cases)? And maybe others, in the future?

What if we move the information that is only relevant to a single
command into its own man page? I.e. git-grep.txt would have something
like:

sparse.restrictCmds::
See complete definition in linkgit:git-config[1]. In grep, the
restriction takes effect in three cases: with --cached; when a
commit-ish is given; when searching a working tree where some paths
excluded by the sparsity patterns are present (e.g. manually created
paths or not removed submodules).

The only problem then is that the information would be a little
scattered... But I think it shouldn't be a big deal, as a person
interested in knowing how foo behaves with sparse.restrictCmds would
only need to look into foo's man page, anyway.

> > diff --git a/git.c b/git.c
> > index a2d337eed7..6db1382ae4 100644
> > --- a/git.c
> > +++ b/git.c
> > @@ -319,6 +324,7 @@ static int handle_options(const char ***argv, int *argc, int *envchanged)
> >                 (*argv)++;
> >                 (*argc)--;
> >         }
> > +
> >         return (*argv) - orig_argv;
> >  }
> >
>
> Why the stray whitespace change?

Oops, that shouldn't be there. Thanks!

>
> > diff --git a/sparse-checkout.c b/sparse-checkout.c
> > new file mode 100644
> > index 0000000000..9a9e50fd29
> > --- /dev/null
> > +++ b/sparse-checkout.c
> > @@ -0,0 +1,16 @@
> > +#include "cache.h"
> > +#include "config.h"
> > +#include "sparse-checkout.h"
> > +
> > +int restrict_to_sparse_paths(struct repository *repo)
> > +{
> > +       int ret;
> > +
> > +       if (opt_restrict_to_sparse_paths >= 0)
> > +               return opt_restrict_to_sparse_paths;
> > +
> > +       if (repo_config_get_bool(repo, "sparse.restrictcmds", &ret))
> > +               ret = 1;
> > +
> > +       return ret;
> > +}
>
> Do we want to considering renaming this file to sparse.c, since it's
> for sparse grep and sparse diff and etc., not just for the checkout
> piece?  It would also go along well with our toplevel related config
> being in the "sparse" namespace.

Makes sense. But since Stolee is already working on
"sparse-checkout.c" [1], if we use "sparse.c" in this series we will
end up with two extra files. And as "sparse.c" is quite small, I think
we could unify into the "sparse-checkout.c".

[1]: https://lore.kernel.org/git/0181a134bfb6986dc0e54ae624c478446a1324a9.1588857462.git.gitgitgadget@gmail.com/

> > diff --git a/t/t7817-grep-sparse-checkout.sh b/t/t7817-grep-sparse-checkout.sh
> > index ce080cf572..1aef084186 100755
> > --- a/t/t7817-grep-sparse-checkout.sh
> > +++ b/t/t7817-grep-sparse-checkout.sh
>
> All these testcases look great (modulo the small typo I pointed out
> earlier); I kept thinking "but what about case <x>?" and then I kept
> reading and saw you covered it.  You even added some I wasn't thinking
> about and might have overlooked but seem important.

Thanks :)

```

## Elijah Newren, 2020-06-03 02:38

Subject: Re: [PATCH v3 4/5] grep: honor sparse checkout patterns
Message-ID: <CABPp-BF6=s-cAy98d-FTTExeR18YhxrHmDNzbH-1P8AiMfskfg@mail.gmail.com>
URL: https://gitlist.dev/e/CABPp-BF6%3Ds-cAy98d-FTTExeR18YhxrHmDNzbH-1P8AiMfskfg%40mail.gmail.com
In-Reply-To: <CAHd-oW7JEu0rBrBMyjfFZ4WZ982+WwpGSvqg4meOwxmHjocknQ@mail.gmail.com>

```
On Sun, May 31, 2020 at 9:44 PM Matheus Tavares Bernardino
<matheus.bernardino@usp.br> wrote:
>
> On Sat, May 30, 2020 at 12:48 PM Elijah Newren <newren@gmail.com> wrote:
> >
> > On Wed, May 27, 2020 at 6:13 PM Matheus Tavares
> > <matheus.bernardino@usp.br> wrote:
> > >
[...]
> > > +static struct pattern_list *get_sparsity_patterns(struct repository *repo)
> > > +{
> > > +       struct pattern_list *patterns;
> > > +       char *sparse_file;
> > > +       int sparse_config, cone_config;
> > > +
> > > +       if (repo_config_get_bool(repo, "core.sparsecheckout", &sparse_config) ||
> > > +           !sparse_config) {
> > > +               return NULL;
> > > +       }
> >
> > Is core_apply_sparse_checkout not initialized for some reason?
>
> It should be already initialized, yes. But we cannot rely on that as
> `repo` might be a submodule, and core_apply_sparse_checkout holds the
> configuration's value for `the_repository`.

Ah, gotcha.  Thanks for straightening me out.

> > > +static int in_sparse_checkout(struct strbuf *path, int prefix_len,
> >
> > This function name in_sparse_checkout() makes me think "Does the
> > working tree represent a sparse checkout?"  Perhaps we could rename it
> > to path_matches_sparsity_patterns() ?
> >
> > Also, is there a reason we can't use dir.c's
> > path_matches_pattern_list() here?
>
> Oh, we do use path_matches_pattern_list() inside:
>
> > > +       *match = path_matches_pattern_list(path->buf, path->len,
> > > +                                          path->buf + prefix_len, &dtype,
> > > +                                          sparsity, istate);
> > > +       if (*match == UNDECIDED)
> > > +               *match = parent_match;
>
> > How does this new function differ
> > in behavior from that function?
>
> The idea of in_sparse_checkout() is to implement a logic closer to
> what we have in clear_ce_flags_1(). Here, it is effectively a wrapper
> to path_matches_pattern_list() but with some extra logic to decide
> whether grep should search in a given entry, based on its mode, the
> match result against the sparsity patterns, and the result from the
> parent dir.

I've had this response and one to 5/5 sitting in my draft folder for
over a day because I was hoping to go read clear_ce_flags_1() and find
out what it is.  I have no idea, so your answer doesn't answer my
question... ;-)  I'll try to find some time and maybe respond further
after I do.

>
> > > diff --git a/t/t7817-grep-sparse-checkout.sh b/t/t7817-grep-sparse-checkout.sh
> > > new file mode 100755
> > > index 0000000000..ce080cf572
> > > --- /dev/null
> > > +++ b/t/t7817-grep-sparse-checkout.sh
> > > @@ -0,0 +1,174 @@
> > > +#!/bin/sh
> > > +
> > > +test_description='grep in sparse checkout
> > > +
> > > +This test creates a repo with the following structure:
> > > +
> > > +.
> > > +|-- a
> > > +|-- b
> > > +|-- dir
> > > +|   `-- c
> > > +|-- sub
> > > +|   |-- A
> > > +|   |   `-- a
> > > +|   `-- B
> > > +|       `-- b
> > > +`-- sub2
> > > +    `-- a
> > > +
> > > +Where . has non-cone mode sparsity patterns, sub is a submodule with cone mode
> >
> > Maybe "Where the outer repository has non-code mode..."?  The use of
> > '.' threw me for a bit.
>
> Sure!
>
> > > +test_done
> > > --
> > > 2.26.2
> >
> > Looks good.  Do we want to add a testcase where a file is unmerged and
> > present in the working copy despite not matching the sparsity patterns
> > (i.e. to emulate being in the middle of a merge/rebase/cherry-pick)?
>
> Sure, I can add that. But after a quick test here, it seems that the
> unmerged path doesn't have the SKIP_WORKTREE bit set. Is this how it
> should be?

Right, the merge machinery will clear the SKIP_WORKTREE bit when it
writes out conflicted files.  Also, any future 'git sparse-checkout'
commands will see the unmerged entry and avoid marking it as
SKIP_WORKTREE even though it doesn't match the sparsity patterns.
Thus, grep doesn't have to do any special checking for whether the
files are merged or not, and from your current implementation probably
doesn't look like a special case at all -- you just check the
SKIP_WORKTREE bit.

However, I think the test still has value because the test enforces
that other areas of the code (merge, sparse-checkout) don't break the
invariants that grep is relying on.  (I could see someone making a
merge change that keeps the SKIP_WORKTREE bit accidentally set even
though it writes the file out to the working tree, for example.)
Sure, merge has some tests around that, so it might be viewed as
slightly duplicative, but I see it as an interesting edge case that
exercises whether the SKIP_WORKTREE bit should really be set and since
grep expects a certain invariant about how that is handled, the
testcase will help make sure our expectations aren't violated.

```

## Elijah Newren, 2020-06-03 02:39

Subject: Re: [PATCH v3 5/5] config: add setting to ignore sparsity patterns in some cmds
Message-ID: <CABPp-BH0d5WKz7bXLkFQGDBKXbd0tccS_+1_iNc1Wqr93h+KaQ@mail.gmail.com>
URL: https://gitlist.dev/e/CABPp-BH0d5WKz7bXLkFQGDBKXbd0tccS_%2B1_iNc1Wqr93h%2BKaQ%40mail.gmail.com
In-Reply-To: <CAHd-oW7b41hqfPXm_GL_sth+QRfx56ceMr4VM9B9xhj3_P9iGQ@mail.gmail.com>

```
On Sun, May 31, 2020 at 9:46 PM Matheus Tavares Bernardino
<matheus.bernardino@usp.br> wrote:
>
> On Sat, May 30, 2020 at 1:18 PM Elijah Newren <newren@gmail.com> wrote:
> >
> > On Wed, May 27, 2020 at 6:14 PM Matheus Tavares
> > <matheus.bernardino@usp.br> wrote:
> > > diff --git a/Documentation/config/sparse.txt b/Documentation/config/sparse.txt
> > > new file mode 100644
> > > index 0000000000..2a25b4b8ef
> > > --- /dev/null
> > > +++ b/Documentation/config/sparse.txt
> > > @@ -0,0 +1,24 @@
> > > +sparse.restrictCmds::
> > > +       Only meaningful in conjunction with core.sparseCheckout. This option
> > > +       extends sparse checkouts (which limit which paths are written to the
> > > +       working tree), so that output and operations are also limited to the
> > > +       sparsity paths where possible and implemented. The purpose of this
> > > +       option is to (1) focus output for the user on the portion of the
> > > +       repository that is of interest to them, and (2) enable potentially
> > > +       dramatic performance improvements, especially in conjunction with
> > > +       partial clones.
> > > ++
> > > +When this option is true (default), some git commands may limit their behavior
> > > +to the paths specified by the sparsity patterns, or to the intersection of
> > > +those paths and any (like `*.c`) that the user might also specify on the
> > > +command line. When false, the affected commands will work on full trees,
> > > +ignoring the sparsity patterns. For now, only git-grep honors this setting. In
> > > +this command, the restriction takes effect in three cases: with --cached; when
> > > +a commit-ish is given; when searching a working tree where some paths excluded
> > > +by the sparsity patterns are present (e.g. manually created paths or not
> > > +removed submodules).
> >
> > I think "In this command, the restriction takes effect..." to the end
> > of the paragraph should be removed.  I don't want every subcommand's
> > behavior to be specified here; it'll grow unreadably long and be more
> > likely to eventually go stale.
>
> Yeah, I was also concerned about that. But wouldn't it be important to
> inform the users how the setting takes place in grep (specially with
> the corner cases)? And maybe others, in the future?
>
> What if we move the information that is only relevant to a single
> command into its own man page? I.e. git-grep.txt would have something
> like:

Moving it to grep's manpage seems ideal to me.  grep's behavior should
be defined in grep's manual.

> sparse.restrictCmds::
> See complete definition in linkgit:git-config[1]. In grep, the
> restriction takes effect in three cases: with --cached; when a
> commit-ish is given; when searching a working tree where some paths
> excluded by the sparsity patterns are present (e.g. manually created
> paths or not removed submodules).

That looks more than a little confusing.  Could this definition be
something more like "See base definition in linkgit:git-config[1].
grep honors sparse.restrictCmds by limiting searches to the sparsity
paths in three cases: when searching the working tree, when searching
the index with --cached, or when searching a specified commit"

> The only problem then is that the information would be a little
> scattered... But I think it shouldn't be a big deal, as a person
> interested in knowing how foo behaves with sparse.restrictCmds would
> only need to look into foo's man page, anyway.
>
> > > diff --git a/git.c b/git.c
> > > index a2d337eed7..6db1382ae4 100644
> > > --- a/git.c
> > > +++ b/git.c
> > > @@ -319,6 +324,7 @@ static int handle_options(const char ***argv, int *argc, int *envchanged)
> > >                 (*argv)++;
> > >                 (*argc)--;
> > >         }
> > > +
> > >         return (*argv) - orig_argv;
> > >  }
> > >
> >
> > Why the stray whitespace change?
>
> Oops, that shouldn't be there. Thanks!
>
> >
> > > diff --git a/sparse-checkout.c b/sparse-checkout.c
> > > new file mode 100644
> > > index 0000000000..9a9e50fd29
> > > --- /dev/null
> > > +++ b/sparse-checkout.c
> > > @@ -0,0 +1,16 @@
> > > +#include "cache.h"
> > > +#include "config.h"
> > > +#include "sparse-checkout.h"
> > > +
> > > +int restrict_to_sparse_paths(struct repository *repo)
> > > +{
> > > +       int ret;
> > > +
> > > +       if (opt_restrict_to_sparse_paths >= 0)
> > > +               return opt_restrict_to_sparse_paths;
> > > +
> > > +       if (repo_config_get_bool(repo, "sparse.restrictcmds", &ret))
> > > +               ret = 1;
> > > +
> > > +       return ret;
> > > +}
> >
> > Do we want to considering renaming this file to sparse.c, since it's
> > for sparse grep and sparse diff and etc., not just for the checkout
> > piece?  It would also go along well with our toplevel related config
> > being in the "sparse" namespace.
>
> Makes sense. But since Stolee is already working on
> "sparse-checkout.c" [1], if we use "sparse.c" in this series we will
> end up with two extra files. And as "sparse.c" is quite small, I think
> we could unify into the "sparse-checkout.c".
>
> [1]: https://lore.kernel.org/git/0181a134bfb6986dc0e54ae624c478446a1324a9.1588857462.git.gitgitgadget@gmail.com/

Or we could just suggest he use sparse.c too.  :-)

Stolee?


> > > diff --git a/t/t7817-grep-sparse-checkout.sh b/t/t7817-grep-sparse-checkout.sh
> > > index ce080cf572..1aef084186 100755
> > > --- a/t/t7817-grep-sparse-checkout.sh
> > > +++ b/t/t7817-grep-sparse-checkout.sh
> >
> > All these testcases look great (modulo the small typo I pointed out
> > earlier); I kept thinking "but what about case <x>?" and then I kept
> > reading and saw you covered it.  You even added some I wasn't thinking
> > about and might have overlooked but seem important.
>
> Thanks :)

```

## Matheus Tavares Bernardino, 2020-06-10 17:08

Subject: Re: [PATCH v3 4/5] grep: honor sparse checkout patterns
Message-ID: <CAHd-oW4bKG+MDCaDm+5Ha-+vvFy=LT9nnxCmQUre-BCtqWcd3Q@mail.gmail.com>
URL: https://gitlist.dev/e/CAHd-oW4bKG%2BMDCaDm%2B5Ha-%2BvvFy%3DLT9nnxCmQUre-BCtqWcd3Q%40mail.gmail.com
In-Reply-To: <CABPp-BF6=s-cAy98d-FTTExeR18YhxrHmDNzbH-1P8AiMfskfg@mail.gmail.com>

```
On Tue, Jun 2, 2020 at 11:38 PM Elijah Newren <newren@gmail.com> wrote:
>
> On Sun, May 31, 2020 at 9:44 PM Matheus Tavares Bernardino
> <matheus.bernardino@usp.br> wrote:
> >
> > On Sat, May 30, 2020 at 12:48 PM Elijah Newren <newren@gmail.com> wrote:
> > >
> > > On Wed, May 27, 2020 at 6:13 PM Matheus Tavares
> > > <matheus.bernardino@usp.br> wrote:
> > > >
> > > > +static int in_sparse_checkout(struct strbuf *path, int prefix_len,
> > >
> > > This function name in_sparse_checkout() makes me think "Does the
> > > working tree represent a sparse checkout?"  Perhaps we could rename it
> > > to path_matches_sparsity_patterns() ?
> > >
> > > Also, is there a reason we can't use dir.c's
> > > path_matches_pattern_list() here?
> >
> > Oh, we do use path_matches_pattern_list() inside:
> >
> > > > +       *match = path_matches_pattern_list(path->buf, path->len,
> > > > +                                          path->buf + prefix_len, &dtype,
> > > > +                                          sparsity, istate);
> > > > +       if (*match == UNDECIDED)
> > > > +               *match = parent_match;
> >
> > > How does this new function differ
> > > in behavior from that function?
> >
> > The idea of in_sparse_checkout() is to implement a logic closer to
> > what we have in clear_ce_flags_1(). Here, it is effectively a wrapper
> > to path_matches_pattern_list() but with some extra logic to decide
> > whether grep should search in a given entry, based on its mode, the
> > match result against the sparsity patterns, and the result from the
> > parent dir.
>
> I've had this response and one to 5/5 sitting in my draft folder for
> over a day because I was hoping to go read clear_ce_flags_1() and find
> out what it is.  I have no idea, so your answer doesn't answer my
> question... ;-)  I'll try to find some time and maybe respond further
> after I do.

Oops, sorry for the incomplete answer. clear_ce_flags() recursively
traverses the index entries, unsetting the bits specified in a given
mask when the entry matches a given pattern list. (It is used in
unpack-trees.c:mark_new_skip_worktree() to clear the
CE_NEW_SKIP_WORKTREE bit for the matched entries.) clear_ce_flags()
does use path_matches_pattern_list() but it also has to check some
additional rules for cone mode (as there might be recursive
matches/non-matches). These rules are implemented in
clear_ce_flags_dir().

in_sparse_checkout() is a small wrapper around
path_matches_pattern_list() with (1) the additional checks for cone
mode, similar to what clear_ce_flags_dir() implements, and (2) the
usage of the parent dir's match_result when undecided about the
current path. We could just implement this directly in grep_tree(),
but I thought that isolating this logic into its own static function
would make grep_tree() more readable.

> > > > diff --git a/t/t7817-grep-sparse-checkout.sh b/t/t7817-grep-sparse-checkout.sh
> > > > new file mode 100755
> > > > index 0000000000..ce080cf572
> > > > --- /dev/null
> > > > +++ b/t/t7817-grep-sparse-checkout.sh
> > >
> > > Looks good.  Do we want to add a testcase where a file is unmerged and
> > > present in the working copy despite not matching the sparsity patterns
> > > (i.e. to emulate being in the middle of a merge/rebase/cherry-pick)?
> >
> > Sure, I can add that. But after a quick test here, it seems that the
> > unmerged path doesn't have the SKIP_WORKTREE bit set. Is this how it
> > should be?
>
> Right, the merge machinery will clear the SKIP_WORKTREE bit when it
> writes out conflicted files.  Also, any future 'git sparse-checkout'
> commands will see the unmerged entry and avoid marking it as
> SKIP_WORKTREE even though it doesn't match the sparsity patterns.
> Thus, grep doesn't have to do any special checking for whether the
> files are merged or not, and from your current implementation probably
> doesn't look like a special case at all -- you just check the
> SKIP_WORKTREE bit.
>
> However, I think the test still has value because the test enforces
> that other areas of the code (merge, sparse-checkout) don't break the
> invariants that grep is relying on.  (I could see someone making a
> merge change that keeps the SKIP_WORKTREE bit accidentally set even
> though it writes the file out to the working tree, for example.)
> Sure, merge has some tests around that, so it might be viewed as
> slightly duplicative, but I see it as an interesting edge case that
> exercises whether the SKIP_WORKTREE bit should really be set and since
> grep expects a certain invariant about how that is handled, the
> testcase will help make sure our expectations aren't violated.

OK. I will add this test for the next version.

```

## Matheus Tavares Bernardino, 2020-06-10 21:15

Subject: Re: [PATCH v3 5/5] config: add setting to ignore sparsity patterns in some cmds
Message-ID: <CAHd-oW5gqs1uG5L4=JaT6Jzs58StE1WO0goPJE2atumbyC3Wow@mail.gmail.com>
URL: https://gitlist.dev/e/CAHd-oW5gqs1uG5L4%3DJaT6Jzs58StE1WO0goPJE2atumbyC3Wow%40mail.gmail.com
In-Reply-To: <CABPp-BH0d5WKz7bXLkFQGDBKXbd0tccS_+1_iNc1Wqr93h+KaQ@mail.gmail.com>

```
On Tue, Jun 2, 2020 at 11:40 PM Elijah Newren <newren@gmail.com> wrote:
>
> On Sun, May 31, 2020 at 9:46 PM Matheus Tavares Bernardino
> <matheus.bernardino@usp.br> wrote:
> >
>
> Moving it to grep's manpage seems ideal to me.  grep's behavior should
> be defined in grep's manual.
>
> > sparse.restrictCmds::
> > See complete definition in linkgit:git-config[1]. In grep, the
> > restriction takes effect in three cases: with --cached; when a
> > commit-ish is given; when searching a working tree where some paths
> > excluded by the sparsity patterns are present (e.g. manually created
> > paths or not removed submodules).
>
> That looks more than a little confusing.  Could this definition be
> something more like "See base definition in linkgit:git-config[1].
> grep honors sparse.restrictCmds by limiting searches to the sparsity
> paths in three cases: when searching the working tree, when searching
> the index with --cached, or when searching a specified commit"

Yes, this looks better, thanks. I would only add a brief explanation
on what we mean by limiting the search in the working tree case. Since
the working tree should already contain only the sparse paths (in most
cases), I think this sentence may sound a little confusing without
some explanation. Even further, some users might expect that `git -c
sparse.restrictCmds=false grep $pattern` would restore the previous
behavior of falling back to the cache for non-present entries, which
is not true.

In particular, I would like to emphasize that the use for
`sparse.restrictCmds=false` in the working tree case, is for
situations like the one you described in [1]:

* uses sparse-checkout to remove a bunch of files/directories they
don't care about
* creates a new file that happens to have the same name as an
(unfortunately) generically worded filename that exists in the index
(but is marked SKIP_WORKTREE and had previously been removed)

In this situation, grep would ignore the said file by default, but
search it with `sparse.restrictCmds=false`.

So what do you think of the following:

sparse.restrictCmds::
See base definition in linkgit:git-config[1]. grep honors
sparse.restrictCmds by limiting searches to the sparsity paths in
three cases: when searching the working tree, when searching the index
with --cached, and when searching a specified commit. Note: when this
option is set to true (default), the working tree search will ignore
paths that are present despite not matching the sparsity patterns.
This can happen, for example, if you create a new file in a path that
was previously removed by git-sparse-checkout. Or if you don't
deinitialize a submodule that is excluded by the sparsity patterns
(thus remaining in the working copy, anyway).

[1]: https://lore.kernel.org/git/CABPp-BE+BL3Nq=Co=-kNB_wr=6gqX8zcGwa0ega_pGBpk6xYsg@mail.gmail.com/

```

## Elijah Newren, 2020-06-11 00:35

Subject: Re: [PATCH v3 5/5] config: add setting to ignore sparsity patterns in some cmds
Message-ID: <CABPp-BFJG7uFAZNidDPK2o7eHv-eYBsmcdnVxkOnKcZo7WzmFQ@mail.gmail.com>
URL: https://gitlist.dev/e/CABPp-BFJG7uFAZNidDPK2o7eHv-eYBsmcdnVxkOnKcZo7WzmFQ%40mail.gmail.com
In-Reply-To: <CAHd-oW5gqs1uG5L4=JaT6Jzs58StE1WO0goPJE2atumbyC3Wow@mail.gmail.com>

```
Hi Matheus,

On Wed, Jun 10, 2020 at 2:15 PM Matheus Tavares Bernardino
<matheus.bernardino@usp.br> wrote:
>
> On Tue, Jun 2, 2020 at 11:40 PM Elijah Newren <newren@gmail.com> wrote:
> >
> > On Sun, May 31, 2020 at 9:46 PM Matheus Tavares Bernardino
> > <matheus.bernardino@usp.br> wrote:
> > >
> >
> > Moving it to grep's manpage seems ideal to me.  grep's behavior should
> > be defined in grep's manual.
> >
> > > sparse.restrictCmds::
> > > See complete definition in linkgit:git-config[1]. In grep, the
> > > restriction takes effect in three cases: with --cached; when a
> > > commit-ish is given; when searching a working tree where some paths
> > > excluded by the sparsity patterns are present (e.g. manually created
> > > paths or not removed submodules).
> >
> > That looks more than a little confusing.  Could this definition be
> > something more like "See base definition in linkgit:git-config[1].
> > grep honors sparse.restrictCmds by limiting searches to the sparsity
> > paths in three cases: when searching the working tree, when searching
> > the index with --cached, or when searching a specified commit"
>
> Yes, this looks better, thanks. I would only add a brief explanation
> on what we mean by limiting the search in the working tree case.

Possibly, but I think it would be easy to go overboard here.

> Since
> the working tree should already contain only the sparse paths (in most
> cases), I think this sentence may sound a little confusing without
> some explanation.

That's an interesting flag.  I'm curious, though, would they be
confused by it, or would it just seem immediately obvious and almost
not worth mentioning?  In other words, would they think "Well, if you
use sparse-checkout to get just a subset of files checked out, it
totally makes sense that grep would be limited in that case.  Why do
they even need to mention it -- just for completeness, I guess?"

And even if not all users think that way, would a large percentage of
users around them think that way and point out the obviousness of the
docs?

If not, maybe we just add a "(obviously)" comment right after "working tree"?

> Even further, some users might expect that `git -c
> sparse.restrictCmds=false grep $pattern` would restore the previous
> behavior of falling back to the cache for non-present entries, which
> is not true.

10 years from now, I don't want our docs to consist of a long
explanation of all the bugs that existed in various ancient versions
of git and how modern behavior differs from each previous iteration.
There are times when it's worth calling out bugs in prior versions to
bring it to the attention of our users, but I don't see how this is
one of them.  The previous behavior was just outright buggy and
inconsistent, and from my viewpoint, was also a regression.  I think
it should have been reverted regardless of your series, though
skip_worktree stuff was dormant and went unused for a really long
time.

Also, this is a special area of git where focusing too much on
backward compatibility might actually be detrimental.  Backward
compatibility is a really good goal to keep in mind in general, but
the SKIP_WORKTREE usability was traditionally really, really bad -- so
much so that outright replacing was contemplated by its author[A], and
we placed a HUGE ALL CAPS DISCLAIMER in the documentation of
sparse-checkout about how users should expect the behavior of commands
to change[B].  So, unlike other areas of git, we should focus on
getting sparse-checkout behavior right more than on bug compatibility
with previous code and long migration stories.  Given the context of
such disclaimers and changes, the idea of trying to document those
changes makes me think that in the not too distant future we would
have the equivalent of the following humorous driving directions from
the era before smartphones: "To get to Joe's place, you turn right on
the first road after where Billy's Barn burned down 5 years ago..."
(when the burned Barn was cleared out 4 years ago and there's no
indication of where it once was)

[A] https://lore.kernel.org/git/CABPp-BGE-m_UFfUt_moXG-YR=ZW8hMzMwraD7fkFV-+sEHw36w@mail.gmail.com/
[B] https://git-scm.com/docs/git-sparse-checkout#_description

> In particular, I would like to emphasize that the use for
> `sparse.restrictCmds=false` in the working tree case, is for
> situations like the one you described in [1]:
>
> * uses sparse-checkout to remove a bunch of files/directories they
> don't care about
> * creates a new file that happens to have the same name as an
> (unfortunately) generically worded filename that exists in the index
> (but is marked SKIP_WORKTREE and had previously been removed)
>
> In this situation, grep would ignore the said file by default, but
> search it with `sparse.restrictCmds=false`.

I think this is such a weird and unusual case that I'm not sure it
merits mentioning in the docs.

But if others disagree and think this case is worth mentioning in the
docs, then it shouldn't just be mentioned in "git grep".  All affected
manpages should be updated to discuss how they handle this obscure
corner case.  For example, `git diff` and `git status` just ignore
these files and do not print out any information about them.  So it's
kind of like these files are ignored...but even `git status --ignored`
won't show anything about such files.

Anyway, I think this is a pretty obscure case whose discussion would
dilute the value of the manual in teaching people the basics of
commands.

> So what do you think of the following:
>
> sparse.restrictCmds::
> See base definition in linkgit:git-config[1]. grep honors
> sparse.restrictCmds by limiting searches to the sparsity paths in
> three cases: when searching the working tree, when searching the index
> with --cached, and when searching a specified commit.

Good up to here.  I think I'd like to use just this text as-is (or
maybe with the "(obviously)" addition) and then see if we get feedback
that we need clarifications, because I'm worried our attempts at
clarifying might backfire.  For example...

> Note: when this
> option is set to true (default), the working tree search will ignore
> paths that are present despite not matching the sparsity patterns.

You've run into the same problem Stolee and I did by trying to provide
details about one case, but overlooking others.  ;-)  This "Note:"
statement is not correct; there's a couple cases it gets wrong:

merge/rebase/cherry-pick can unset the SKIP_WORKTREE bit even for
paths that do not match the sparsity patterns in order to be able to
materialize a file and show conflicts.  In fact, they are allowed to
unset the bit for other files and materialize them too (see
https://lore.kernel.org/git/xmqqbmb1a7ga.fsf@gitster-ct.c.googlers.com/).
Such paths, despite not matching the sparsity patterns, will not have
the SKIP_WORKTREE bit set.  And it is the SKIP_WORKTREE bit, rather
than the sparsity patterns, that git-grep uses for deciding which
files in the working tree to search.

Also, if someone runs sparse-checkout init/set, and sparse-checkout
would normally remove some file but notices that the file has local
modifications, then sparse-checkout will avoid removing the file AND
will avoid setting the SKIP_WORKTREE bit on that file.  See commit
681c637b4a ("unpack-trees: failure to set SKIP_WORKTREE bits always
just a warning", 2020-03-27)

> This can happen, for example, if you create a new file in a path that
> was previously removed by git-sparse-checkout.

This is that obscure corner case discussed above.

> Or if you don't
> deinitialize a submodule that is excluded by the sparsity patterns
> (thus remaining in the working copy, anyway).

This case requires more thought.  If a submodule doesn't match the
sparsity patterns, we already said elsewhere that sparse-checkout
should not remove the submodule (since doing so would risk data loss).
But do we set the SKIP_WORKTREE bit for it?  Generally,
sparse-checkout avoids removing files with modifications, and if it
doesn't remove them it also doesn't set the SKIP_WORKTREE bit.  For
consistency, should sparse-checkout not set SKIP_WORKTREE for
initialized submodules?

If we don't set the SKIP_WORKTREE bit for initialized submodules, then
we don't actually have a second different case to mention here.

Granted, that's more an issue for `sparse-checkout` than `grep`.


Hope that all helps.  Let me know if it doesn't, if you disagree with
any parts, or some parts aren't clear.
Elijah

```

## Matheus Tavares, 2020-06-12 15:44

Subject: [PATCH v4 0/6] grep: honor sparse checkout and add option to ignore it
Message-ID: <cover.1591974940.git.matheus.bernardino@usp.br>
URL: https://gitlist.dev/e/cover.1591974940.git.matheus.bernardino%40usp.br
In-Reply-To: <cover.1590627264.git.matheus.bernardino@usp.br>

```
This series makes git-grep restrict its output to the present sparsity
patterns. A new global option is added to toggle this behavior in grep
and hopefully more commands in the future.

Main changes since v3:

Patch 2:
- Reworded commit message for clarity.

Patch 3 and 4:
- Split into two patches. The first one contains the changes to easily
  accommodate new options in t/helper/test-config; the second adds
  --submodule=path.

Patch 4:
- Removed the section "Such scenario might not be needed now..." from
  the commit message. This was not true as we already have other
  submodule configs, even in git-grep itself, which should be considered
  when recursing into submodules.  And this should happen for both the
  local scope and worktree scope of the submodules configs.

Patch 5:
- Reworded commit message as suggested by Elijah [1].
- Fixed spelling errors in t7817 (as also pointed in [1]).
- Added test to ensure grep searches unmerged files despite not matching
  the sparsity patterns.
- Renamed builtin/grep.c:in_sparse_checkout() to
  path_in_sparse_checkout() for clarity.

Patch 6:
- Fixed typos and spelling errors.
- Removed unnecessary new line in git.c.
- Included "sparse-checkout.h" in git.c to avoid Sparse error as Ramsay
  Jones pointed out. And moved opt_restrict_to_sparse_paths to
  sparse-checkout.c.
- Moved information about how grep honors sparse.restrictCmds to grep's
  man page.

[1]: https://lore.kernel.org/git/CABPp-BFsCPPNOZ92JQRJeGyNd0e-TCW-LcLyr0i_+VSQJP+GCg@mail.gmail.com/

CI: https://github.com/matheustavares/git/actions/runs/133459296

Matheus Tavares (6):
  doc: grep: unify info on configuration variables
  t/helper/test-config: return exit codes consistently
  t/helper/test-config: facilitate addition of new cli options
  config: correctly read worktree configs in submodules
  grep: honor sparse checkout patterns
  config: add setting to ignore sparsity patterns in some cmds

 Documentation/config.txt               |   2 +
 Documentation/config/grep.txt          |  18 +-
 Documentation/config/sparse.txt        |  20 ++
 Documentation/git-grep.txt             |  36 +--
 Documentation/git.txt                  |   4 +
 Makefile                               |   1 +
 builtin/grep.c                         | 134 ++++++++++-
 config.c                               |  21 +-
 contrib/completion/git-completion.bash |   2 +
 git.c                                  |   5 +
 sparse-checkout.c                      |  18 ++
 sparse-checkout.h                      |  11 +
 t/helper/test-config.c                 | 183 +++++++++-----
 t/t2404-worktree-config.sh             |  16 ++
 t/t7011-skip-worktree-reading.sh       |   9 -
 t/t7817-grep-sparse-checkout.sh        | 321 +++++++++++++++++++++++++
 t/t9902-completion.sh                  |   4 +-
 17 files changed, 687 insertions(+), 118 deletions(-)
 create mode 100644 Documentation/config/sparse.txt
 create mode 100644 sparse-checkout.c
 create mode 100644 sparse-checkout.h
 create mode 100755 t/t7817-grep-sparse-checkout.sh

Range-diff against v3:
1:  86602034c1 = 1:  99cf2124f3 doc: grep: unify info on configuration variables
2:  e5b689aaad ! 2:  85c429ac69 t/helper/test-config: return exit codes consistently
    @@ Commit message
         different codes, to reflect the status of the requested operations.
         These codes are sometimes checked in the tests, but not all of the codes
         are returned consistently by the helper: 1 will usually refer to a
    -    "value not found", but usage errors can also return 1 or 128. The latter
    -    is also expected on errors within the configset functions. These
    +    "value not found", but usage errors can also return 1 or 128. Moreover,
    +    128 is also expected on errors within the configset functions. These
         inconsistent uses of the exit codes can lead to false positives in the
    -    tests. Although all tests that currently check the helper's exit code,
    -    on errors, do also check the output, it's still better to standardize
    -    the exit codes and avoid future problems in new tests. While we are
    -    here, let's also check that we have the expected argc for
    +    tests. Although all tests which expect errors and check the helper's
    +    exit code currently also check the output, it's still better to
    +    standardize the exit codes and avoid future problems in new tests.
    +    While we are here, let's also check that we have the expected argc for
         configset_get_value and configset_get_value_multi, before trying to use
         argv.
     
-:  ---------- > 3:  e9eaaecccc t/helper/test-config: facilitate addition of new cli options
3:  0d2fd01305 ! 4:  6402c96807 config: correctly read worktree configs in submodules
    @@ Commit message
         to make the path to the file. Furthermore, it also checks that
         extensions.worktreeConfig is set through the
         repository_format_worktree_config variable, which refers to
    -    the_repository only. Thus, when a submodule has worktree settings, a
    -    command executed in the superproject that recurses into the submodule
    -    won't find the said settings.
    +    the_repository only. Thus, when a submodule has worktree-specific
    +    settings, a command executed in the superproject that recurses into the
    +    submodule won't find the said settings.
     
    -    Such a scenario might not be needed now, but it will be in the following
    -    patch. git-grep will learn to honor sparse checkouts and, when running
    -    with --recurse-submodules, the submodule's sparse checkout settings must
    -    be loaded. As these settings are stored in the config.worktree file,
    -    they would be ignored without this patch. So let's fix this by reading
    -    the right config.worktree file and extensions.worktreeConfig setting,
    -    based on the git_dir and commondir paths given to
    -    do_git_config_sequence(). Also add a test to avoid any regressions.
    +    This will be especially important in the next patch: git-grep will learn
    +    to honor sparse checkouts and, when running with --recurse-submodules,
    +    the submodule's sparse checkout settings must be loaded. As these
    +    settings are stored in the config.worktree file, they would be ignored
    +    without this patch. So let's fix this by reading the right
    +    config.worktree file and extensions.worktreeConfig setting, based on the
    +    git_dir and commondir paths given to do_git_config_sequence(). Also
    +    add a test to avoid any regressions.
     
         Signed-off-by: Matheus Tavares <matheus.bernardino@usp.br>
     
    @@ t/helper/test-config.c
       * get_value -> prints the value with highest priority for the entered key
       *
     @@ t/helper/test-config.c: int cmd__config(int argc, const char **argv)
    - 	int i, val;
    - 	const char *v;
      	const struct string_list *strptr;
    --	struct config_set cs;
    -+	struct config_set cs = { .hash_initialized = 0 };
    + 	struct config_set cs = { .hash_initialized = 0 };
      	enum test_config_exit_code ret = TC_SUCCESS;
     +	struct repository *repo = the_repository;
     +	const char *subrepo_path = NULL;
    -+
    -+	argc--; /* skip over "config" */
    -+	argv++;
    -+
    -+	if (argc == 0)
    -+		goto print_usage_error;
    -+
    + 
    + 	argc--; /* skip over "config" */
    + 	argv++;
    +@@ t/helper/test-config.c: int cmd__config(int argc, const char **argv)
    + 	if (argc == 0)
    + 		goto print_usage_error;
    + 
     +	if (skip_prefix(*argv, "--submodule=", &subrepo_path)) {
     +		argc--;
     +		argv++;
     +		if (argc == 0)
     +			goto print_usage_error;
     +	}
    - 
    --	if (argc == 3 && !strcmp(argv[1], "read_early_config")) {
    --		read_early_config(early_config_cb, (void *)argv[2]);
    -+	if (argc == 2 && !strcmp(argv[0], "read_early_config")) {
    ++
    + 	if (argc == 2 && !strcmp(argv[0], "read_early_config")) {
     +		if (subrepo_path) {
     +			fprintf(stderr, "Cannot use --submodule with read_early_config\n");
     +			return TC_USAGE_ERROR;
     +		}
    -+		read_early_config(early_config_cb, (void *)argv[1]);
    + 		read_early_config(early_config_cb, (void *)argv[1]);
      		return TC_SUCCESS;
      	}
    - 
    +@@ t/helper/test-config.c: int cmd__config(int argc, const char **argv)
      	setup_git_directory();
    --
      	git_configset_init(&cs);
      
    --	if (argc < 2)
    --		goto print_usage_error;
     +	if (subrepo_path) {
     +		const struct submodule *sub;
     +		struct repository *subrepo = xcalloc(1, sizeof(*repo));
    @@ t/helper/test-config.c: int cmd__config(int argc, const char **argv)
     +		}
     +		repo = subrepo;
     +	}
    - 
    --	if (argc == 3 && !strcmp(argv[1], "get_value")) {
    --		if (!git_config_get_value(argv[2], &v)) {
    -+	if (argc == 2 && !strcmp(argv[0], "get_value")) {
    ++
    + 	if (argc == 2 && !strcmp(argv[0], "get_value")) {
    +-		if (!git_config_get_value(argv[1], &v)) {
     +		if (!repo_config_get_value(repo, argv[1], &v)) {
      			if (!v)
      				printf("(NULL)\n");
      			else
    - 				printf("%s\n", v);
    - 		} else {
    --			printf("Value not found for \"%s\"\n", argv[2]);
    -+			printf("Value not found for \"%s\"\n", argv[1]);
    +@@ t/helper/test-config.c: int cmd__config(int argc, const char **argv)
      			ret = TC_VALUE_NOT_FOUND;
      		}
    --	} else if (argc == 3 && !strcmp(argv[1], "get_value_multi")) {
    --		strptr = git_config_get_value_multi(argv[2]);
    -+	} else if (argc == 2 && !strcmp(argv[0], "get_value_multi")) {
    + 	} else if (argc == 2 && !strcmp(argv[0], "get_value_multi")) {
    +-		strptr = git_config_get_value_multi(argv[1]);
     +		strptr = repo_config_get_value_multi(repo, argv[1]);
      		if (strptr) {
      			for (i = 0; i < strptr->nr; i++) {
      				v = strptr->items[i].string;
     @@ t/helper/test-config.c: int cmd__config(int argc, const char **argv)
    - 					printf("%s\n", v);
    - 			}
    - 		} else {
    --			printf("Value not found for \"%s\"\n", argv[2]);
    -+			printf("Value not found for \"%s\"\n", argv[1]);
      			ret = TC_VALUE_NOT_FOUND;
      		}
    --	} else if (argc == 3 && !strcmp(argv[1], "get_int")) {
    --		if (!git_config_get_int(argv[2], &val)) {
    -+	} else if (argc == 2 && !strcmp(argv[0], "get_int")) {
    + 	} else if (argc == 2 && !strcmp(argv[0], "get_int")) {
    +-		if (!git_config_get_int(argv[1], &val)) {
     +		if (!repo_config_get_int(repo, argv[1], &val)) {
      			printf("%d\n", val);
      		} else {
    --			printf("Value not found for \"%s\"\n", argv[2]);
    -+			printf("Value not found for \"%s\"\n", argv[1]);
    + 			printf("Value not found for \"%s\"\n", argv[1]);
      			ret = TC_VALUE_NOT_FOUND;
      		}
    --	} else if (argc == 3 && !strcmp(argv[1], "get_bool")) {
    --		if (!git_config_get_bool(argv[2], &val)) {
    -+	} else if (argc == 2 && !strcmp(argv[0], "get_bool")) {
    + 	} else if (argc == 2 && !strcmp(argv[0], "get_bool")) {
    +-		if (!git_config_get_bool(argv[1], &val)) {
     +		if (!repo_config_get_bool(repo, argv[1], &val)) {
      			printf("%d\n", val);
      		} else {
    --			printf("Value not found for \"%s\"\n", argv[2]);
     +
    -+			printf("Value not found for \"%s\"\n", argv[1]);
    + 			printf("Value not found for \"%s\"\n", argv[1]);
      			ret = TC_VALUE_NOT_FOUND;
      		}
    --	} else if (argc == 3 && !strcmp(argv[1], "get_string")) {
    --		if (!git_config_get_string_const(argv[2], &v)) {
    -+	} else if (argc == 2 && !strcmp(argv[0], "get_string")) {
    + 	} else if (argc == 2 && !strcmp(argv[0], "get_string")) {
    +-		if (!git_config_get_string_const(argv[1], &v)) {
     +		if (!repo_config_get_string_const(repo, argv[1], &v)) {
      			printf("%s\n", v);
      		} else {
    --			printf("Value not found for \"%s\"\n", argv[2]);
    -+			printf("Value not found for \"%s\"\n", argv[1]);
    + 			printf("Value not found for \"%s\"\n", argv[1]);
      			ret = TC_VALUE_NOT_FOUND;
      		}
    --	} else if (argc >= 3 && !strcmp(argv[1], "configset_get_value")) {
    --		for (i = 3; i < argc; i++) {
    -+	} else if (argc >= 2 && !strcmp(argv[0], "configset_get_value")) {
    + 	} else if (argc >= 2 && !strcmp(argv[0], "configset_get_value")) {
     +		if (subrepo_path) {
     +			fprintf(stderr, "Cannot use --submodule with configset_get_value\n");
     +			ret = TC_USAGE_ERROR;
     +			goto out;
     +		}
    -+		for (i = 2; i < argc; i++) {
    + 		for (i = 2; i < argc; i++) {
      			int err;
      			if ((err = git_configset_add_file(&cs, argv[i]))) {
    - 				fprintf(stderr, "Error (%d) reading configuration file %s.\n", err, argv[i]);
     @@ t/helper/test-config.c: int cmd__config(int argc, const char **argv)
    - 				goto out;
    - 			}
    - 		}
    --		if (!git_configset_get_value(&cs, argv[2], &v)) {
    -+		if (!git_configset_get_value(&cs, argv[1], &v)) {
    - 			if (!v)
    - 				printf("(NULL)\n");
    - 			else
    - 				printf("%s\n", v);
    - 		} else {
    --			printf("Value not found for \"%s\"\n", argv[2]);
    -+			printf("Value not found for \"%s\"\n", argv[1]);
      			ret = TC_VALUE_NOT_FOUND;
      		}
    --	} else if (argc >= 3 && !strcmp(argv[1], "configset_get_value_multi")) {
    --		for (i = 3; i < argc; i++) {
    -+	} else if (argc >= 2 && !strcmp(argv[0], "configset_get_value_multi")) {
    + 	} else if (argc >= 2 && !strcmp(argv[0], "configset_get_value_multi")) {
     +		if (subrepo_path) {
     +			fprintf(stderr, "Cannot use --submodule with configset_get_value_multi\n");
     +			ret = TC_USAGE_ERROR;
     +			goto out;
     +		}
    -+		for (i = 2; i < argc; i++) {
    + 		for (i = 2; i < argc; i++) {
      			int err;
      			if ((err = git_configset_add_file(&cs, argv[i]))) {
    - 				fprintf(stderr, "Error (%d) reading configuration file %s.\n", err, argv[i]);
     @@ t/helper/test-config.c: int cmd__config(int argc, const char **argv)
    - 				goto out;
    - 			}
    - 		}
    --		strptr = git_configset_get_value_multi(&cs, argv[2]);
    -+		strptr = git_configset_get_value_multi(&cs, argv[1]);
    - 		if (strptr) {
    - 			for (i = 0; i < strptr->nr; i++) {
    - 				v = strptr->items[i].string;
    -@@ t/helper/test-config.c: int cmd__config(int argc, const char **argv)
    - 					printf("%s\n", v);
    - 			}
    - 		} else {
    --			printf("Value not found for \"%s\"\n", argv[2]);
    -+			printf("Value not found for \"%s\"\n", argv[1]);
      			ret = TC_VALUE_NOT_FOUND;
      		}
    --	} else if (!strcmp(argv[1], "iterate")) {
    + 	} else if (!strcmp(argv[0], "iterate")) {
     -		git_config(iterate_cb, NULL);
    -+	} else if (!strcmp(argv[0], "iterate")) {
     +		repo_config(repo, iterate_cb, NULL);
      	} else {
      print_usage_error:
4:  3b819a8d52 ! 5:  4d2916eb99 grep: honor sparse checkout patterns
    @@ Commit message
     
         One of the main uses for a sparse checkout is to allow users to focus on
         the subset of files in a repository in which they are interested. But
    -    git-grep currently ignores the sparsity patterns and report all matches
    +    git-grep currently ignores the sparsity patterns and reports all matches
         found outside this subset, which kind of goes in the opposite direction.
    -    Let's fix that, making it honor the sparsity boundaries for every
    -    grepping case where this is relevant:
    +    There are some use cases for ignoring the sparsity patterns and the next
    +    commit will add an option to obtain this behavior, but here we start by
    +    making grep honor the sparsity boundaries in every case where this is
    +    relevant:
     
         - git grep in worktree
         - git grep --cached
         - git grep $REVISION
     
    -    For the worktree case, we will not grep paths that have the
    -    SKIP_WORKTREE bit set, even if they are present for some reason (e.g.
    -    manually created after `git sparse-checkout init`). But the next patch
    -    will add an option to do so. (See 'Note' below.)
    +    For the worktree and cached cases, we iterate over paths without the
    +    SKIP_WORKTREE bit set, and limit our searches to these paths. For the
    +    $REVISION case, we limit the paths we search to those that match the
    +    sparsity patterns. (We do not check the SKIP_WORKTREE bit for the
    +    $REVISION case, because $REVISION may contain paths that do not exist in
    +    HEAD and thus for which we have no SKIP_WORKTREE bit to consult. The
    +    sparsity patterns tell us how the SKIP_WORKTREE bit would be set if we
    +    were to check out $REVISION, so we consult those. Also, we don't use the
    +    sparsity patterns with the worktree or cached cases, both because we
    +    have a bit we can check directly and more efficiently, and because
    +    unmerged entries from a merge or a rebase could cause more files to
    +    temporarily be present than the sparsity patterns would normally
    +    select.)
     
    -    For `git grep $REVISION`, we will choose to honor the sparsity patterns
    -    only when $REVISION is a commit-ish object. The reason is that, for a
    -    tree, we don't know whether it represents the root of a repository or a
    -    subtree. So we wouldn't be able to correctly match it against the
    -    sparsity patterns. E.g. suppose we have a repository with these two
    -    sparsity rules: "/*" and "!/a"; and the following structure:
    -
    -    /
    -    | - a (file)
    -    | - d (dir)
    -        | - a (file)
    -
    -    If `git grep $REVISION` were to honor the sparsity patterns for every
    -    object type, when grepping the /d tree, we would wrongly ignore the /d/a
    -    file. This happens because we wouldn't know it resides in /d and
    -    therefore it would wrongly match the pattern "!/a". Furthermore, for a
    -    search in a blob object, we wouldn't even have a path to check the
    -    patterns against. So, let's ignore the sparsity patterns when grepping
    -    non-commit-ish objects.
    -
    -    Note: The behavior introduced in this patch is what some users have
    -    reported[1] that they would like by default. But the old behavior is
    -    still desirable for some use cases. Therefore, the next patch will add
    -    an option to allow restoring it when needed.
    -
    -    [1]: https://lore.kernel.org/git/CABPp-BGuFhDwWZBRaD3nA8ui46wor-4=Ha1G1oApsfF8KNpfGQ@mail.gmail.com/
    +    Note that there is a special case here: `git grep $TREE`. In this case,
    +    we cannot know whether $TREE corresponds to the root of the repository
    +    or some sub-tree, and thus there is no way for us to know which sparsity
    +    patterns, if any, apply. So the $TREE case will not use sparsity
    +    patterns or any SKIP_WORKTREE bits and will instead always search all
    +    files within the $TREE.
     
         Signed-off-by: Matheus Tavares <matheus.bernardino@usp.br>
     
    @@ builtin/grep.c: static int grep_cache(struct grep_opt *opt,
     +	return patterns;
     +}
     +
    -+static int in_sparse_checkout(struct strbuf *path, int prefix_len,
    -+			      unsigned int entry_mode,
    -+			      struct index_state *istate,
    -+			      struct pattern_list *sparsity,
    -+			      enum pattern_match_result parent_match,
    -+			      enum pattern_match_result *match)
    ++static int path_in_sparse_checkout(struct strbuf *path, int prefix_len,
    ++				   unsigned int entry_mode,
    ++				   struct index_state *istate,
    ++				   struct pattern_list *sparsity,
    ++				   enum pattern_match_result parent_match,
    ++				   enum pattern_match_result *match)
     +{
     +	int dtype = DT_UNKNOWN;
     +	int is_dir = S_ISDIR(entry_mode);
    @@ builtin/grep.c: static int grep_tree(struct grep_opt *opt, const struct pathspec
     +			struct strbuf path = STRBUF_INIT;
     +			strbuf_addstr(&path, base->buf + tn_len);
     +
    -+			if (!in_sparse_checkout(&path, old_baselen - tn_len,
    -+						entry.mode, repo->index,
    -+						sparsity, default_sparsity_match,
    -+						&sparsity_match)) {
    ++			if (!path_in_sparse_checkout(&path, old_baselen - tn_len,
    ++						     entry.mode, repo->index,
    ++						     sparsity, default_sparsity_match,
    ++						     &sparsity_match)) {
     +				strbuf_setlen(base, old_baselen);
     +				continue;
     +			}
    @@ t/t7817-grep-sparse-checkout.sh (new)
     +`-- sub2
     +    `-- a
     +
    -+Where . has non-cone mode sparsity patterns, sub is a submodule with cone mode
    -+sparsity patterns and sub2 is a submodule that is excluded by the superproject
    -+sparsity patterns. The resulting sparse checkout should leave the following
    -+structure on the working tree:
    ++Where the outer repository has non-cone mode sparsity patterns, sub is a
    ++submodule with cone mode sparsity patterns and sub2 is a submodule that is
    ++excluded by the superproject sparsity patterns. The resulting sparse checkout
    ++should leave the following structure in the working tree:
     +
     +.
     +|-- a
    @@ t/t7817-grep-sparse-checkout.sh (new)
     +	test_path_is_file sub2/a
     +'
     +
    -+# The test bellow checks a special case: the sparsity patterns exclude '/b'
    -+# and sparse checkout is enable, but the path exists on the working tree (e.g.
    ++# The test below checks a special case: the sparsity patterns exclude '/b'
    ++# and sparse checkout is enabled, but the path exists in the working tree (e.g.
     +# manually created after `git sparse-checkout init`). In this case, grep should
     +# skip it.
     +test_expect_success 'grep in working tree should honor sparse checkout' '
    @@ t/t7817-grep-sparse-checkout.sh (new)
     +	test_cmp expect actual
     +'
     +
    ++test_expect_success 'grep unmerged file despite not matching sparsity patterns' '
    ++	cat >expect <<-EOF &&
    ++	b:modified-b-in-branchX
    ++	b:modified-b-in-branchY
    ++	EOF
    ++	test_when_finished "test_might_fail git merge --abort && \
    ++			    git checkout master" &&
    ++
    ++	git sparse-checkout disable &&
    ++	git checkout -b branchY master &&
    ++	test_commit modified-b-in-branchY b &&
    ++	git checkout -b branchX master &&
    ++	test_commit modified-b-in-branchX b &&
    ++
    ++	git sparse-checkout init &&
    ++	test_path_is_missing b &&
    ++	test_must_fail git merge branchY &&
    ++	git grep "modified-b" >actual &&
    ++	test_cmp expect actual
    ++'
    ++
     +test_expect_success 'grep --cached should honor sparse checkout' '
     +	cat >expect <<-EOF &&
     +	a:text
5:  02990a6fa1 ! 6:  4547718b60 config: add setting to ignore sparsity patterns in some cmds
    @@ Documentation/config.txt: include::config/sequencer.txt[]
      
      include::config/ssh.txt[]
     
    + ## Documentation/config/grep.txt ##
    +@@ Documentation/config/grep.txt: grep.fullName::
    + grep.fallbackToNoIndex::
    + 	If set to true, fall back to git grep --no-index if git grep
    + 	is executed outside of a git repository.  Defaults to false.
    ++
    ++ifdef::git-grep[]
    ++sparse.restrictCmds::
    ++	See base definition in linkgit:git-config[1]. grep honors
    ++	sparse.restrictCmds by limiting searches to the sparsity paths in three
    ++	cases: when searching the working tree, when searching the index with
    ++	--cached, and when searching a specified commit.
    ++endif::git-grep[]
    +
      ## Documentation/config/sparse.txt (new) ##
     @@
     +sparse.restrictCmds::
    @@ Documentation/config/sparse.txt (new)
     +to the paths specified by the sparsity patterns, or to the intersection of
     +those paths and any (like `*.c`) that the user might also specify on the
     +command line. When false, the affected commands will work on full trees,
    -+ignoring the sparsity patterns. For now, only git-grep honors this setting. In
    -+this command, the restriction takes effect in three cases: with --cached; when
    -+a commit-ish is given; when searching a working tree where some paths excluded
    -+by the sparsity patterns are present (e.g. manually created paths or not
    -+removed submodules).
    ++ignoring the sparsity patterns. For now, only git-grep honors this setting.
     ++
     +Note: commands which export, integrity check, or create history will always
     +operate on full trees (e.g. fast-export, format-patch, fsck, commit, etc.),
    -+unaffected by any sparsity patterns. Also, writting commands such as
    ++unaffected by any sparsity patterns. Also, writing commands such as
     +sparse-checkout and read-tree will not be affected by this configuration.
     
    - ## Documentation/git-grep.txt ##
    -@@ Documentation/git-grep.txt: characters.  An empty string as search expression matches all lines.
    - CONFIGURATION
    - -------------
    - 
    -+git-grep honors the sparse.restrictCmds setting. See its definition in
    -+linkgit:git-config[1].
    -+
    - :git-grep: 1
    - include::config/grep.txt[]
    - 
    -
      ## Documentation/git.txt ##
     @@ Documentation/git.txt: If you just want to run git as if it was started in `<path>` then use
      	Do not perform optional operations that require locks. This is
    @@ contrib/completion/git-completion.bash: __git_main ()
      		*)
     
      ## git.c ##
    -@@ git.c: const char git_more_info_string[] =
    - 	   "See 'git help git' for an overview of the system.");
    - 
    - static int use_pager = -1;
    -+int opt_restrict_to_sparse_paths = -1;
    - 
    - static void list_builtins(struct string_list *list, unsigned int exclude_option);
    +@@
    + #include "run-command.h"
    + #include "alias.h"
    + #include "shallow.h"
    ++#include "sparse-checkout.h"
      
    + #define RUN_SETUP		(1<<0)
    + #define RUN_SETUP_GENTLY	(1<<1)
     @@ git.c: static int handle_options(const char ***argv, int *argc, int *envchanged)
      			} else {
      				exit(list_cmds(cmd));
    @@ git.c: static int handle_options(const char ***argv, int *argc, int *envchanged)
      		} else {
      			fprintf(stderr, _("unknown option: %s\n"), cmd);
      			usage(git_usage_string);
    -@@ git.c: static int handle_options(const char ***argv, int *argc, int *envchanged)
    - 		(*argv)++;
    - 		(*argc)--;
    - 	}
    -+
    - 	return (*argv) - orig_argv;
    - }
    - 
     
      ## sparse-checkout.c (new) ##
     @@
    @@ sparse-checkout.c (new)
     +#include "config.h"
     +#include "sparse-checkout.h"
     +
    ++int opt_restrict_to_sparse_paths = -1;
    ++
     +int restrict_to_sparse_paths(struct repository *repo)
     +{
     +	int ret;
    @@ sparse-checkout.h (new)
     +
     +struct repository;
     +
    -+extern int opt_restrict_to_sparse_paths; /* from git.c */
    ++extern int opt_restrict_to_sparse_paths;
     +
     +/* Whether or not cmds should restrict behavior on sparse paths, in this repo */
     +int restrict_to_sparse_paths(struct repository *repo);
    @@ t/t7817-grep-sparse-checkout.sh: test_expect_success 'setup' '
      	test_path_is_file sub2/a
      '
      
    --# The test bellow checks a special case: the sparsity patterns exclude '/b'
    -+# The two tests bellow check a special case: the sparsity patterns exclude '/b'
    - # and sparse checkout is enable, but the path exists on the working tree (e.g.
    +-# The test below checks a special case: the sparsity patterns exclude '/b'
    ++# The two tests below check a special case: the sparsity patterns exclude '/b'
    + # and sparse checkout is enabled, but the path exists in the working tree (e.g.
      # manually created after `git sparse-checkout init`). In this case, grep should
     -# skip it.
     +# skip the file by default, but not with --no-restrict-to-sparse-paths.
    @@ t/t7817-grep-sparse-checkout.sh: test_expect_success 'grep in working tree shoul
     +	test_cmp expect actual
     +'
      
    - test_expect_success 'grep --cached should honor sparse checkout' '
    + test_expect_success 'grep unmerged file despite not matching sparsity patterns' '
      	cat >expect <<-EOF &&
     @@ t/t7817-grep-sparse-checkout.sh: test_expect_success 'grep <tree-ish> should ignore sparsity patterns' '
      '
    @@ t/t7817-grep-sparse-checkout.sh: test_expect_success 'grep --recurse-submodules
     +	'
     +done
     +
    -+test_expect_success 'grep --recurse-submodules --cached \w --no-restrict-to-sparse-paths' '
    ++test_expect_success 'grep --recurse-submodules --cached w/ --no-restrict-to-sparse-paths' '
     +	cat >expect <<-EOF &&
     +	a:text
     +	b:text
    @@ t/t7817-grep-sparse-checkout.sh: test_expect_success 'grep --recurse-submodules
     +	test_cmp expect actual
     +'
     +
    -+test_expect_success 'grep --recurse-submodules <commit-ish> \w --no-restrict-to-sparse-paths' '
    ++test_expect_success 'grep --recurse-submodules <commit-ish> w/ --no-restrict-to-sparse-paths' '
     +	commit=$(git rev-parse HEAD) &&
     +	cat >expect_commit <<-EOF &&
     +	$commit:a:text
-- 
2.26.2


```

## Matheus Tavares, 2020-06-12 15:45

Subject: [PATCH v4 2/6] t/helper/test-config: return exit codes consistently
Message-ID: <85c429ac6924fefcd6b93ccefbdd52903929bb02.1591974940.git.matheus.bernardino@usp.br>
URL: https://gitlist.dev/e/85c429ac6924fefcd6b93ccefbdd52903929bb02.1591974940.git.matheus.bernardino%40usp.br
In-Reply-To: <cover.1591974940.git.matheus.bernardino@usp.br>

```
The test-config helper may exit with a variety of at least four
different codes, to reflect the status of the requested operations.
These codes are sometimes checked in the tests, but not all of the codes
are returned consistently by the helper: 1 will usually refer to a
"value not found", but usage errors can also return 1 or 128. Moreover,
128 is also expected on errors within the configset functions. These
inconsistent uses of the exit codes can lead to false positives in the
tests. Although all tests which expect errors and check the helper's
exit code currently also check the output, it's still better to
standardize the exit codes and avoid future problems in new tests.
While we are here, let's also check that we have the expected argc for
configset_get_value and configset_get_value_multi, before trying to use
argv.

Note: this change is implemented with the unification of the exit
labels. This might seem unnecessary, for now, but it will benefit the
next patch, which will increase the cleanup section.

Signed-off-by: Matheus Tavares <matheus.bernardino@usp.br>
---
 t/helper/test-config.c | 76 ++++++++++++++++++++++--------------------
 1 file changed, 40 insertions(+), 36 deletions(-)

diff --git a/t/helper/test-config.c b/t/helper/test-config.c
index 234c722b48..1c8e965840 100644
--- a/t/helper/test-config.c
+++ b/t/helper/test-config.c
@@ -30,6 +30,14 @@
  * iterate -> iterate over all values using git_config(), and print some
  *            data for each
  *
+ * Exit codes:
+ *     0:   success
+ *     1:   value not found for the given config key
+ *     2:   config file path given as argument is inaccessible or doesn't exist
+ *     129: test-config usage error
+ *
+ * Note: tests may also expect 128 for die() calls in the config machinery.
+ *
  * Examples:
  *
  * To print the value with highest priority for key "foo.bAr Baz.rock":
@@ -64,35 +72,42 @@ static int early_config_cb(const char *var, const char *value, void *vdata)
 	return 0;
 }
 
+enum test_config_exit_code {
+	TC_SUCCESS = 0,
+	TC_VALUE_NOT_FOUND = 1,
+	TC_CONFIG_FILE_ERROR = 2,
+	TC_USAGE_ERROR = 129,
+};
+
 int cmd__config(int argc, const char **argv)
 {
 	int i, val;
 	const char *v;
 	const struct string_list *strptr;
 	struct config_set cs;
+	enum test_config_exit_code ret = TC_SUCCESS;
 
 	if (argc == 3 && !strcmp(argv[1], "read_early_config")) {
 		read_early_config(early_config_cb, (void *)argv[2]);
-		return 0;
+		return TC_SUCCESS;
 	}
 
 	setup_git_directory();
 
 	git_configset_init(&cs);
 
-	if (argc < 2) {
-		fprintf(stderr, "Please, provide a command name on the command-line\n");
-		goto exit1;
-	} else if (argc == 3 && !strcmp(argv[1], "get_value")) {
+	if (argc < 2)
+		goto print_usage_error;
+
+	if (argc == 3 && !strcmp(argv[1], "get_value")) {
 		if (!git_config_get_value(argv[2], &v)) {
 			if (!v)
 				printf("(NULL)\n");
 			else
 				printf("%s\n", v);
-			goto exit0;
 		} else {
 			printf("Value not found for \"%s\"\n", argv[2]);
-			goto exit1;
+			ret = TC_VALUE_NOT_FOUND;
 		}
 	} else if (argc == 3 && !strcmp(argv[1], "get_value_multi")) {
 		strptr = git_config_get_value_multi(argv[2]);
@@ -104,41 +119,38 @@ int cmd__config(int argc, const char **argv)
 				else
 					printf("%s\n", v);
 			}
-			goto exit0;
 		} else {
 			printf("Value not found for \"%s\"\n", argv[2]);
-			goto exit1;
+			ret = TC_VALUE_NOT_FOUND;
 		}
 	} else if (argc == 3 && !strcmp(argv[1], "get_int")) {
 		if (!git_config_get_int(argv[2], &val)) {
 			printf("%d\n", val);
-			goto exit0;
 		} else {
 			printf("Value not found for \"%s\"\n", argv[2]);
-			goto exit1;
+			ret = TC_VALUE_NOT_FOUND;
 		}
 	} else if (argc == 3 && !strcmp(argv[1], "get_bool")) {
 		if (!git_config_get_bool(argv[2], &val)) {
 			printf("%d\n", val);
-			goto exit0;
 		} else {
 			printf("Value not found for \"%s\"\n", argv[2]);
-			goto exit1;
+			ret = TC_VALUE_NOT_FOUND;
 		}
 	} else if (argc == 3 && !strcmp(argv[1], "get_string")) {
 		if (!git_config_get_string_const(argv[2], &v)) {
 			printf("%s\n", v);
-			goto exit0;
 		} else {
 			printf("Value not found for \"%s\"\n", argv[2]);
-			goto exit1;
+			ret = TC_VALUE_NOT_FOUND;
 		}
-	} else if (!strcmp(argv[1], "configset_get_value")) {
+	} else if (argc >= 3 && !strcmp(argv[1], "configset_get_value")) {
 		for (i = 3; i < argc; i++) {
 			int err;
 			if ((err = git_configset_add_file(&cs, argv[i]))) {
 				fprintf(stderr, "Error (%d) reading configuration file %s.\n", err, argv[i]);
-				goto exit2;
+				ret = TC_CONFIG_FILE_ERROR;
+				goto out;
 			}
 		}
 		if (!git_configset_get_value(&cs, argv[2], &v)) {
@@ -146,17 +158,17 @@ int cmd__config(int argc, const char **argv)
 				printf("(NULL)\n");
 			else
 				printf("%s\n", v);
-			goto exit0;
 		} else {
 			printf("Value not found for \"%s\"\n", argv[2]);
-			goto exit1;
+			ret = TC_VALUE_NOT_FOUND;
 		}
-	} else if (!strcmp(argv[1], "configset_get_value_multi")) {
+	} else if (argc >= 3 && !strcmp(argv[1], "configset_get_value_multi")) {
 		for (i = 3; i < argc; i++) {
 			int err;
 			if ((err = git_configset_add_file(&cs, argv[i]))) {
 				fprintf(stderr, "Error (%d) reading configuration file %s.\n", err, argv[i]);
-				goto exit2;
+				ret = TC_CONFIG_FILE_ERROR;
+				goto out;
 			}
 		}
 		strptr = git_configset_get_value_multi(&cs, argv[2]);
@@ -168,27 +180,19 @@ int cmd__config(int argc, const char **argv)
 				else
 					printf("%s\n", v);
 			}
-			goto exit0;
 		} else {
 			printf("Value not found for \"%s\"\n", argv[2]);
-			goto exit1;
+			ret = TC_VALUE_NOT_FOUND;
 		}
 	} else if (!strcmp(argv[1], "iterate")) {
 		git_config(iterate_cb, NULL);
-		goto exit0;
+	} else {
+print_usage_error:
+		fprintf(stderr, "Invalid syntax. Usage: test-tool config <cmd> [args]\n");
+		ret = TC_USAGE_ERROR;
 	}
 
-	die("%s: Please check the syntax and the function name", argv[0]);
-
-exit0:
-	git_configset_clear(&cs);
-	return 0;
-
-exit1:
-	git_configset_clear(&cs);
-	return 1;
-
-exit2:
+out:
 	git_configset_clear(&cs);
-	return 2;
+	return ret;
 }
-- 
2.26.2


```

## Matheus Tavares, 2020-06-12 15:44

Subject: [PATCH v4 1/6] doc: grep: unify info on configuration variables
Message-ID: <99cf2124f349a98b10fc603137e10d38c7ea533a.1591974940.git.matheus.bernardino@usp.br>
URL: https://gitlist.dev/e/99cf2124f349a98b10fc603137e10d38c7ea533a.1591974940.git.matheus.bernardino%40usp.br
In-Reply-To: <cover.1591974940.git.matheus.bernardino@usp.br>

```
Explanations about the configuration variables for git-grep are
duplicated in "Documentation/git-grep.txt" and
"Documentation/config/grep.txt", which can make maintenance difficult.
The first also contains a definition not present in the latter
(grep.fullName). To avoid problems like this, let's unify the
information in the second file and include it in the first.

Signed-off-by: Matheus Tavares <matheus.bernardino@usp.br>
---
 Documentation/config/grep.txt | 10 ++++++++--
 Documentation/git-grep.txt    | 36 ++++++-----------------------------
 2 files changed, 14 insertions(+), 32 deletions(-)

diff --git a/Documentation/config/grep.txt b/Documentation/config/grep.txt
index 44abe45a7c..dd51db38e1 100644
--- a/Documentation/config/grep.txt
+++ b/Documentation/config/grep.txt
@@ -16,8 +16,14 @@ grep.extendedRegexp::
 	other than 'default'.
 
 grep.threads::
-	Number of grep worker threads to use.
-	See `grep.threads` in linkgit:git-grep[1] for more information.
+	Number of grep worker threads to use. See `--threads`
+ifndef::git-grep[]
+	in linkgit:git-grep[1]
+endif::git-grep[]
+	for more information.
+
+grep.fullName::
+	If set to true, enable `--full-name` option by default.
 
 grep.fallbackToNoIndex::
 	If set to true, fall back to git grep --no-index if git grep
diff --git a/Documentation/git-grep.txt b/Documentation/git-grep.txt
index a7f9bc99ea..9bdf807584 100644
--- a/Documentation/git-grep.txt
+++ b/Documentation/git-grep.txt
@@ -41,34 +41,8 @@ characters.  An empty string as search expression matches all lines.
 CONFIGURATION
 -------------
 
-grep.lineNumber::
-	If set to true, enable `-n` option by default.
-
-grep.column::
-	If set to true, enable the `--column` option by default.
-
-grep.patternType::
-	Set the default matching behavior. Using a value of 'basic', 'extended',
-	'fixed', or 'perl' will enable the `--basic-regexp`, `--extended-regexp`,
-	`--fixed-strings`, or `--perl-regexp` option accordingly, while the
-	value 'default' will return to the default matching behavior.
-
-grep.extendedRegexp::
-	If set to true, enable `--extended-regexp` option by default. This
-	option is ignored when the `grep.patternType` option is set to a value
-	other than 'default'.
-
-grep.threads::
-	Number of grep worker threads to use. If unset (or set to 0), Git will
-	use as many threads as the number of logical cores available.
-
-grep.fullName::
-	If set to true, enable `--full-name` option by default.
-
-grep.fallbackToNoIndex::
-	If set to true, fall back to git grep --no-index if git grep
-	is executed outside of a git repository.  Defaults to false.
-
+:git-grep: 1
+include::config/grep.txt[]
 
 OPTIONS
 -------
@@ -269,8 +243,10 @@ providing this option will cause it to die.
 	found.
 
 --threads <num>::
-	Number of grep worker threads to use.
-	See `grep.threads` in 'CONFIGURATION' for more information.
+	Number of grep worker threads to use. If not provided (or set to
+	0), Git will use as many worker threads as the number of logical
+	cores available. The default value can also be set with the
+	`grep.threads` configuration.
 
 -f <file>::
 	Read patterns from <file>, one per line.
-- 
2.26.2


```

## Matheus Tavares, 2020-06-12 15:45

Subject: [PATCH v4 3/6] t/helper/test-config: facilitate addition of new cli options
Message-ID: <e9eaaecccc1be4be9ecae31e09422189c027e010.1591974940.git.matheus.bernardino@usp.br>
URL: https://gitlist.dev/e/e9eaaecccc1be4be9ecae31e09422189c027e010.1591974940.git.matheus.bernardino%40usp.br
In-Reply-To: <cover.1591974940.git.matheus.bernardino@usp.br>

```
test-config parses its arguments in an if-else chain, with one arm for
each available subcommand. Every arm expects (and checks) that argv
corresponds to something like "config <subcommand> [<subcommand args>]".
This means that whenever we want to change the syntax to accommodate a
new argument before <subcommand> (as we will do in the next patch), we
also need to increment the indexes accessing argv everywhere in the
if-else chain. This makes patches adding new options much noisier than
they need to be, besides being error-prone. So let's skip the "config"
argument in argv and argc to take the extra complexity out of such
patches (as the following one).

Signed-off-by: Matheus Tavares <matheus.bernardino@usp.br>
---
 t/helper/test-config.c | 64 ++++++++++++++++++++++--------------------
 1 file changed, 33 insertions(+), 31 deletions(-)

diff --git a/t/helper/test-config.c b/t/helper/test-config.c
index 1c8e965840..61da2574c5 100644
--- a/t/helper/test-config.c
+++ b/t/helper/test-config.c
@@ -84,33 +84,35 @@ int cmd__config(int argc, const char **argv)
 	int i, val;
 	const char *v;
 	const struct string_list *strptr;
-	struct config_set cs;
+	struct config_set cs = { .hash_initialized = 0 };
 	enum test_config_exit_code ret = TC_SUCCESS;
 
-	if (argc == 3 && !strcmp(argv[1], "read_early_config")) {
-		read_early_config(early_config_cb, (void *)argv[2]);
+	argc--; /* skip over "config" */
+	argv++;
+
+	if (argc == 0)
+		goto print_usage_error;
+
+	if (argc == 2 && !strcmp(argv[0], "read_early_config")) {
+		read_early_config(early_config_cb, (void *)argv[1]);
 		return TC_SUCCESS;
 	}
 
 	setup_git_directory();
-
 	git_configset_init(&cs);
 
-	if (argc < 2)
-		goto print_usage_error;
-
-	if (argc == 3 && !strcmp(argv[1], "get_value")) {
-		if (!git_config_get_value(argv[2], &v)) {
+	if (argc == 2 && !strcmp(argv[0], "get_value")) {
+		if (!git_config_get_value(argv[1], &v)) {
 			if (!v)
 				printf("(NULL)\n");
 			else
 				printf("%s\n", v);
 		} else {
-			printf("Value not found for \"%s\"\n", argv[2]);
+			printf("Value not found for \"%s\"\n", argv[1]);
 			ret = TC_VALUE_NOT_FOUND;
 		}
-	} else if (argc == 3 && !strcmp(argv[1], "get_value_multi")) {
-		strptr = git_config_get_value_multi(argv[2]);
+	} else if (argc == 2 && !strcmp(argv[0], "get_value_multi")) {
+		strptr = git_config_get_value_multi(argv[1]);
 		if (strptr) {
 			for (i = 0; i < strptr->nr; i++) {
 				v = strptr->items[i].string;
@@ -120,32 +122,32 @@ int cmd__config(int argc, const char **argv)
 					printf("%s\n", v);
 			}
 		} else {
-			printf("Value not found for \"%s\"\n", argv[2]);
+			printf("Value not found for \"%s\"\n", argv[1]);
 			ret = TC_VALUE_NOT_FOUND;
 		}
-	} else if (argc == 3 && !strcmp(argv[1], "get_int")) {
-		if (!git_config_get_int(argv[2], &val)) {
+	} else if (argc == 2 && !strcmp(argv[0], "get_int")) {
+		if (!git_config_get_int(argv[1], &val)) {
 			printf("%d\n", val);
 		} else {
-			printf("Value not found for \"%s\"\n", argv[2]);
+			printf("Value not found for \"%s\"\n", argv[1]);
 			ret = TC_VALUE_NOT_FOUND;
 		}
-	} else if (argc == 3 && !strcmp(argv[1], "get_bool")) {
-		if (!git_config_get_bool(argv[2], &val)) {
+	} else if (argc == 2 && !strcmp(argv[0], "get_bool")) {
+		if (!git_config_get_bool(argv[1], &val)) {
 			printf("%d\n", val);
 		} else {
-			printf("Value not found for \"%s\"\n", argv[2]);
+			printf("Value not found for \"%s\"\n", argv[1]);
 			ret = TC_VALUE_NOT_FOUND;
 		}
-	} else if (argc == 3 && !strcmp(argv[1], "get_string")) {
-		if (!git_config_get_string_const(argv[2], &v)) {
+	} else if (argc == 2 && !strcmp(argv[0], "get_string")) {
+		if (!git_config_get_string_const(argv[1], &v)) {
 			printf("%s\n", v);
 		} else {
-			printf("Value not found for \"%s\"\n", argv[2]);
+			printf("Value not found for \"%s\"\n", argv[1]);
 			ret = TC_VALUE_NOT_FOUND;
 		}
-	} else if (argc >= 3 && !strcmp(argv[1], "configset_get_value")) {
-		for (i = 3; i < argc; i++) {
+	} else if (argc >= 2 && !strcmp(argv[0], "configset_get_value")) {
+		for (i = 2; i < argc; i++) {
 			int err;
 			if ((err = git_configset_add_file(&cs, argv[i]))) {
 				fprintf(stderr, "Error (%d) reading configuration file %s.\n", err, argv[i]);
@@ -153,17 +155,17 @@ int cmd__config(int argc, const char **argv)
 				goto out;
 			}
 		}
-		if (!git_configset_get_value(&cs, argv[2], &v)) {
+		if (!git_configset_get_value(&cs, argv[1], &v)) {
 			if (!v)
 				printf("(NULL)\n");
 			else
 				printf("%s\n", v);
 		} else {
-			printf("Value not found for \"%s\"\n", argv[2]);
+			printf("Value not found for \"%s\"\n", argv[1]);
 			ret = TC_VALUE_NOT_FOUND;
 		}
-	} else if (argc >= 3 && !strcmp(argv[1], "configset_get_value_multi")) {
-		for (i = 3; i < argc; i++) {
+	} else if (argc >= 2 && !strcmp(argv[0], "configset_get_value_multi")) {
+		for (i = 2; i < argc; i++) {
 			int err;
 			if ((err = git_configset_add_file(&cs, argv[i]))) {
 				fprintf(stderr, "Error (%d) reading configuration file %s.\n", err, argv[i]);
@@ -171,7 +173,7 @@ int cmd__config(int argc, const char **argv)
 				goto out;
 			}
 		}
-		strptr = git_configset_get_value_multi(&cs, argv[2]);
+		strptr = git_configset_get_value_multi(&cs, argv[1]);
 		if (strptr) {
 			for (i = 0; i < strptr->nr; i++) {
 				v = strptr->items[i].string;
@@ -181,10 +183,10 @@ int cmd__config(int argc, const char **argv)
 					printf("%s\n", v);
 			}
 		} else {
-			printf("Value not found for \"%s\"\n", argv[2]);
+			printf("Value not found for \"%s\"\n", argv[1]);
 			ret = TC_VALUE_NOT_FOUND;
 		}
-	} else if (!strcmp(argv[1], "iterate")) {
+	} else if (!strcmp(argv[0], "iterate")) {
 		git_config(iterate_cb, NULL);
 	} else {
 print_usage_error:
-- 
2.26.2


```

## Matheus Tavares, 2020-06-12 15:45

Subject: [PATCH v4 4/6] config: correctly read worktree configs in submodules
Message-ID: <6402c968077900d48d189551a652e10984437a9f.1591974940.git.matheus.bernardino@usp.br>
URL: https://gitlist.dev/e/6402c968077900d48d189551a652e10984437a9f.1591974940.git.matheus.bernardino%40usp.br
In-Reply-To: <cover.1591974940.git.matheus.bernardino@usp.br>

```
One of the steps in do_git_config_sequence() is to load the
worktree-specific config file. Although the function receives a git_dir
string, it relies on git_pathdup(), which uses the_repository->git_dir,
to make the path to the file. Furthermore, it also checks that
extensions.worktreeConfig is set through the
repository_format_worktree_config variable, which refers to
the_repository only. Thus, when a submodule has worktree-specific
settings, a command executed in the superproject that recurses into the
submodule won't find the said settings.

This will be especially important in the next patch: git-grep will learn
to honor sparse checkouts and, when running with --recurse-submodules,
the submodule's sparse checkout settings must be loaded. As these
settings are stored in the config.worktree file, they would be ignored
without this patch. So let's fix this by reading the right
config.worktree file and extensions.worktreeConfig setting, based on the
git_dir and commondir paths given to do_git_config_sequence(). Also
add a test to avoid any regressions.

Signed-off-by: Matheus Tavares <matheus.bernardino@usp.br>
---
 config.c                   | 21 +++++++++---
 t/helper/test-config.c     | 67 +++++++++++++++++++++++++++++++++-----
 t/t2404-worktree-config.sh | 16 +++++++++
 3 files changed, 91 insertions(+), 13 deletions(-)

diff --git a/config.c b/config.c
index 8db9c77098..c2d56309dc 100644
--- a/config.c
+++ b/config.c
@@ -1747,11 +1747,22 @@ static int do_git_config_sequence(const struct config_options *opts,
 		ret += git_config_from_file(fn, repo_config, data);
 
 	current_parsing_scope = CONFIG_SCOPE_WORKTREE;
-	if (!opts->ignore_worktree && repository_format_worktree_config) {
-		char *path = git_pathdup("config.worktree");
-		if (!access_or_die(path, R_OK, 0))
-			ret += git_config_from_file(fn, path, data);
-		free(path);
+	if (!opts->ignore_worktree && repo_config && opts->git_dir) {
+		struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
+		struct strbuf buf = STRBUF_INIT;
+
+		read_repository_format(&repo_fmt, repo_config);
+
+		if (!verify_repository_format(&repo_fmt, &buf) &&
+		    repo_fmt.worktree_config) {
+			char *path = mkpathdup("%s/config.worktree", opts->git_dir);
+			if (!access_or_die(path, R_OK, 0))
+				ret += git_config_from_file(fn, path, data);
+			free(path);
+		}
+
+		strbuf_release(&buf);
+		clear_repository_format(&repo_fmt);
 	}
 
 	current_parsing_scope = CONFIG_SCOPE_COMMAND;
diff --git a/t/helper/test-config.c b/t/helper/test-config.c
index 61da2574c5..284f83a921 100644
--- a/t/helper/test-config.c
+++ b/t/helper/test-config.c
@@ -2,12 +2,19 @@
 #include "cache.h"
 #include "config.h"
 #include "string-list.h"
+#include "submodule-config.h"
 
 /*
  * This program exposes the C API of the configuration mechanism
  * as a set of simple commands in order to facilitate testing.
  *
- * Reads stdin and prints result of command to stdout:
+ * Usage: test-tool config [--submodule=<path>] <cmd> [<args>]
+ *
+ * If --submodule=<path> is given, <cmd> will operate on the submodule at the
+ * given <path>. This option is not valid for the commands: read_early_config,
+ * configset_get_value and configset_get_value_multi.
+ *
+ * Possible cmds are:
  *
  * get_value -> prints the value with highest priority for the entered key
  *
@@ -86,6 +93,8 @@ int cmd__config(int argc, const char **argv)
 	const struct string_list *strptr;
 	struct config_set cs = { .hash_initialized = 0 };
 	enum test_config_exit_code ret = TC_SUCCESS;
+	struct repository *repo = the_repository;
+	const char *subrepo_path = NULL;
 
 	argc--; /* skip over "config" */
 	argv++;
@@ -93,7 +102,18 @@ int cmd__config(int argc, const char **argv)
 	if (argc == 0)
 		goto print_usage_error;
 
+	if (skip_prefix(*argv, "--submodule=", &subrepo_path)) {
+		argc--;
+		argv++;
+		if (argc == 0)
+			goto print_usage_error;
+	}
+
 	if (argc == 2 && !strcmp(argv[0], "read_early_config")) {
+		if (subrepo_path) {
+			fprintf(stderr, "Cannot use --submodule with read_early_config\n");
+			return TC_USAGE_ERROR;
+		}
 		read_early_config(early_config_cb, (void *)argv[1]);
 		return TC_SUCCESS;
 	}
@@ -101,8 +121,23 @@ int cmd__config(int argc, const char **argv)
 	setup_git_directory();
 	git_configset_init(&cs);
 
+	if (subrepo_path) {
+		const struct submodule *sub;
+		struct repository *subrepo = xcalloc(1, sizeof(*repo));
+
+		sub = submodule_from_path(the_repository, &null_oid, subrepo_path);
+		if (!sub || repo_submodule_init(subrepo, the_repository, sub)) {
+			fprintf(stderr, "Invalid argument to --submodule: '%s'\n",
+				subrepo_path);
+			free(subrepo);
+			ret = TC_USAGE_ERROR;
+			goto out;
+		}
+		repo = subrepo;
+	}
+
 	if (argc == 2 && !strcmp(argv[0], "get_value")) {
-		if (!git_config_get_value(argv[1], &v)) {
+		if (!repo_config_get_value(repo, argv[1], &v)) {
 			if (!v)
 				printf("(NULL)\n");
 			else
@@ -112,7 +147,7 @@ int cmd__config(int argc, const char **argv)
 			ret = TC_VALUE_NOT_FOUND;
 		}
 	} else if (argc == 2 && !strcmp(argv[0], "get_value_multi")) {
-		strptr = git_config_get_value_multi(argv[1]);
+		strptr = repo_config_get_value_multi(repo, argv[1]);
 		if (strptr) {
 			for (i = 0; i < strptr->nr; i++) {
 				v = strptr->items[i].string;
@@ -126,27 +161,33 @@ int cmd__config(int argc, const char **argv)
 			ret = TC_VALUE_NOT_FOUND;
 		}
 	} else if (argc == 2 && !strcmp(argv[0], "get_int")) {
-		if (!git_config_get_int(argv[1], &val)) {
+		if (!repo_config_get_int(repo, argv[1], &val)) {
 			printf("%d\n", val);
 		} else {
 			printf("Value not found for \"%s\"\n", argv[1]);
 			ret = TC_VALUE_NOT_FOUND;
 		}
 	} else if (argc == 2 && !strcmp(argv[0], "get_bool")) {
-		if (!git_config_get_bool(argv[1], &val)) {
+		if (!repo_config_get_bool(repo, argv[1], &val)) {
 			printf("%d\n", val);
 		} else {
+
 			printf("Value not found for \"%s\"\n", argv[1]);
 			ret = TC_VALUE_NOT_FOUND;
 		}
 	} else if (argc == 2 && !strcmp(argv[0], "get_string")) {
-		if (!git_config_get_string_const(argv[1], &v)) {
+		if (!repo_config_get_string_const(repo, argv[1], &v)) {
 			printf("%s\n", v);
 		} else {
 			printf("Value not found for \"%s\"\n", argv[1]);
 			ret = TC_VALUE_NOT_FOUND;
 		}
 	} else if (argc >= 2 && !strcmp(argv[0], "configset_get_value")) {
+		if (subrepo_path) {
+			fprintf(stderr, "Cannot use --submodule with configset_get_value\n");
+			ret = TC_USAGE_ERROR;
+			goto out;
+		}
 		for (i = 2; i < argc; i++) {
 			int err;
 			if ((err = git_configset_add_file(&cs, argv[i]))) {
@@ -165,6 +206,11 @@ int cmd__config(int argc, const char **argv)
 			ret = TC_VALUE_NOT_FOUND;
 		}
 	} else if (argc >= 2 && !strcmp(argv[0], "configset_get_value_multi")) {
+		if (subrepo_path) {
+			fprintf(stderr, "Cannot use --submodule with configset_get_value_multi\n");
+			ret = TC_USAGE_ERROR;
+			goto out;
+		}
 		for (i = 2; i < argc; i++) {
 			int err;
 			if ((err = git_configset_add_file(&cs, argv[i]))) {
@@ -187,14 +233,19 @@ int cmd__config(int argc, const char **argv)
 			ret = TC_VALUE_NOT_FOUND;
 		}
 	} else if (!strcmp(argv[0], "iterate")) {
-		git_config(iterate_cb, NULL);
+		repo_config(repo, iterate_cb, NULL);
 	} else {
 print_usage_error:
-		fprintf(stderr, "Invalid syntax. Usage: test-tool config <cmd> [args]\n");
+		fprintf(stderr, "Invalid syntax. Usage: test-tool config"
+				" [--submodule=<path>] <cmd> [args]\n");
 		ret = TC_USAGE_ERROR;
 	}
 
 out:
 	git_configset_clear(&cs);
+	if (repo != the_repository) {
+		repo_clear(repo);
+		free(repo);
+	}
 	return ret;
 }
diff --git a/t/t2404-worktree-config.sh b/t/t2404-worktree-config.sh
index 286121d8de..b6ab793203 100755
--- a/t/t2404-worktree-config.sh
+++ b/t/t2404-worktree-config.sh
@@ -76,4 +76,20 @@ test_expect_success 'config.worktree no longer read without extension' '
 	test_cmp_config -C wt2 shared this.is
 '
 
+test_expect_success 'correctly read config.worktree from submodules' '
+	test_unconfig extensions.worktreeConfig &&
+	git init sub &&
+	(
+		cd sub &&
+		test_commit A &&
+		git config extensions.worktreeConfig true &&
+		git config --worktree wtconfig.sub test-value
+	) &&
+	git submodule add ./sub &&
+	git commit -m "add sub" &&
+	echo test-value >expect &&
+	test-tool config --submodule=sub get_value wtconfig.sub >actual &&
+	test_cmp expect actual
+'
+
 test_done
-- 
2.26.2


```

## Matheus Tavares, 2020-06-12 15:45

Subject: [PATCH v4 5/6] grep: honor sparse checkout patterns
Message-ID: <4d2916eb99e0182b3121e3d74bd75c3f478b294e.1591974940.git.matheus.bernardino@usp.br>
URL: https://gitlist.dev/e/4d2916eb99e0182b3121e3d74bd75c3f478b294e.1591974940.git.matheus.bernardino%40usp.br
In-Reply-To: <cover.1591974940.git.matheus.bernardino@usp.br>

```
One of the main uses for a sparse checkout is to allow users to focus on
the subset of files in a repository in which they are interested. But
git-grep currently ignores the sparsity patterns and reports all matches
found outside this subset, which kind of goes in the opposite direction.
There are some use cases for ignoring the sparsity patterns and the next
commit will add an option to obtain this behavior, but here we start by
making grep honor the sparsity boundaries in every case where this is
relevant:

- git grep in worktree
- git grep --cached
- git grep $REVISION

For the worktree and cached cases, we iterate over paths without the
SKIP_WORKTREE bit set, and limit our searches to these paths. For the
$REVISION case, we limit the paths we search to those that match the
sparsity patterns. (We do not check the SKIP_WORKTREE bit for the
$REVISION case, because $REVISION may contain paths that do not exist in
HEAD and thus for which we have no SKIP_WORKTREE bit to consult. The
sparsity patterns tell us how the SKIP_WORKTREE bit would be set if we
were to check out $REVISION, so we consult those. Also, we don't use the
sparsity patterns with the worktree or cached cases, both because we
have a bit we can check directly and more efficiently, and because
unmerged entries from a merge or a rebase could cause more files to
temporarily be present than the sparsity patterns would normally
select.)

Note that there is a special case here: `git grep $TREE`. In this case,
we cannot know whether $TREE corresponds to the root of the repository
or some sub-tree, and thus there is no way for us to know which sparsity
patterns, if any, apply. So the $TREE case will not use sparsity
patterns or any SKIP_WORKTREE bits and will instead always search all
files within the $TREE.

Signed-off-by: Matheus Tavares <matheus.bernardino@usp.br>
---
 builtin/grep.c                   | 125 ++++++++++++++++++--
 t/t7011-skip-worktree-reading.sh |   9 --
 t/t7817-grep-sparse-checkout.sh  | 195 +++++++++++++++++++++++++++++++
 3 files changed, 312 insertions(+), 17 deletions(-)
 create mode 100755 t/t7817-grep-sparse-checkout.sh

diff --git a/builtin/grep.c b/builtin/grep.c
index a5056f395a..bee0681393 100644
--- a/builtin/grep.c
+++ b/builtin/grep.c
@@ -410,7 +410,7 @@ static int grep_cache(struct grep_opt *opt,
 		      const struct pathspec *pathspec, int cached);
 static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
 		     struct tree_desc *tree, struct strbuf *base, int tn_len,
-		     int check_attr);
+		     int is_root_tree);
 
 static int grep_submodule(struct grep_opt *opt,
 			  const struct pathspec *pathspec,
@@ -508,6 +508,10 @@ static int grep_cache(struct grep_opt *opt,
 
 	for (nr = 0; nr < repo->index->cache_nr; nr++) {
 		const struct cache_entry *ce = repo->index->cache[nr];
+
+		if (ce_skip_worktree(ce))
+			continue;
+
 		strbuf_setlen(&name, name_base_len);
 		strbuf_addstr(&name, ce->name);
 
@@ -520,8 +524,7 @@ static int grep_cache(struct grep_opt *opt,
 			 * cache entry are identical, even if worktree file has
 			 * been modified, so use cache version instead
 			 */
-			if (cached || (ce->ce_flags & CE_VALID) ||
-			    ce_skip_worktree(ce)) {
+			if (cached || (ce->ce_flags & CE_VALID)) {
 				if (ce_stage(ce) || ce_intent_to_add(ce))
 					continue;
 				hit |= grep_oid(opt, &ce->oid, name.buf,
@@ -552,9 +555,76 @@ static int grep_cache(struct grep_opt *opt,
 	return hit;
 }
 
-static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
-		     struct tree_desc *tree, struct strbuf *base, int tn_len,
-		     int check_attr)
+static struct pattern_list *get_sparsity_patterns(struct repository *repo)
+{
+	struct pattern_list *patterns;
+	char *sparse_file;
+	int sparse_config, cone_config;
+
+	if (repo_config_get_bool(repo, "core.sparsecheckout", &sparse_config) ||
+	    !sparse_config) {
+		return NULL;
+	}
+
+	sparse_file = repo_git_path(repo, "info/sparse-checkout");
+	patterns = xcalloc(1, sizeof(*patterns));
+
+	if (repo_config_get_bool(repo, "core.sparsecheckoutcone", &cone_config))
+		cone_config = 0;
+	patterns->use_cone_patterns = cone_config;
+
+	if (add_patterns_from_file_to_list(sparse_file, "", 0, patterns, NULL)) {
+		if (file_exists(sparse_file)) {
+			warning(_("failed to load sparse-checkout file: '%s'"),
+				sparse_file);
+		}
+		free(sparse_file);
+		free(patterns);
+		return NULL;
+	}
+
+	free(sparse_file);
+	return patterns;
+}
+
+static int path_in_sparse_checkout(struct strbuf *path, int prefix_len,
+				   unsigned int entry_mode,
+				   struct index_state *istate,
+				   struct pattern_list *sparsity,
+				   enum pattern_match_result parent_match,
+				   enum pattern_match_result *match)
+{
+	int dtype = DT_UNKNOWN;
+	int is_dir = S_ISDIR(entry_mode);
+
+	if (parent_match == MATCHED_RECURSIVE) {
+		*match = parent_match;
+		return 1;
+	}
+
+	if (is_dir && !is_dir_sep(path->buf[path->len - 1]))
+		strbuf_addch(path, '/');
+
+	*match = path_matches_pattern_list(path->buf, path->len,
+					   path->buf + prefix_len, &dtype,
+					   sparsity, istate);
+	if (*match == UNDECIDED)
+		*match = parent_match;
+
+	if (is_dir)
+		strbuf_trim_trailing_dir_sep(path);
+
+	if (*match == NOT_MATCHED &&
+		(!is_dir || (is_dir && sparsity->use_cone_patterns)))
+	     return 0;
+
+	return 1;
+}
+
+static int do_grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
+			struct tree_desc *tree, struct strbuf *base, int tn_len,
+			int check_attr, struct pattern_list *sparsity,
+			enum pattern_match_result default_sparsity_match)
 {
 	struct repository *repo = opt->repo;
 	int hit = 0;
@@ -570,6 +640,7 @@ static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
 
 	while (tree_entry(tree, &entry)) {
 		int te_len = tree_entry_len(&entry);
+		enum pattern_match_result sparsity_match = 0;
 
 		if (match != all_entries_interesting) {
 			strbuf_addstr(&name, base->buf + tn_len);
@@ -586,6 +657,19 @@ static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
 
 		strbuf_add(base, entry.path, te_len);
 
+		if (sparsity) {
+			struct strbuf path = STRBUF_INIT;
+			strbuf_addstr(&path, base->buf + tn_len);
+
+			if (!path_in_sparse_checkout(&path, old_baselen - tn_len,
+						     entry.mode, repo->index,
+						     sparsity, default_sparsity_match,
+						     &sparsity_match)) {
+				strbuf_setlen(base, old_baselen);
+				continue;
+			}
+		}
+
 		if (S_ISREG(entry.mode)) {
 			hit |= grep_oid(opt, &entry.oid, base->buf, tn_len,
 					 check_attr ? base->buf + tn_len : NULL);
@@ -602,8 +686,8 @@ static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
 
 			strbuf_addch(base, '/');
 			init_tree_desc(&sub, data, size);
-			hit |= grep_tree(opt, pathspec, &sub, base, tn_len,
-					 check_attr);
+			hit |= do_grep_tree(opt, pathspec, &sub, base, tn_len,
+					    check_attr, sparsity, sparsity_match);
 			free(data);
 		} else if (recurse_submodules && S_ISGITLINK(entry.mode)) {
 			hit |= grep_submodule(opt, pathspec, &entry.oid,
@@ -621,6 +705,31 @@ static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
 	return hit;
 }
 
+/*
+ * Note: sparsity patterns and paths' attributes will only be considered if
+ * is_root_tree has true value. (Otherwise, we cannot properly perform pattern
+ * matching on paths.)
+ */
+static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
+		     struct tree_desc *tree, struct strbuf *base, int tn_len,
+		     int is_root_tree)
+{
+	struct pattern_list *patterns = NULL;
+	int ret;
+
+	if (is_root_tree)
+		patterns = get_sparsity_patterns(opt->repo);
+
+	ret = do_grep_tree(opt, pathspec, tree, base, tn_len, is_root_tree,
+			   patterns, 0);
+
+	if (patterns) {
+		clear_pattern_list(patterns);
+		free(patterns);
+	}
+	return ret;
+}
+
 static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
 		       struct object *obj, const char *name, const char *path)
 {
diff --git a/t/t7011-skip-worktree-reading.sh b/t/t7011-skip-worktree-reading.sh
index 37525cae3a..26852586ac 100755
--- a/t/t7011-skip-worktree-reading.sh
+++ b/t/t7011-skip-worktree-reading.sh
@@ -109,15 +109,6 @@ test_expect_success 'ls-files --modified' '
 	test -z "$(git ls-files -m)"
 '
 
-test_expect_success 'grep with skip-worktree file' '
-	git update-index --no-skip-worktree 1 &&
-	echo test > 1 &&
-	git update-index 1 &&
-	git update-index --skip-worktree 1 &&
-	rm 1 &&
-	test "$(git grep --no-ext-grep test)" = "1:test"
-'
-
 echo ":000000 100644 $ZERO_OID $EMPTY_BLOB A	1" > expected
 test_expect_success 'diff-index does not examine skip-worktree absent entries' '
 	setup_absent &&
diff --git a/t/t7817-grep-sparse-checkout.sh b/t/t7817-grep-sparse-checkout.sh
new file mode 100755
index 0000000000..b3109e3479
--- /dev/null
+++ b/t/t7817-grep-sparse-checkout.sh
@@ -0,0 +1,195 @@
+#!/bin/sh
+
+test_description='grep in sparse checkout
+
+This test creates a repo with the following structure:
+
+.
+|-- a
+|-- b
+|-- dir
+|   `-- c
+|-- sub
+|   |-- A
+|   |   `-- a
+|   `-- B
+|       `-- b
+`-- sub2
+    `-- a
+
+Where the outer repository has non-cone mode sparsity patterns, sub is a
+submodule with cone mode sparsity patterns and sub2 is a submodule that is
+excluded by the superproject sparsity patterns. The resulting sparse checkout
+should leave the following structure in the working tree:
+
+.
+|-- a
+|-- sub
+|   `-- B
+|       `-- b
+`-- sub2
+    `-- a
+
+But note that sub2 should have the SKIP_WORKTREE bit set.
+'
+
+. ./test-lib.sh
+
+test_expect_success 'setup' '
+	echo "text" >a &&
+	echo "text" >b &&
+	mkdir dir &&
+	echo "text" >dir/c &&
+
+	git init sub &&
+	(
+		cd sub &&
+		mkdir A B &&
+		echo "text" >A/a &&
+		echo "text" >B/b &&
+		git add A B &&
+		git commit -m sub &&
+		git sparse-checkout init --cone &&
+		git sparse-checkout set B
+	) &&
+
+	git init sub2 &&
+	(
+		cd sub2 &&
+		echo "text" >a &&
+		git add a &&
+		git commit -m sub2
+	) &&
+
+	git submodule add ./sub &&
+	git submodule add ./sub2 &&
+	git add a b dir &&
+	git commit -m super &&
+	git sparse-checkout init --no-cone &&
+	git sparse-checkout set "/*" "!b" "!/*/" "sub" &&
+
+	git tag -am tag-to-commit tag-to-commit HEAD &&
+	tree=$(git rev-parse HEAD^{tree}) &&
+	git tag -am tag-to-tree tag-to-tree $tree &&
+
+	test_path_is_missing b &&
+	test_path_is_missing dir &&
+	test_path_is_missing sub/A &&
+	test_path_is_file a &&
+	test_path_is_file sub/B/b &&
+	test_path_is_file sub2/a
+'
+
+# The test below checks a special case: the sparsity patterns exclude '/b'
+# and sparse checkout is enabled, but the path exists in the working tree (e.g.
+# manually created after `git sparse-checkout init`). In this case, grep should
+# skip it.
+test_expect_success 'grep in working tree should honor sparse checkout' '
+	cat >expect <<-EOF &&
+	a:text
+	EOF
+	echo "new-text" >b &&
+	test_when_finished "rm b" &&
+	git grep "text" >actual &&
+	test_cmp expect actual
+'
+
+test_expect_success 'grep unmerged file despite not matching sparsity patterns' '
+	cat >expect <<-EOF &&
+	b:modified-b-in-branchX
+	b:modified-b-in-branchY
+	EOF
+	test_when_finished "test_might_fail git merge --abort && \
+			    git checkout master" &&
+
+	git sparse-checkout disable &&
+	git checkout -b branchY master &&
+	test_commit modified-b-in-branchY b &&
+	git checkout -b branchX master &&
+	test_commit modified-b-in-branchX b &&
+
+	git sparse-checkout init &&
+	test_path_is_missing b &&
+	test_must_fail git merge branchY &&
+	git grep "modified-b" >actual &&
+	test_cmp expect actual
+'
+
+test_expect_success 'grep --cached should honor sparse checkout' '
+	cat >expect <<-EOF &&
+	a:text
+	EOF
+	git grep --cached "text" >actual &&
+	test_cmp expect actual
+'
+
+test_expect_success 'grep <commit-ish> should honor sparse checkout' '
+	commit=$(git rev-parse HEAD) &&
+	cat >expect_commit <<-EOF &&
+	$commit:a:text
+	EOF
+	cat >expect_tag-to-commit <<-EOF &&
+	tag-to-commit:a:text
+	EOF
+	git grep "text" $commit >actual_commit &&
+	test_cmp expect_commit actual_commit &&
+	git grep "text" tag-to-commit >actual_tag-to-commit &&
+	test_cmp expect_tag-to-commit actual_tag-to-commit
+'
+
+test_expect_success 'grep <tree-ish> should ignore sparsity patterns' '
+	commit=$(git rev-parse HEAD) &&
+	tree=$(git rev-parse HEAD^{tree}) &&
+	cat >expect_tree <<-EOF &&
+	$tree:a:text
+	$tree:b:text
+	$tree:dir/c:text
+	EOF
+	cat >expect_tag-to-tree <<-EOF &&
+	tag-to-tree:a:text
+	tag-to-tree:b:text
+	tag-to-tree:dir/c:text
+	EOF
+	git grep "text" $tree >actual_tree &&
+	test_cmp expect_tree actual_tree &&
+	git grep "text" tag-to-tree >actual_tag-to-tree &&
+	test_cmp expect_tag-to-tree actual_tag-to-tree
+'
+
+# Note that sub2/ is present in the worktree but it is excluded by the sparsity
+# patterns, so grep should not recurse into it.
+test_expect_success 'grep --recurse-submodules should honor sparse checkout in submodule' '
+	cat >expect <<-EOF &&
+	a:text
+	sub/B/b:text
+	EOF
+	git grep --recurse-submodules "text" >actual &&
+	test_cmp expect actual
+'
+
+test_expect_success 'grep --recurse-submodules --cached should honor sparse checkout in submodule' '
+	cat >expect <<-EOF &&
+	a:text
+	sub/B/b:text
+	EOF
+	git grep --recurse-submodules --cached "text" >actual &&
+	test_cmp expect actual
+'
+
+test_expect_success 'grep --recurse-submodules <commit-ish> should honor sparse checkout in submodule' '
+	commit=$(git rev-parse HEAD) &&
+	cat >expect_commit <<-EOF &&
+	$commit:a:text
+	$commit:sub/B/b:text
+	EOF
+	cat >expect_tag-to-commit <<-EOF &&
+	tag-to-commit:a:text
+	tag-to-commit:sub/B/b:text
+	EOF
+	git grep --recurse-submodules "text" $commit >actual_commit &&
+	test_cmp expect_commit actual_commit &&
+	git grep --recurse-submodules "text" tag-to-commit >actual_tag-to-commit &&
+	test_cmp expect_tag-to-commit actual_tag-to-commit
+'
+
+test_done
-- 
2.26.2


```

## Matheus Tavares, 2020-06-12 15:45

Subject: [PATCH v4 6/6] config: add setting to ignore sparsity patterns in some cmds
Message-ID: <4547718b608b76e6ee71d8331110b44496e2f304.1591974940.git.matheus.bernardino@usp.br>
URL: https://gitlist.dev/e/4547718b608b76e6ee71d8331110b44496e2f304.1591974940.git.matheus.bernardino%40usp.br
In-Reply-To: <cover.1591974940.git.matheus.bernardino@usp.br>

```
When sparse checkout is enabled, some users expect the output of certain
commands (such as grep, diff, and log) to be also restricted within the
sparsity patterns. This would allow them to effectively work only on the
subset of files in which they are interested; and allow some commands to
possibly perform better, by not considering uninteresting paths. For
this reason, we taught grep to honor the sparsity patterns, in the
previous patch. But, on the other hand, allowing grep and the other
commands mentioned to optionally ignore the patterns also make for some
interesting use cases. E.g. using grep to search for a function
documentation that resides outside the sparse checkout.

In any case, there is no current way for users to configure the behavior
they want for these commands. Aiming to provide this flexibility, let's
introduce the sparse.restrictCmds setting (and the analogous
--[no]-restrict-to-sparse-paths global option). The default value is
true. For now, grep is the only one affected by this setting, but the
goal is to have support for more commands, in the future.

Helped-by: Elijah Newren <newren@gmail.com>
Signed-off-by: Matheus Tavares <matheus.bernardino@usp.br>
---
 Documentation/config.txt               |   2 +
 Documentation/config/grep.txt          |   8 ++
 Documentation/config/sparse.txt        |  20 ++++
 Documentation/git.txt                  |   4 +
 Makefile                               |   1 +
 builtin/grep.c                         |  13 ++-
 contrib/completion/git-completion.bash |   2 +
 git.c                                  |   5 +
 sparse-checkout.c                      |  18 ++++
 sparse-checkout.h                      |  11 +++
 t/t7817-grep-sparse-checkout.sh        | 132 ++++++++++++++++++++++++-
 t/t9902-completion.sh                  |   4 +-
 12 files changed, 214 insertions(+), 6 deletions(-)
 create mode 100644 Documentation/config/sparse.txt
 create mode 100644 sparse-checkout.c
 create mode 100644 sparse-checkout.h

diff --git a/Documentation/config.txt b/Documentation/config.txt
index ef0768b91a..fd74b80302 100644
--- a/Documentation/config.txt
+++ b/Documentation/config.txt
@@ -436,6 +436,8 @@ include::config/sequencer.txt[]
 
 include::config/showbranch.txt[]
 
+include::config/sparse.txt[]
+
 include::config/splitindex.txt[]
 
 include::config/ssh.txt[]
diff --git a/Documentation/config/grep.txt b/Documentation/config/grep.txt
index dd51db38e1..a3275ab4b7 100644
--- a/Documentation/config/grep.txt
+++ b/Documentation/config/grep.txt
@@ -28,3 +28,11 @@ grep.fullName::
 grep.fallbackToNoIndex::
 	If set to true, fall back to git grep --no-index if git grep
 	is executed outside of a git repository.  Defaults to false.
+
+ifdef::git-grep[]
+sparse.restrictCmds::
+	See base definition in linkgit:git-config[1]. grep honors
+	sparse.restrictCmds by limiting searches to the sparsity paths in three
+	cases: when searching the working tree, when searching the index with
+	--cached, and when searching a specified commit.
+endif::git-grep[]
diff --git a/Documentation/config/sparse.txt b/Documentation/config/sparse.txt
new file mode 100644
index 0000000000..494761526e
--- /dev/null
+++ b/Documentation/config/sparse.txt
@@ -0,0 +1,20 @@
+sparse.restrictCmds::
+	Only meaningful in conjunction with core.sparseCheckout. This option
+	extends sparse checkouts (which limit which paths are written to the
+	working tree), so that output and operations are also limited to the
+	sparsity paths where possible and implemented. The purpose of this
+	option is to (1) focus output for the user on the portion of the
+	repository that is of interest to them, and (2) enable potentially
+	dramatic performance improvements, especially in conjunction with
+	partial clones.
++
+When this option is true (default), some git commands may limit their behavior
+to the paths specified by the sparsity patterns, or to the intersection of
+those paths and any (like `*.c`) that the user might also specify on the
+command line. When false, the affected commands will work on full trees,
+ignoring the sparsity patterns. For now, only git-grep honors this setting.
++
+Note: commands which export, integrity check, or create history will always
+operate on full trees (e.g. fast-export, format-patch, fsck, commit, etc.),
+unaffected by any sparsity patterns. Also, writing commands such as
+sparse-checkout and read-tree will not be affected by this configuration.
diff --git a/Documentation/git.txt b/Documentation/git.txt
index 40bd32f590..89604b6648 100644
--- a/Documentation/git.txt
+++ b/Documentation/git.txt
@@ -180,6 +180,10 @@ If you just want to run git as if it was started in `<path>` then use
 	Do not perform optional operations that require locks. This is
 	equivalent to setting the `GIT_OPTIONAL_LOCKS` to `0`.
 
+--[no-]restrict-to-sparse-paths::
+	Overrides the sparse.restrictCmds configuration (see
+	linkgit:git-config[1]) for this execution.
+
 --list-cmds=group[,group...]::
 	List commands by group. This is an internal/experimental
 	option and may change or be removed in the future. Supported
diff --git a/Makefile b/Makefile
index 372139f1f2..9c8a6f19cd 100644
--- a/Makefile
+++ b/Makefile
@@ -983,6 +983,7 @@ LIB_OBJS += sha1-name.o
 LIB_OBJS += shallow.o
 LIB_OBJS += sideband.o
 LIB_OBJS += sigchain.o
+LIB_OBJS += sparse-checkout.o
 LIB_OBJS += split-index.o
 LIB_OBJS += stable-qsort.o
 LIB_OBJS += strbuf.o
diff --git a/builtin/grep.c b/builtin/grep.c
index bee0681393..7f485ea732 100644
--- a/builtin/grep.c
+++ b/builtin/grep.c
@@ -25,6 +25,7 @@
 #include "submodule-config.h"
 #include "object-store.h"
 #include "packfile.h"
+#include "sparse-checkout.h"
 
 static char const * const grep_usage[] = {
 	N_("git grep [<options>] [-e] <pattern> [<rev>...] [[--] <path>...]"),
@@ -498,6 +499,7 @@ static int grep_cache(struct grep_opt *opt,
 	int nr;
 	struct strbuf name = STRBUF_INIT;
 	int name_base_len = 0;
+	int sparse_paths_only =	restrict_to_sparse_paths(repo);
 	if (repo->submodule_prefix) {
 		name_base_len = strlen(repo->submodule_prefix);
 		strbuf_addstr(&name, repo->submodule_prefix);
@@ -509,7 +511,7 @@ static int grep_cache(struct grep_opt *opt,
 	for (nr = 0; nr < repo->index->cache_nr; nr++) {
 		const struct cache_entry *ce = repo->index->cache[nr];
 
-		if (ce_skip_worktree(ce))
+		if (sparse_paths_only && ce_skip_worktree(ce))
 			continue;
 
 		strbuf_setlen(&name, name_base_len);
@@ -715,9 +717,10 @@ static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
 		     int is_root_tree)
 {
 	struct pattern_list *patterns = NULL;
+	int sparse_paths_only = restrict_to_sparse_paths(opt->repo);
 	int ret;
 
-	if (is_root_tree)
+	if (is_root_tree && sparse_paths_only)
 		patterns = get_sparsity_patterns(opt->repo);
 
 	ret = do_grep_tree(opt, pathspec, tree, base, tn_len, is_root_tree,
@@ -1257,6 +1260,12 @@ int cmd_grep(int argc, const char **argv, const char *prefix)
 
 	if (!use_index || untracked) {
 		int use_exclude = (opt_exclude < 0) ? use_index : !!opt_exclude;
+
+		if (opt_restrict_to_sparse_paths >= 0) {
+			die(_("--[no-]restrict-to-sparse-paths is incompatible"
+				  " with --no-index and --untracked"));
+		}
+
 		hit = grep_directory(&opt, &pathspec, use_exclude, use_index);
 	} else if (0 <= opt_exclude) {
 		die(_("--[no-]exclude-standard cannot be used for tracked contents"));
diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
index 4b59004847..3f15fd5275 100644
--- a/contrib/completion/git-completion.bash
+++ b/contrib/completion/git-completion.bash
@@ -3208,6 +3208,8 @@ __git_main ()
 			--namespace=
 			--no-replace-objects
 			--help
+			--restrict-to-sparse-paths
+			--no-restrict-to-sparse-paths
 			"
 			;;
 		*)
diff --git a/git.c b/git.c
index a2d337eed7..99bac1d26d 100644
--- a/git.c
+++ b/git.c
@@ -5,6 +5,7 @@
 #include "run-command.h"
 #include "alias.h"
 #include "shallow.h"
+#include "sparse-checkout.h"
 
 #define RUN_SETUP		(1<<0)
 #define RUN_SETUP_GENTLY	(1<<1)
@@ -311,6 +312,10 @@ static int handle_options(const char ***argv, int *argc, int *envchanged)
 			} else {
 				exit(list_cmds(cmd));
 			}
+		} else if (!strcmp(cmd, "--restrict-to-sparse-paths")) {
+			opt_restrict_to_sparse_paths = 1;
+		} else if (!strcmp(cmd, "--no-restrict-to-sparse-paths")) {
+			opt_restrict_to_sparse_paths = 0;
 		} else {
 			fprintf(stderr, _("unknown option: %s\n"), cmd);
 			usage(git_usage_string);
diff --git a/sparse-checkout.c b/sparse-checkout.c
new file mode 100644
index 0000000000..96c5ed5446
--- /dev/null
+++ b/sparse-checkout.c
@@ -0,0 +1,18 @@
+#include "cache.h"
+#include "config.h"
+#include "sparse-checkout.h"
+
+int opt_restrict_to_sparse_paths = -1;
+
+int restrict_to_sparse_paths(struct repository *repo)
+{
+	int ret;
+
+	if (opt_restrict_to_sparse_paths >= 0)
+		return opt_restrict_to_sparse_paths;
+
+	if (repo_config_get_bool(repo, "sparse.restrictcmds", &ret))
+		ret = 1;
+
+	return ret;
+}
diff --git a/sparse-checkout.h b/sparse-checkout.h
new file mode 100644
index 0000000000..a4805e443a
--- /dev/null
+++ b/sparse-checkout.h
@@ -0,0 +1,11 @@
+#ifndef SPARSE_CHECKOUT_H
+#define SPARSE_CHECKOUT_H
+
+struct repository;
+
+extern int opt_restrict_to_sparse_paths;
+
+/* Whether or not cmds should restrict behavior on sparse paths, in this repo */
+int restrict_to_sparse_paths(struct repository *repo);
+
+#endif /* SPARSE_CHECKOUT_H */
diff --git a/t/t7817-grep-sparse-checkout.sh b/t/t7817-grep-sparse-checkout.sh
index b3109e3479..f93a4f71d1 100755
--- a/t/t7817-grep-sparse-checkout.sh
+++ b/t/t7817-grep-sparse-checkout.sh
@@ -80,10 +80,10 @@ test_expect_success 'setup' '
 	test_path_is_file sub2/a
 '
 
-# The test below checks a special case: the sparsity patterns exclude '/b'
+# The two tests below check a special case: the sparsity patterns exclude '/b'
 # and sparse checkout is enabled, but the path exists in the working tree (e.g.
 # manually created after `git sparse-checkout init`). In this case, grep should
-# skip it.
+# skip the file by default, but not with --no-restrict-to-sparse-paths.
 test_expect_success 'grep in working tree should honor sparse checkout' '
 	cat >expect <<-EOF &&
 	a:text
@@ -93,6 +93,16 @@ test_expect_success 'grep in working tree should honor sparse checkout' '
 	git grep "text" >actual &&
 	test_cmp expect actual
 '
+test_expect_success 'grep w/ --no-restrict-to-sparse-paths for sparsely excluded but present paths' '
+	cat >expect <<-EOF &&
+	a:text
+	b:new-text
+	EOF
+	echo "new-text" >b &&
+	test_when_finished "rm b" &&
+	git --no-restrict-to-sparse-paths grep "text" >actual &&
+	test_cmp expect actual
+'
 
 test_expect_success 'grep unmerged file despite not matching sparsity patterns' '
 	cat >expect <<-EOF &&
@@ -157,7 +167,7 @@ test_expect_success 'grep <tree-ish> should ignore sparsity patterns' '
 '
 
 # Note that sub2/ is present in the worktree but it is excluded by the sparsity
-# patterns, so grep should not recurse into it.
+# patterns, so grep should only recurse into it with --no-restrict-to-sparse-paths.
 test_expect_success 'grep --recurse-submodules should honor sparse checkout in submodule' '
 	cat >expect <<-EOF &&
 	a:text
@@ -166,6 +176,15 @@ test_expect_success 'grep --recurse-submodules should honor sparse checkout in s
 	git grep --recurse-submodules "text" >actual &&
 	test_cmp expect actual
 '
+test_expect_success 'grep --recurse-submodules should search in excluded submodules w/ --no-restrict-to-sparse-paths' '
+	cat >expect <<-EOF &&
+	a:text
+	sub/B/b:text
+	sub2/a:text
+	EOF
+	git --no-restrict-to-sparse-paths grep --recurse-submodules "text" >actual &&
+	test_cmp expect actual
+'
 
 test_expect_success 'grep --recurse-submodules --cached should honor sparse checkout in submodule' '
 	cat >expect <<-EOF &&
@@ -192,4 +211,111 @@ test_expect_success 'grep --recurse-submodules <commit-ish> should honor sparse
 	test_cmp expect_tag-to-commit actual_tag-to-commit
 '
 
+for cmd in 'git --no-restrict-to-sparse-paths grep' \
+	   'git -c sparse.restrictCmds=false grep' \
+	   'git -c sparse.restrictCmds=true --no-restrict-to-sparse-paths grep'
+do
+
+	test_expect_success "$cmd --cached should ignore sparsity patterns" '
+		cat >expect <<-EOF &&
+		a:text
+		b:text
+		dir/c:text
+		EOF
+		$cmd --cached "text" >actual &&
+		test_cmp expect actual
+	'
+
+	test_expect_success "$cmd <commit-ish> should ignore sparsity patterns" '
+		commit=$(git rev-parse HEAD) &&
+		cat >expect_commit <<-EOF &&
+		$commit:a:text
+		$commit:b:text
+		$commit:dir/c:text
+		EOF
+		cat >expect_tag-to-commit <<-EOF &&
+		tag-to-commit:a:text
+		tag-to-commit:b:text
+		tag-to-commit:dir/c:text
+		EOF
+		$cmd "text" $commit >actual_commit &&
+		test_cmp expect_commit actual_commit &&
+		$cmd "text" tag-to-commit >actual_tag-to-commit &&
+		test_cmp expect_tag-to-commit actual_tag-to-commit
+	'
+done
+
+test_expect_success 'grep --recurse-submodules --cached w/ --no-restrict-to-sparse-paths' '
+	cat >expect <<-EOF &&
+	a:text
+	b:text
+	dir/c:text
+	sub/A/a:text
+	sub/B/b:text
+	sub2/a:text
+	EOF
+	git --no-restrict-to-sparse-paths grep --recurse-submodules --cached \
+		"text" >actual &&
+	test_cmp expect actual
+'
+
+test_expect_success 'grep --recurse-submodules <commit-ish> w/ --no-restrict-to-sparse-paths' '
+	commit=$(git rev-parse HEAD) &&
+	cat >expect_commit <<-EOF &&
+	$commit:a:text
+	$commit:b:text
+	$commit:dir/c:text
+	$commit:sub/A/a:text
+	$commit:sub/B/b:text
+	$commit:sub2/a:text
+	EOF
+	cat >expect_tag-to-commit <<-EOF &&
+	tag-to-commit:a:text
+	tag-to-commit:b:text
+	tag-to-commit:dir/c:text
+	tag-to-commit:sub/A/a:text
+	tag-to-commit:sub/B/b:text
+	tag-to-commit:sub2/a:text
+	EOF
+	git --no-restrict-to-sparse-paths grep --recurse-submodules "text" \
+		$commit >actual_commit &&
+	test_cmp expect_commit actual_commit &&
+	git --no-restrict-to-sparse-paths grep --recurse-submodules "text" \
+		tag-to-commit >actual_tag-to-commit &&
+	test_cmp expect_tag-to-commit actual_tag-to-commit
+'
+
+test_expect_success 'should respect the sparse.restrictCmds values from submodules' '
+	cat >expect <<-EOF &&
+	a:text
+	sub/A/a:text
+	sub/B/b:text
+	EOF
+	test_config -C sub sparse.restrictCmds false &&
+	git grep --cached --recurse-submodules "text" >actual &&
+	test_cmp expect actual
+'
+
+test_expect_success 'should propagate --[no]-restrict-to-sparse-paths to submodules' '
+	cat >expect <<-EOF &&
+	a:text
+	b:text
+	dir/c:text
+	sub/A/a:text
+	sub/B/b:text
+	sub2/a:text
+	EOF
+	test_config -C sub sparse.restrictCmds true &&
+	git --no-restrict-to-sparse-paths grep --cached --recurse-submodules "text" >actual &&
+	test_cmp expect actual
+'
+
+for opt in '--untracked' '--no-index'
+do
+	test_expect_success "--[no]-restrict-to-sparse-paths and $opt are incompatible" "
+		test_must_fail git --restrict-to-sparse-paths grep $opt . 2>actual &&
+		test_i18ngrep 'restrict-to-sparse-paths is incompatible with' actual
+	"
+done
+
 test_done
diff --git a/t/t9902-completion.sh b/t/t9902-completion.sh
index 3c44af6940..a4a7767e06 100755
--- a/t/t9902-completion.sh
+++ b/t/t9902-completion.sh
@@ -1473,6 +1473,8 @@ test_expect_success 'double dash "git" itself' '
 	--namespace=
 	--no-replace-objects Z
 	--help Z
+	--restrict-to-sparse-paths Z
+	--no-restrict-to-sparse-paths Z
 	EOF
 '
 
@@ -1515,7 +1517,7 @@ test_expect_success 'general options' '
 	test_completion "git --nam" "--namespace=" &&
 	test_completion "git --bar" "--bare " &&
 	test_completion "git --inf" "--info-path " &&
-	test_completion "git --no-r" "--no-replace-objects "
+	test_completion "git --no-rep" "--no-replace-objects "
 '
 
 test_expect_success 'general options plus command' '
-- 
2.26.2


```

## Elijah Newren, 2020-06-16 19:13

Subject: Re: [PATCH v4 4/6] config: correctly read worktree configs in submodules
Message-ID: <CABPp-BGdEyEeajYZj_rdxp=MyEQdszuyjVTax=hhYj3fOtRQUQ@mail.gmail.com>
URL: https://gitlist.dev/e/CABPp-BGdEyEeajYZj_rdxp%3DMyEQdszuyjVTax%3DhhYj3fOtRQUQ%40mail.gmail.com
In-Reply-To: <6402c968077900d48d189551a652e10984437a9f.1591974940.git.matheus.bernardino@usp.br>

```
Hi,

On Fri, Jun 12, 2020 at 8:45 AM Matheus Tavares
<matheus.bernardino@usp.br> wrote:
>
> One of the steps in do_git_config_sequence() is to load the
> worktree-specific config file. Although the function receives a git_dir
> string, it relies on git_pathdup(), which uses the_repository->git_dir,
> to make the path to the file. Furthermore, it also checks that
> extensions.worktreeConfig is set through the
> repository_format_worktree_config variable, which refers to
> the_repository only. Thus, when a submodule has worktree-specific
> settings, a command executed in the superproject that recurses into the
> submodule won't find the said settings.
>
> This will be especially important in the next patch: git-grep will learn
> to honor sparse checkouts and, when running with --recurse-submodules,
> the submodule's sparse checkout settings must be loaded. As these
> settings are stored in the config.worktree file, they would be ignored
> without this patch. So let's fix this by reading the right
> config.worktree file and extensions.worktreeConfig setting, based on the
> git_dir and commondir paths given to do_git_config_sequence(). Also
> add a test to avoid any regressions.

Thanks for splitting this part of the change out from the previous patch.

>
> Signed-off-by: Matheus Tavares <matheus.bernardino@usp.br>
> ---
>  config.c                   | 21 +++++++++---
>  t/helper/test-config.c     | 67 +++++++++++++++++++++++++++++++++-----
>  t/t2404-worktree-config.sh | 16 +++++++++
>  3 files changed, 91 insertions(+), 13 deletions(-)
>
> diff --git a/config.c b/config.c
> index 8db9c77098..c2d56309dc 100644
> --- a/config.c
> +++ b/config.c
> @@ -1747,11 +1747,22 @@ static int do_git_config_sequence(const struct config_options *opts,
>                 ret += git_config_from_file(fn, repo_config, data);
>
>         current_parsing_scope = CONFIG_SCOPE_WORKTREE;
> -       if (!opts->ignore_worktree && repository_format_worktree_config) {
> -               char *path = git_pathdup("config.worktree");
> -               if (!access_or_die(path, R_OK, 0))
> -                       ret += git_config_from_file(fn, path, data);
> -               free(path);
> +       if (!opts->ignore_worktree && repo_config && opts->git_dir) {

What happens when opts->git_dir is NULL?  (Does that ever even
happen?)  Should it fall back to the old code path in that case?

> +               struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
> +               struct strbuf buf = STRBUF_INIT;
> +
> +               read_repository_format(&repo_fmt, repo_config);
> +
> +               if (!verify_repository_format(&repo_fmt, &buf) &&
> +                   repo_fmt.worktree_config) {
> +                       char *path = mkpathdup("%s/config.worktree", opts->git_dir);
> +                       if (!access_or_die(path, R_OK, 0))
> +                               ret += git_config_from_file(fn, path, data);
> +                       free(path);
> +               }
> +
> +               strbuf_release(&buf);
> +               clear_repository_format(&repo_fmt);

I've tried to poke around a little at this block, but as with the
previous series, I still feel like it should be reviewed by someone
who knows submodules and/or config handling better.  That's easier now
that the patch has been split up.  Unfortunately, trying to figure out
who the submodule expert(s) are (looking at authors of
submodule*.[ch]) seems to lead me to a who's who of people who are no
longer active in the project.  :-(  Maybe Peff or jrnieder would have
suggestions; cc'ing them.

>         }
>
>         current_parsing_scope = CONFIG_SCOPE_COMMAND;
> diff --git a/t/helper/test-config.c b/t/helper/test-config.c
> index 61da2574c5..284f83a921 100644
> --- a/t/helper/test-config.c
> +++ b/t/helper/test-config.c
> @@ -2,12 +2,19 @@
>  #include "cache.h"
>  #include "config.h"
>  #include "string-list.h"
> +#include "submodule-config.h"
>
>  /*
>   * This program exposes the C API of the configuration mechanism
>   * as a set of simple commands in order to facilitate testing.
>   *
> - * Reads stdin and prints result of command to stdout:
> + * Usage: test-tool config [--submodule=<path>] <cmd> [<args>]
> + *
> + * If --submodule=<path> is given, <cmd> will operate on the submodule at the
> + * given <path>. This option is not valid for the commands: read_early_config,
> + * configset_get_value and configset_get_value_multi.
> + *
> + * Possible cmds are:
>   *
>   * get_value -> prints the value with highest priority for the entered key
>   *
> @@ -86,6 +93,8 @@ int cmd__config(int argc, const char **argv)
>         const struct string_list *strptr;
>         struct config_set cs = { .hash_initialized = 0 };
>         enum test_config_exit_code ret = TC_SUCCESS;
> +       struct repository *repo = the_repository;
> +       const char *subrepo_path = NULL;
>
>         argc--; /* skip over "config" */
>         argv++;
> @@ -93,7 +102,18 @@ int cmd__config(int argc, const char **argv)
>         if (argc == 0)
>                 goto print_usage_error;
>
> +       if (skip_prefix(*argv, "--submodule=", &subrepo_path)) {
> +               argc--;
> +               argv++;
> +               if (argc == 0)
> +                       goto print_usage_error;
> +       }
> +
>         if (argc == 2 && !strcmp(argv[0], "read_early_config")) {
> +               if (subrepo_path) {
> +                       fprintf(stderr, "Cannot use --submodule with read_early_config\n");
> +                       return TC_USAGE_ERROR;
> +               }
>                 read_early_config(early_config_cb, (void *)argv[1]);
>                 return TC_SUCCESS;
>         }
> @@ -101,8 +121,23 @@ int cmd__config(int argc, const char **argv)
>         setup_git_directory();
>         git_configset_init(&cs);
>
> +       if (subrepo_path) {
> +               const struct submodule *sub;
> +               struct repository *subrepo = xcalloc(1, sizeof(*repo));
> +
> +               sub = submodule_from_path(the_repository, &null_oid, subrepo_path);
> +               if (!sub || repo_submodule_init(subrepo, the_repository, sub)) {
> +                       fprintf(stderr, "Invalid argument to --submodule: '%s'\n",
> +                               subrepo_path);
> +                       free(subrepo);
> +                       ret = TC_USAGE_ERROR;
> +                       goto out;
> +               }
> +               repo = subrepo;
> +       }
> +
>         if (argc == 2 && !strcmp(argv[0], "get_value")) {
> -               if (!git_config_get_value(argv[1], &v)) {
> +               if (!repo_config_get_value(repo, argv[1], &v)) {
>                         if (!v)
>                                 printf("(NULL)\n");
>                         else
> @@ -112,7 +147,7 @@ int cmd__config(int argc, const char **argv)
>                         ret = TC_VALUE_NOT_FOUND;
>                 }
>         } else if (argc == 2 && !strcmp(argv[0], "get_value_multi")) {
> -               strptr = git_config_get_value_multi(argv[1]);
> +               strptr = repo_config_get_value_multi(repo, argv[1]);
>                 if (strptr) {
>                         for (i = 0; i < strptr->nr; i++) {
>                                 v = strptr->items[i].string;
> @@ -126,27 +161,33 @@ int cmd__config(int argc, const char **argv)
>                         ret = TC_VALUE_NOT_FOUND;
>                 }
>         } else if (argc == 2 && !strcmp(argv[0], "get_int")) {
> -               if (!git_config_get_int(argv[1], &val)) {
> +               if (!repo_config_get_int(repo, argv[1], &val)) {
>                         printf("%d\n", val);
>                 } else {
>                         printf("Value not found for \"%s\"\n", argv[1]);
>                         ret = TC_VALUE_NOT_FOUND;
>                 }
>         } else if (argc == 2 && !strcmp(argv[0], "get_bool")) {
> -               if (!git_config_get_bool(argv[1], &val)) {
> +               if (!repo_config_get_bool(repo, argv[1], &val)) {
>                         printf("%d\n", val);
>                 } else {
> +
>                         printf("Value not found for \"%s\"\n", argv[1]);
>                         ret = TC_VALUE_NOT_FOUND;
>                 }
>         } else if (argc == 2 && !strcmp(argv[0], "get_string")) {
> -               if (!git_config_get_string_const(argv[1], &v)) {
> +               if (!repo_config_get_string_const(repo, argv[1], &v)) {
>                         printf("%s\n", v);
>                 } else {
>                         printf("Value not found for \"%s\"\n", argv[1]);
>                         ret = TC_VALUE_NOT_FOUND;
>                 }
>         } else if (argc >= 2 && !strcmp(argv[0], "configset_get_value")) {
> +               if (subrepo_path) {
> +                       fprintf(stderr, "Cannot use --submodule with configset_get_value\n");
> +                       ret = TC_USAGE_ERROR;
> +                       goto out;
> +               }
>                 for (i = 2; i < argc; i++) {
>                         int err;
>                         if ((err = git_configset_add_file(&cs, argv[i]))) {
> @@ -165,6 +206,11 @@ int cmd__config(int argc, const char **argv)
>                         ret = TC_VALUE_NOT_FOUND;
>                 }
>         } else if (argc >= 2 && !strcmp(argv[0], "configset_get_value_multi")) {
> +               if (subrepo_path) {
> +                       fprintf(stderr, "Cannot use --submodule with configset_get_value_multi\n");
> +                       ret = TC_USAGE_ERROR;
> +                       goto out;
> +               }
>                 for (i = 2; i < argc; i++) {
>                         int err;
>                         if ((err = git_configset_add_file(&cs, argv[i]))) {
> @@ -187,14 +233,19 @@ int cmd__config(int argc, const char **argv)
>                         ret = TC_VALUE_NOT_FOUND;
>                 }
>         } else if (!strcmp(argv[0], "iterate")) {
> -               git_config(iterate_cb, NULL);
> +               repo_config(repo, iterate_cb, NULL);
>         } else {
>  print_usage_error:
> -               fprintf(stderr, "Invalid syntax. Usage: test-tool config <cmd> [args]\n");
> +               fprintf(stderr, "Invalid syntax. Usage: test-tool config"
> +                               " [--submodule=<path>] <cmd> [args]\n");
>                 ret = TC_USAGE_ERROR;
>         }
>
>  out:
>         git_configset_clear(&cs);
> +       if (repo != the_repository) {
> +               repo_clear(repo);
> +               free(repo);
> +       }
>         return ret;
>  }
> diff --git a/t/t2404-worktree-config.sh b/t/t2404-worktree-config.sh
> index 286121d8de..b6ab793203 100755
> --- a/t/t2404-worktree-config.sh
> +++ b/t/t2404-worktree-config.sh
> @@ -76,4 +76,20 @@ test_expect_success 'config.worktree no longer read without extension' '
>         test_cmp_config -C wt2 shared this.is
>  '
>
> +test_expect_success 'correctly read config.worktree from submodules' '
> +       test_unconfig extensions.worktreeConfig &&
> +       git init sub &&
> +       (
> +               cd sub &&
> +               test_commit A &&
> +               git config extensions.worktreeConfig true &&
> +               git config --worktree wtconfig.sub test-value
> +       ) &&
> +       git submodule add ./sub &&
> +       git commit -m "add sub" &&
> +       echo test-value >expect &&
> +       test-tool config --submodule=sub get_value wtconfig.sub >actual &&
> +       test_cmp expect actual
> +'
> +
>  test_done
> --
> 2.26.2

```

## Elijah Newren, 2020-06-16 22:31

Subject: Re: [PATCH v4 0/6] grep: honor sparse checkout and add option to ignore it
Message-ID: <CABPp-BEJsY6ut0Xqk+vD++0wuqgu=oG_xRA-D7tO4Fsu-piujg@mail.gmail.com>
URL: https://gitlist.dev/e/CABPp-BEJsY6ut0Xqk%2BvD%2B%2B0wuqgu%3DoG_xRA-D7tO4Fsu-piujg%40mail.gmail.com
In-Reply-To: <cover.1591974940.git.matheus.bernardino@usp.br>

```
On Fri, Jun 12, 2020 at 8:45 AM Matheus Tavares
<matheus.bernardino@usp.br> wrote:
>
> This series makes git-grep restrict its output to the present sparsity
> patterns. A new global option is added to toggle this behavior in grep
> and hopefully more commands in the future.

You've cleaned up all the issues (or corrected my understanding) from
my comments in the previous iterations of this series; I didn't spot
any additional issues in reading over this latest version of the
series.

However, I would like someone more familiar with submodules and/or
config to take a look at the changes to do_git_config_sequence() in
patch 4, as I commented on there, if we can find someone to do so.

Thanks for working on this; nice work!

Elijah

```

## Matheus Tavares Bernardino, 2020-06-21 16:05

Subject: Re: [PATCH v4 4/6] config: correctly read worktree configs in submodules
Message-ID: <CAHd-oW5vKQMuVEtcnoqYARTAZz4M5bSt+j3R=z_iFcH4-oU6FQ@mail.gmail.com>
URL: https://gitlist.dev/e/CAHd-oW5vKQMuVEtcnoqYARTAZz4M5bSt%2Bj3R%3Dz_iFcH4-oU6FQ%40mail.gmail.com
In-Reply-To: <CABPp-BGdEyEeajYZj_rdxp=MyEQdszuyjVTax=hhYj3fOtRQUQ@mail.gmail.com>

```
On Tue, Jun 16, 2020 at 4:13 PM Elijah Newren <newren@gmail.com> wrote:
>
> On Fri, Jun 12, 2020 at 8:45 AM Matheus Tavares
> <matheus.bernardino@usp.br> wrote:
> >
> >  config.c                   | 21 +++++++++---
> >  t/helper/test-config.c     | 67 +++++++++++++++++++++++++++++++++-----
> >  t/t2404-worktree-config.sh | 16 +++++++++
> >  3 files changed, 91 insertions(+), 13 deletions(-)
> >
> > diff --git a/config.c b/config.c
> > index 8db9c77098..c2d56309dc 100644
> > --- a/config.c
> > +++ b/config.c
> > @@ -1747,11 +1747,22 @@ static int do_git_config_sequence(const struct config_options *opts,
> >                 ret += git_config_from_file(fn, repo_config, data);
> >
> >         current_parsing_scope = CONFIG_SCOPE_WORKTREE;
> > -       if (!opts->ignore_worktree && repository_format_worktree_config) {
> > -               char *path = git_pathdup("config.worktree");
> > -               if (!access_or_die(path, R_OK, 0))
> > -                       ret += git_config_from_file(fn, path, data);
> > -               free(path);
> > +       if (!opts->ignore_worktree && repo_config && opts->git_dir) {
>
> What happens when opts->git_dir is NULL?  (Does that ever even
> happen?)  Should it fall back to the old code path in that case?

Sorry for not replying earlier.

Yes, opts->git_dir might be NULL in some cases. I did a quick grep
search, though, and it seems that this only happens in two
circumstances: (1) in builtin/config.c when
startup_info->have_repository is false; and (2) in
read_early_config(), if have_git_dir() returns false and
discover_git_directory() fails.

For (2), I think it is right to ignore the worktree config file when
opts->git_dir is NULL because we indeed don't have a repo to read the
file from. I'm tempted to say the same for (1), but I'm not very
familiar with setup.c. By the definition of have_git_dir() it seems
possible to have the_repository->git_dir set up even when
startup_info->have_repository == false:

int have_git_dir(void)
{
        return startup_info->have_repository
                || the_repository->gitdir;
}

Nevertheless, the current calls to config_with_options() either set
both opts->git_dir and opts->commondir or none. So if we were to fall
back to the_repository->git_dir, for the worktree config, when
startup_info->have_repository == false, the local config file would
still be ignored during the config sequence in such case. I think it
wouldn't make much sense to ignore the local config file but try to
load the worktree-specific one, which is also dependent on having a
repo, and even more specific. So I think we shouldn't fall back to the
old code path. But I would appreciate hearing from others more
familiar with this code.

```

## Jonathan Nieder, 2020-09-01 02:41

Subject: Re: [PATCH v4 4/6] config: correctly read worktree configs in submodules
Message-ID: <20200901024130.GA3332286@google.com>
URL: https://gitlist.dev/e/20200901024130.GA3332286%40google.com
In-Reply-To: <6402c968077900d48d189551a652e10984437a9f.1591974940.git.matheus.bernardino@usp.br>

```
Hi,

Matheus Tavares wrote:

> One of the steps in do_git_config_sequence() is to load the
> worktree-specific config file. Although the function receives a git_dir
> string, it relies on git_pathdup(), which uses the_repository->git_dir,
> to make the path to the file. Furthermore, it also checks that
> extensions.worktreeConfig is set through the
> repository_format_worktree_config variable, which refers to
> the_repository only. Thus, when a submodule has worktree-specific
> settings, a command executed in the superproject that recurses into the
> submodule won't find the said settings.

I think the above goes out of order: it states the "how" before the
"what".  Instead, a commit message should lead with the problem the
change aims to solve.

Is the idea here that until this patch, we're only able to read
worktree config from a repository when extensions.worktreeConfig is
set in the_repository, meaning that

- when examining submodule config in a process where the_repository
  represents the superproject, we do not read the submodule's worktree
  config even if extensions.worktreeConfig is set in the submodule,
  unless the superproject has extensions.worktreeConfig set, and

- when examining submodule config in a process where the_repository
  represents the superproject, we *do* read the submodule's worktree
  config even if extensions.worktreeConfig is not set in the submodule,
  if the superproject has extensions.worktreeConfig set, and

?

That sounds like a serious problem indeed.  Thanks for fixing it.

> This will be especially important in the next patch: git-grep will learn
> to honor sparse checkouts and, when running with --recurse-submodules,
> the submodule's sparse checkout settings must be loaded. As these
> settings are stored in the config.worktree file, they would be ignored
> without this patch. So let's fix this by reading the right
> config.worktree file and extensions.worktreeConfig setting, based on the
> git_dir and commondir paths given to do_git_config_sequence(). Also
> add a test to avoid any regressions.

I see.  I'm not sure that's more important than other cases, but I
can understand if the problem was noticed in this circumstance. :)

> Signed-off-by: Matheus Tavares <matheus.bernardino@usp.br>
> ---
>  config.c                   | 21 +++++++++---
>  t/helper/test-config.c     | 67 +++++++++++++++++++++++++++++++++-----
>  t/t2404-worktree-config.sh | 16 +++++++++
>  3 files changed, 91 insertions(+), 13 deletions(-)
> 
> diff --git a/config.c b/config.c
> index 8db9c77098..c2d56309dc 100644
> --- a/config.c
> +++ b/config.c
> @@ -1747,11 +1747,22 @@ static int do_git_config_sequence(const struct config_options *opts,
>  		ret += git_config_from_file(fn, repo_config, data);
>  
>  	current_parsing_scope = CONFIG_SCOPE_WORKTREE;
> -	if (!opts->ignore_worktree && repository_format_worktree_config) {
> +	if (!opts->ignore_worktree && repo_config && opts->git_dir) {

Can we eliminate the repository_format_worktree_config global to save
the next caller from the same problem?

> +		struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
> +		struct strbuf buf = STRBUF_INIT;
> +
> +		read_repository_format(&repo_fmt, repo_config);
> +
> +		if (!verify_repository_format(&repo_fmt, &buf) &&
> +		    repo_fmt.worktree_config) {

This undoes the caching the repository_format_worktree_config means to
do.  Can we cache the value in "struct repository" instead?  That way,
in the common case where we're reading the_repository, we wouldn't
experience a slowdown.

> -		char *path = git_pathdup("config.worktree");
> +			char *path = mkpathdup("%s/config.worktree", opts->git_dir);

Can this use a helper like repo_git_path or strbuf_repo_git_path
(preferably one using strbuf like the latter)?

[...]
> +		strbuf_release(&buf);
> +		clear_repository_format(&repo_fmt);
>  	}
>  
>  	current_parsing_scope = CONFIG_SCOPE_COMMAND;
> diff --git a/t/helper/test-config.c b/t/helper/test-config.c
> index 61da2574c5..284f83a921 100644
> --- a/t/helper/test-config.c
> +++ b/t/helper/test-config.c
> @@ -2,12 +2,19 @@
>  #include "cache.h"
>  #include "config.h"
>  #include "string-list.h"
> +#include "submodule-config.h"
>  
>  /*
>   * This program exposes the C API of the configuration mechanism
>   * as a set of simple commands in order to facilitate testing.
>   *
> - * Reads stdin and prints result of command to stdout:
> + * Usage: test-tool config [--submodule=<path>] <cmd> [<args>]
> + *
> + * If --submodule=<path> is given, <cmd> will operate on the submodule at the
> + * given <path>. This option is not valid for the commands: read_early_config,
> + * configset_get_value and configset_get_value_multi.

Nice!

[...]
> @@ -93,7 +102,18 @@ int cmd__config(int argc, const char **argv)
>  	if (argc == 0)
>  		goto print_usage_error;
>  
> +	if (skip_prefix(*argv, "--submodule=", &subrepo_path)) {
> +		argc--;
> +		argv++;
> +		if (argc == 0)
> +			goto print_usage_error;
> +	}

Can this use the parse_options API?

> +
>  	if (argc == 2 && !strcmp(argv[0], "read_early_config")) {
> +		if (subrepo_path) {
> +			fprintf(stderr, "Cannot use --submodule with read_early_config\n");
> +			return TC_USAGE_ERROR;

Should this use die() or BUG()?

> +		}
>  		read_early_config(early_config_cb, (void *)argv[1]);
>  		return TC_SUCCESS;
>  	}
> @@ -101,8 +121,23 @@ int cmd__config(int argc, const char **argv)
>  	setup_git_directory();
>  	git_configset_init(&cs);
>  
> +	if (subrepo_path) {
> +		const struct submodule *sub;
> +		struct repository *subrepo = xcalloc(1, sizeof(*repo));

nit: this could be scoped to cmd__config:

	struct repository subrepo = {0};

> +
> +		sub = submodule_from_path(the_repository, &null_oid, subrepo_path);
> +		if (!sub || repo_submodule_init(subrepo, the_repository, sub)) {
> +			fprintf(stderr, "Invalid argument to --submodule: '%s'\n",
> +				subrepo_path);
> +			free(subrepo);
> +			ret = TC_USAGE_ERROR;

Likewise: I think may want to use die() or BUG() (and likewise for other
USAGE_ERROR cases).

Thanks and hope that helps,
Jonathan

```

## Matheus Tavares Bernardino, 2020-09-01 21:44

Subject: Re: [PATCH v4 4/6] config: correctly read worktree configs in submodules
Message-ID: <CAHd-oW6LA7Ovnu-e9c+WapF-e+JMichWZEetxmnbjCT_H6D0AQ@mail.gmail.com>
URL: https://gitlist.dev/e/CAHd-oW6LA7Ovnu-e9c%2BWapF-e%2BJMichWZEetxmnbjCT_H6D0AQ%40mail.gmail.com
In-Reply-To: <20200901024130.GA3332286@google.com>

```
Hi, Jonathan

On Mon, Aug 31, 2020 at 11:41 PM Jonathan Nieder <jrnieder@gmail.com> wrote:
>
> Hi,
>
> Matheus Tavares wrote:
>
> > One of the steps in do_git_config_sequence() is to load the
> > worktree-specific config file. Although the function receives a git_dir
> > string, it relies on git_pathdup(), which uses the_repository->git_dir,
> > to make the path to the file. Furthermore, it also checks that
> > extensions.worktreeConfig is set through the
> > repository_format_worktree_config variable, which refers to
> > the_repository only. Thus, when a submodule has worktree-specific
> > settings, a command executed in the superproject that recurses into the
> > submodule won't find the said settings.
>
> I think the above goes out of order: it states the "how" before the
> "what".  Instead, a commit message should lead with the problem the
> change aims to solve.

Thanks. I will reorder these two sections in the commit message.

> Is the idea here that until this patch, we're only able to read
> worktree config from a repository when extensions.worktreeConfig is
> set in the_repository, meaning that
>
> - when examining submodule config in a process where the_repository
>   represents the superproject, we do not read the submodule's worktree
>   config even if extensions.worktreeConfig is set in the submodule,
>   unless the superproject has extensions.worktreeConfig set, and

Right.

> - when examining submodule config in a process where the_repository
>   represents the superproject, we *do* read the submodule's worktree
>   config even if extensions.worktreeConfig is not set in the submodule,
>   if the superproject has extensions.worktreeConfig set, and
>
> ?

Right, but with one change: if extensions.worktreeConfig is not set in
the submodule and it is set in the superproject, the *superproject's*
worktree config is read (independently of which git_dir was given as
argument).

> That sounds like a serious problem indeed.  Thanks for fixing it.
>
> > This will be especially important in the next patch: git-grep will learn
> > to honor sparse checkouts and, when running with --recurse-submodules,
> > the submodule's sparse checkout settings must be loaded. As these
> > settings are stored in the config.worktree file, they would be ignored
> > without this patch. So let's fix this by reading the right
> > config.worktree file and extensions.worktreeConfig setting, based on the
> > git_dir and commondir paths given to do_git_config_sequence(). Also
> > add a test to avoid any regressions.
>
> I see.  I'm not sure that's more important than other cases, but I
> can understand if the problem was noticed in this circumstance. :)
>
> > Signed-off-by: Matheus Tavares <matheus.bernardino@usp.br>
> > ---
> >  config.c                   | 21 +++++++++---
> >  t/helper/test-config.c     | 67 +++++++++++++++++++++++++++++++++-----
> >  t/t2404-worktree-config.sh | 16 +++++++++
> >  3 files changed, 91 insertions(+), 13 deletions(-)
> >
> > diff --git a/config.c b/config.c
> > index 8db9c77098..c2d56309dc 100644
> > --- a/config.c
> > +++ b/config.c
> > @@ -1747,11 +1747,22 @@ static int do_git_config_sequence(const struct config_options *opts,
> >               ret += git_config_from_file(fn, repo_config, data);
> >
> >       current_parsing_scope = CONFIG_SCOPE_WORKTREE;
> > -     if (!opts->ignore_worktree && repository_format_worktree_config) {
> > +     if (!opts->ignore_worktree && repo_config && opts->git_dir) {
>
> Can we eliminate the repository_format_worktree_config global to save
> the next caller from the same problem?

Hmm, I think it's possible, I will investigate it further.

> > +             struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
> > +             struct strbuf buf = STRBUF_INIT;
> > +
> > +             read_repository_format(&repo_fmt, repo_config);
> > +
> > +             if (!verify_repository_format(&repo_fmt, &buf) &&
> > +                 repo_fmt.worktree_config) {
>
> This undoes the caching the repository_format_worktree_config means to
> do.  Can we cache the value in "struct repository" instead?  That way,
> in the common case where we're reading the_repository, we wouldn't
> experience a slowdown.

Yeah, that would be the best solution. But, unfortunately,
do_git_config_sequence() doesn't receive a complete repository struct,
just the 'commondir' and 'git_dir' strings.

> > -             char *path = git_pathdup("config.worktree");
> > +                     char *path = mkpathdup("%s/config.worktree", opts->git_dir);
>
> Can this use a helper like repo_git_path or strbuf_repo_git_path
> (preferably one using strbuf like the latter)?

Hmm, here we would have the same problem of not having a 'struct
repository' to pass to those functions :(

> [...]
> > +             strbuf_release(&buf);
> > +             clear_repository_format(&repo_fmt);
> >       }
> >
> >       current_parsing_scope = CONFIG_SCOPE_COMMAND;
> > diff --git a/t/helper/test-config.c b/t/helper/test-config.c
> > index 61da2574c5..284f83a921 100644
> > --- a/t/helper/test-config.c
> > +++ b/t/helper/test-config.c
> > @@ -2,12 +2,19 @@
> >  #include "cache.h"
> >  #include "config.h"
> >  #include "string-list.h"
> > +#include "submodule-config.h"
> >
> >  /*
> >   * This program exposes the C API of the configuration mechanism
> >   * as a set of simple commands in order to facilitate testing.
> >   *
> > - * Reads stdin and prints result of command to stdout:
> > + * Usage: test-tool config [--submodule=<path>] <cmd> [<args>]
> > + *
> > + * If --submodule=<path> is given, <cmd> will operate on the submodule at the
> > + * given <path>. This option is not valid for the commands: read_early_config,
> > + * configset_get_value and configset_get_value_multi.
>
> Nice!
>
> [...]
> > @@ -93,7 +102,18 @@ int cmd__config(int argc, const char **argv)
> >       if (argc == 0)
> >               goto print_usage_error;
> >
> > +     if (skip_prefix(*argv, "--submodule=", &subrepo_path)) {
> > +             argc--;
> > +             argv++;
> > +             if (argc == 0)
> > +                     goto print_usage_error;
> > +     }
>
> Can this use the parse_options API?

Right, it would make it easier to add more options in the future.
There is only one consideration, though, about parse_options()'s exit
codes on error, but more on that below...

> > +
> >       if (argc == 2 && !strcmp(argv[0], "read_early_config")) {
> > +             if (subrepo_path) {
> > +                     fprintf(stderr, "Cannot use --submodule with read_early_config\n");
> > +                     return TC_USAGE_ERROR;
>
> Should this use die() or BUG()?

The idea of using TC_USAGE_ERROR (129) here and not die() (128), was
that some users of the test-config helper want to detect die() errors
from the config machinery itself. So by using a different exit code,
we can avoid false positives in these tests. Of course they should
also be checking stderr/stdout, but there is at least one test which
only checks the exit code. Rethinking about that now, instead of using
different exit codes in test-config.c, should we adjust the tests to
use `test_must_fail` and only check stderr/stdout? Then we could use
die() (or BUG()) here, as you suggested, as well as the parse_options
API in the snippet above. Does that sound reasonable?

> > +             }
> >               read_early_config(early_config_cb, (void *)argv[1]);
> >               return TC_SUCCESS;
> >       }
> > @@ -101,8 +121,23 @@ int cmd__config(int argc, const char **argv)
> >       setup_git_directory();
> >       git_configset_init(&cs);
> >
> > +     if (subrepo_path) {
> > +             const struct submodule *sub;
> > +             struct repository *subrepo = xcalloc(1, sizeof(*repo));
>
> nit: this could be scoped to cmd__config:
>
>         struct repository subrepo = {0};

OK, will do. Thanks

> > +
> > +             sub = submodule_from_path(the_repository, &null_oid, subrepo_path);
> > +             if (!sub || repo_submodule_init(subrepo, the_repository, sub)) {
> > +                     fprintf(stderr, "Invalid argument to --submodule: '%s'\n",
> > +                             subrepo_path);
> > +                     free(subrepo);
> > +                     ret = TC_USAGE_ERROR;
>
> Likewise: I think may want to use die() or BUG() (and likewise for other
> USAGE_ERROR cases).
>
> Thanks and hope that helps,
> Jonathan

It did :) Thanks a lot for the comments!

```
