From 472b15b76dfea8c63b4eb7139310e9a68c56a805 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 13 Nov 2026 22:54:22 +0100 Subject: [PATCH] =?UTF-8?q?Answer=20stability=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=202=20=F0=9F=9F=A1=20(0=20misread);=20read=20grep?= =?UTF-8?q?=20-d=20recurse=20as=20recursive=20and=20let=20an=20rg=20path?= =?UTF-8?q?=20glob=20lift=20the=20skip?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/rule_hook/folder_search.py | 19 ++++++++++++++----- bin/rule_hook/test_rule_hook.py | 13 +++++++------ 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/bin/rule_hook/folder_search.py b/bin/rule_hook/folder_search.py index 3f6b62b3..a921db5b 100644 --- a/bin/rule_hook/folder_search.py +++ b/bin/rule_hook/folder_search.py @@ -2,6 +2,7 @@ A search reaches a file in a folder it searches unless the tool skips the file. ripgrep, which a Grep runs, and `ag` skip a file that the checkout holding it ignores; a Bash `rg` or `ag` also skips a hidden file and one below a hidden folder of the searched folder, which a Grep doesn't. `grep -r` doesn't skip any file. A glob changes what ripgrep skips, as `globbed` and `skips` say. Each judgment refuses more where it is unsure: an option it doubts lifts a skip, and a pipe's input isn't told apart from the directory, so `x | rg y` in a folder holding the file is refused too.""" +import itertools import os import pathlib import re @@ -12,8 +13,10 @@ from command_lines.shell_command import home_word, Launch, launched, resolved, s GREPS = frozenset({"egrep", "fgrep", "grep"}) SEARCHERS = GREPS | {"ag", "rg"} -# grep searches folders only with an option that makes it recursive; `-d recurse` is not read. -RECURSIVE_GREP = re.compile(r"-[^-]*[rR].*|--(?:dereference-)?recursive|--directories=recurse") +# grep searches folders only with an option that makes it recursive: -r and -R in a cluster, --recursive, and `-d recurse` as one word or two. +RECURSIVE_GREP = re.compile(r"-[^-]*[rR].*|--(?:dereference-)?recursive|--directories=recurse|-[^-]*drecurse") +# The option before a separate `recurse` word that makes grep recursive. +DIRECTORIES_OPTION = re.compile(r"-[^-]*d|--directories") # An option that gives the pattern, so that no operand is the pattern: -e and -f in a cluster, and --regexp and --file. PATTERN_OPTION = re.compile(r"-[^-]*[ef].*|--(?:regexp|file)(?:=.*)?") # rg's --glob and --iglob, and -g at the start of a word: group 1 or 2 holds the glob when it is in the same word, else it is the next word. @@ -31,13 +34,19 @@ def searches(command: str, cwd: str, home: str, path: pathlib.Path) -> bool: if launch is None: continue options, operands = split(launch.arguments) - if launch.tool in GREPS and not any(RECURSIVE_GREP.fullmatch(option) for option in options): + if launch.tool in GREPS and not recursive(launch.arguments, options): continue if any(holds(folder, path) and not skips(launch, options, folder, path) for folder in folders(simple.directory, options, operands, home)): return True return False +def recursive(arguments: list[str], options: list[str]) -> bool: + """Whether a grep's options make it search folders.""" + pairs = itertools.pairwise(arguments) + return any(RECURSIVE_GREP.fullmatch(option) for option in options) or any(value == "recurse" and DIRECTORIES_OPTION.fullmatch(option) for option, value in pairs) + + def split(arguments: list[str]) -> tuple[list[str], list[str]]: """A search's arguments as its options and its operands: the words after `--` are operands.""" options: list[str] = [] @@ -78,13 +87,13 @@ def globs_of(arguments: list[str]) -> tuple[list[str], bool]: def skips(launch: Launch, options: list[str], folder: str, path: pathlib.Path) -> bool: - """Whether the tool passes over path when it searches folder. A grep doesn't pass over any file. rg searches only the files that its globs match, where it has a glob that doesn't exclude files. Otherwise rg and ag pass over a hidden path below folder and an ignored file, unless an option lifts that.""" + """Whether the tool passes over path when it searches folder. A grep doesn't pass over any file. rg searches only the files that its globs match, where it has a glob that doesn't exclude files; a glob holding a `/` counts as matching, since rg anchors it at the directory it runs in, which is not told from the folder searched. Otherwise rg and ag pass over a hidden path below folder and an ignored file, unless an option lifts that.""" if launch.tool in GREPS: return False if launch.tool == "rg": globs, insensitive = globs_of(launch.arguments) if globs: - return not (insensitive or any(globbed(glob, folder, path) for glob in globs)) + return not (insensitive or any("/" in glob or globbed(glob, folder, path) for glob in globs)) long = [option for option in options if option.startswith("--")] clusters = [option[1:] for option in options if not option.startswith("--")] unrestricted = sum(cluster.count("u") for cluster in clusters) + long.count("--unrestricted") diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index 10bc0ac8..f4e65476 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -447,7 +447,7 @@ class EnvFileRead(unittest.TestCase): def test_a_grep_s_glob_is_refused_only_where_it_can_match_the_ignored_file(self): subprocess.run(["git", "init", "--quiet", str(self.home / ".claude")], check=True, env=isolated_env()) (self.home / ".claude" / ".gitignore").write_text(".env\n") - for glob, expected in (("**/*.md", []), ("rules/*.md", []), ("*.py", []), ("!.env", []), ("*", ["env-file-read"]), (".env*", ["env-file-read"]), ("{*.md,.env}", ["env-file-read"])): + for glob, expected in (("**/*.md", []), ("rules/*.md", []), ("*.py", []), ("!.env", []), ("*", ["env-file-read"]), (".env*", ["env-file-read"]), ("?env", ["env-file-read"]), ("?nv", []), ("{*.md,.env}", ["env-file-read"])): with self.subTest(glob): self.assertEqual(self.breached("Grep", {"pattern": "TOKEN", "path": f"{self.home}/.claude", "glob": glob}), expected) @@ -455,7 +455,7 @@ class EnvFileRead(unittest.TestCase): subprocess.run(["git", "init", "--quiet", str(self.home / ".claude")], check=True, env=isolated_env()) (self.home / ".claude" / ".gitignore").write_text(".env\n") # ~/secrets/acme.env is in no checkout, so only the ignored file's breach tells the globs apart. - for glob, refused in ((".claude/*", True), ("**/.env", True), ("/.claude/.env", True), (".claude/**", True), ("secrets/*", False), ("*/*.md", False), (".env/*", False)): + for glob, refused in ((".claude/*", True), ("**/.env", True), ("/.claude/.env", True), (".env", True), (".claude/**", True), ("secrets/*", False), ("*/*.md", False), (".env/*", False)): with self.subTest(glob): found = breaches_of(Call("Grep", {"pattern": "TOKEN", "path": str(self.home), "glob": glob}, "/r"), str(self.home), {}) self.assertEqual(any(breach.detail.startswith(f"the call reads {self.home}/.claude/.env,") for breach in found[2]), refused) @@ -470,7 +470,7 @@ class EnvFileRead(unittest.TestCase): "grep -r TOKEN ~/secrets", "grep -R TOKEN ~/secrets", "grep -rn TOKEN $HOME/secrets", "egrep -ri TOKEN ~/secrets", "fgrep --recursive TOKEN ~/secrets", "rg TOKEN ~/secrets", "rg -n TOKEN ~/secrets", "ag TOKEN ~/secrets", "nice rg TOKEN ~/secrets", "rg -e TOKEN ~/secrets", "rg -A 3 TOKEN ~/secrets", "cat x | rg -g '*.env' TOKEN ~/secrets", - "rg -eTOKEN ~/secrets", "rg --regexp=TOKEN ~/secrets", "grep -rf patterns ~/secrets", "rg TOKEN -- ~/secrets", "rg -- TOKEN ~/secrets", "ag -g '*.md' TOKEN ~/secrets", + "grep -d recurse TOKEN ~/secrets", "grep -nd recurse TOKEN ~/secrets", "grep --directories recurse TOKEN ~/secrets", "grep -drecurse TOKEN ~/secrets", "rg -eTOKEN ~/secrets", "rg --regexp=TOKEN ~/secrets", "grep -rf patterns ~/secrets", "rg TOKEN -- ~/secrets", "rg -- TOKEN ~/secrets", "ag -g '*.md' TOKEN ~/secrets", "grep TOKEN x; rg TOKEN ~/secrets", "cd ~/code && rg TOKEN ~/secrets", "rg -Tgo TOKEN ~/secrets", "rg -rgone TOKEN ~/secrets", "grep -rm1 TOKEN ~/secrets", "grep -rC2 TOKEN ~/secrets", "rg -e1 -nA3 TOKEN ~/secrets", "echo hi && ag TOKEN ~/secrets", ) for command in commands: @@ -552,10 +552,11 @@ class EnvFileRead(unittest.TestCase): with self.subTest(command): self.assertEqual(self.breached("Bash", {"command": command}), expected) - def test_a_glob_matches_a_file_below_the_searched_folder_by_name_or_by_path(self): - for command, expected in (("rg -g '*.env' TOKEN ~", ["env-file-read"]), ("rg -g 'acme.en?' TOKEN ~/secrets", ["env-file-read"]), ("rg -g '/secrets/acme.env' TOKEN ~", ["env-file-read"]), ("rg -g 'acme.enx' TOKEN ~/secrets", [])): + def test_a_path_glob_of_rg_lifts_the_skip_since_rg_anchors_it_at_the_directory_it_runs_in(self): + self.ignoring("secrets", "*.env\n") + for command in ("rg -g 'secrets/*.env' TOKEN secrets", "rg -g 'secrets/*.env' TOKEN ~/secrets", "rg -g '/secrets/*.env' TOKEN secrets"): with self.subTest(command): - self.assertEqual(self.breached("Bash", {"command": command}), expected) + self.assertEqual(self.breached("Bash", {"command": command}, str(self.home)), ["env-file-read"]) def test_a_search_s_breach_is_logged_in_the_directory_the_command_runs_in(self): found = breaches_of(Call("Bash", {"command": "grep -r TOKEN ~/secrets"}, "/r"), str(self.home), {})