Simplify the recursive-search check and kill the mutants of its option parsing
This commit is contained in:
+22
-15
@@ -14,7 +14,7 @@ from rule_hook.call import Call, text
|
||||
from project_config.settings import env_files
|
||||
from failure import Failure
|
||||
from rule_hook.git import guarded_git
|
||||
from command_lines.shell_command import Launch, launched, lexed, OPERATOR, resolved, Simple, simple_commands
|
||||
from command_lines.shell_command import launched, lexed, OPERATOR, resolved, simple_commands
|
||||
|
||||
# Tools that search a folder's files: grep only given an option that makes it recursive, rg and ag always.
|
||||
GREPS = frozenset({"egrep", "fgrep", "grep"})
|
||||
@@ -90,37 +90,44 @@ def searches(command: str, cwd: str, home: str, path: pathlib.Path) -> bool:
|
||||
if launch.tool in GREPS and not any(RECURSIVE_GREP.fullmatch(option) or option.endswith("recurse") for option in [*options, *operands]):
|
||||
continue
|
||||
globs = globs_of(launch.arguments) if launch.tool == "rg" else []
|
||||
if any(holds(folder, path) and not skips(launch.tool, options, globs, folder, path) for folder in folders(simple, launch, options, operands, home)):
|
||||
if any(holds(folder, path) and not skips(launch.tool, options, globs, folder, path) for folder in folders(simple.directory, options, operands, home)):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
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."""
|
||||
end = arguments.index("--") if "--" in arguments else len(arguments)
|
||||
options = [word for word in arguments[:end] if word.startswith("-") and word != "-"]
|
||||
return options, [word for word in arguments[:end] if word not in options] + arguments[end + 1:]
|
||||
options: list[str] = []
|
||||
operands: list[str] = []
|
||||
ended = False
|
||||
for word in arguments:
|
||||
if ended or not word.startswith("-"):
|
||||
operands.append(word)
|
||||
elif word == "--":
|
||||
ended = True
|
||||
else:
|
||||
options.append(word)
|
||||
return options, operands
|
||||
|
||||
|
||||
def folders(simple: Simple, launch: Launch, options: list[str], operands: list[str], home: str) -> list[str]:
|
||||
def folders(directory: str, options: list[str], operands: list[str], home: str) -> list[str]:
|
||||
"""The folders a search reads: its operands that are folders, or the directory it runs in where none names a file or a folder. An option's value is an operand here; one that names no file or folder is dropped like any word that does not."""
|
||||
if not any(PATTERN_OPTION.fullmatch(option) for option in options):
|
||||
# The first operand is the pattern.
|
||||
operands = operands[1:]
|
||||
named = [resolved(simple.directory, home_word(operand), home) for operand in operands]
|
||||
named = [resolved(directory, home_word(operand), home) for operand in operands]
|
||||
existing = [word for word in named if os.path.exists(word)]
|
||||
return [word for word in existing if os.path.isdir(word)] if existing else [simple.directory]
|
||||
return [word for word in existing if os.path.isdir(word)] if existing else [directory]
|
||||
|
||||
|
||||
def globs_of(arguments: list[str]) -> list[str]:
|
||||
"""The globs of rg's -g, --glob and --iglob options; --iglob's matching without regard to case is not translated."""
|
||||
found = []
|
||||
for at, word in enumerate(arguments):
|
||||
option = GLOB_OPTION.fullmatch(word)
|
||||
if option:
|
||||
given = option.group(1) or option.group(2)
|
||||
glob = given if given else "".join(arguments[at + 1:at + 2])
|
||||
# --iglob matches without regard to case, which globbed() does not translate; braces make it count as matching.
|
||||
found.append("{" + glob + "}" if word.startswith("--iglob") else glob)
|
||||
found.append(given if given else arguments[at + 1] if at + 1 < len(arguments) else "")
|
||||
return found
|
||||
|
||||
|
||||
@@ -132,14 +139,14 @@ def skips(tool: str, options: list[str], globs: list[str], folder: str, path: pa
|
||||
if positive:
|
||||
return not any(globbed(glob, folder, path) for glob in positive)
|
||||
long = [option for option in options if option.startswith("--")]
|
||||
short = "".join(option[1:] for option in options if not option.startswith("--"))
|
||||
unrestricted = short.count("u") + long.count("--unrestricted")
|
||||
clusters = [option[1:] for option in options if not option.startswith("--")]
|
||||
unrestricted = sum(cluster.count("u") for cluster in clusters) + long.count("--unrestricted")
|
||||
if tool == "rg":
|
||||
hidden_lifted = "--hidden" in long or "." in short or unrestricted >= 2
|
||||
hidden_lifted = "--hidden" in long or any("." in cluster for cluster in clusters) or unrestricted >= 2
|
||||
ignored_lifted = unrestricted >= 1 or any(option.startswith("--no-ignore") for option in long)
|
||||
else:
|
||||
hidden_lifted = "--hidden" in long or unrestricted >= 1
|
||||
ignored_lifted = unrestricted >= 1 or "U" in short or "a" in short or "--skip-vcs-ignores" in long or "--all-types" in long
|
||||
ignored_lifted = unrestricted >= 1 or any("U" in cluster or "a" in cluster for cluster in clusters) or "--skip-vcs-ignores" in long or "--all-types" in long
|
||||
return (hidden_below(folder, path) and not hidden_lifted) or (ignored(path) and not ignored_lifted)
|
||||
|
||||
|
||||
|
||||
@@ -465,6 +465,8 @@ 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",
|
||||
"grep -d recurse 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 TOKEN x; rg TOKEN ~/secrets", "echo hi && ag TOKEN ~/secrets",
|
||||
)
|
||||
for command in commands:
|
||||
with self.subTest(command):
|
||||
@@ -483,9 +485,19 @@ class EnvFileRead(unittest.TestCase):
|
||||
with self.subTest(command):
|
||||
self.assertEqual(self.breached("Bash", {"command": command}), [])
|
||||
self.assertEqual(self.breached("Bash", {"command": "rg TOKEN"}, f"{self.home}/code"), [])
|
||||
# secrets is the pattern, not the folder ~/secrets that the home directory holds.
|
||||
self.assertEqual(self.breached("Bash", {"command": "rg secrets ~/code"}, str(self.home)), [])
|
||||
|
||||
def test_a_folder_that_starts_with_a_dash_is_searched_after_double_dash(self):
|
||||
write_config(self.home, self.home / "code" / "other")
|
||||
config = self.home / ".claude-projects" / "other" / "config.toml"
|
||||
config.write_text(config.read_text() + 'env-file = "~/-d/x.env"\n')
|
||||
(self.home / "-d").mkdir()
|
||||
(self.home / "-d" / "x.env").write_text("TOKEN=z\n")
|
||||
self.assertEqual(self.breached("Bash", {"command": "rg TOKEN -- -d"}, str(self.home)), ["env-file-read"])
|
||||
|
||||
def test_rg_and_ag_skip_hidden_files_but_grep_does_not(self):
|
||||
for command, expected in (("rg TOKEN ~/.claude", []), ("ag TOKEN ~/.claude", []), ("grep -r TOKEN ~/.claude", ["env-file-read"]), ("rg --hidden TOKEN ~/.claude", ["env-file-read"]), ("rg -. TOKEN ~/.claude", ["env-file-read"]), ("rg -uu TOKEN ~/.claude", ["env-file-read"]), ("ag --hidden TOKEN ~/.claude", ["env-file-read"]), ("ag -u TOKEN ~/.claude", ["env-file-read"])):
|
||||
for command, expected in (("rg TOKEN ~/.claude", []), ("ag TOKEN ~/.claude", []), ("grep -r TOKEN ~/.claude", ["env-file-read"]), ("rg --hidden TOKEN ~/.claude", ["env-file-read"]), ("rg -. TOKEN ~/.claude", ["env-file-read"]), ("rg -uu TOKEN ~/.claude", ["env-file-read"]), ("rg -u -u TOKEN ~/.claude", ["env-file-read"]), ("rg --unrestricted TOKEN ~/.claude", []), ("rg --unrestricted --unrestricted TOKEN ~/.claude", ["env-file-read"]), ("ag --hidden TOKEN ~/.claude", ["env-file-read"]), ("ag -u TOKEN ~/.claude", ["env-file-read"])):
|
||||
with self.subTest(command):
|
||||
self.assertEqual(self.breached("Bash", {"command": command}), expected)
|
||||
|
||||
@@ -500,20 +512,30 @@ class EnvFileRead(unittest.TestCase):
|
||||
(self.home / "code").mkdir()
|
||||
self.assertEqual(self.breached("Bash", {"command": "rg TOKEN ~/code"}), [])
|
||||
|
||||
def test_rg_and_ag_skip_a_file_below_any_hidden_folder_of_the_search(self):
|
||||
write_config(self.home, self.home / "code" / "other")
|
||||
config = self.home / ".claude-projects" / "other" / "config.toml"
|
||||
config.write_text(config.read_text() + 'env-file = "~/outer/deep/.h/b.env"\n')
|
||||
(self.home / "outer" / "deep" / ".h").mkdir(parents=True)
|
||||
(self.home / "outer" / "deep" / ".h" / "b.env").write_text("TOKEN=z\n")
|
||||
for command, expected in (("rg TOKEN ~/outer", []), ("ag TOKEN ~/outer", []), ("rg --hidden TOKEN ~/outer", ["env-file-read"]), ("grep -r TOKEN ~/outer", ["env-file-read"]), ("rg TOKEN ~/outer/deep/.h", ["env-file-read"])):
|
||||
with self.subTest(command):
|
||||
self.assertEqual(self.breached("Bash", {"command": command}), expected)
|
||||
|
||||
def test_rg_and_ag_skip_an_ignored_file_unless_an_option_or_a_glob_lifts_it(self):
|
||||
self.ignoring("secrets", "*.env\n")
|
||||
for command, expected in (
|
||||
("rg TOKEN ~/secrets", []), ("ag TOKEN ~/secrets", []), ("grep -r TOKEN ~/secrets", ["env-file-read"]),
|
||||
("rg --no-ignore TOKEN ~/secrets", ["env-file-read"]), ("rg -u TOKEN ~/secrets", ["env-file-read"]), ("rg --no-ignore-vcs TOKEN ~/secrets", ["env-file-read"]),
|
||||
("ag -U TOKEN ~/secrets", ["env-file-read"]), ("ag --skip-vcs-ignores TOKEN ~/secrets", ["env-file-read"]), ("ag -u TOKEN ~/secrets", ["env-file-read"]),
|
||||
("rg -g '*.env' TOKEN ~/secrets", ["env-file-read"]), ("rg --glob=acme.env TOKEN ~/secrets", ["env-file-read"]), ("rg --iglob '*.ENV' TOKEN ~/secrets", ["env-file-read"]),
|
||||
("rg -g '*.env' TOKEN ~/secrets", ["env-file-read"]), ("rg --glob=acme.env TOKEN ~/secrets", ["env-file-read"]), ("rg --iglob '*.env' TOKEN ~/secrets", ["env-file-read"]), ("ag -a TOKEN ~/secrets", ["env-file-read"]), ("ag --all-types TOKEN ~/secrets", ["env-file-read"]), ("rg -uu TOKEN ~/secrets", ["env-file-read"]),
|
||||
("rg -g '*.md' TOKEN ~/secrets", []), ("rg -g '!*.env' TOKEN ~/secrets", []),
|
||||
):
|
||||
with self.subTest(command):
|
||||
self.assertEqual(self.breached("Bash", {"command": command}), expected)
|
||||
|
||||
def test_rg_searches_only_the_files_a_positive_glob_matches(self):
|
||||
for command, expected in (("rg -g '*.md' TOKEN ~/secrets", []), ("rg -g '*.md' -g '*.env' TOKEN ~/secrets", ["env-file-read"]), ("rg -g '!*.md' TOKEN ~/secrets", ["env-file-read"]), ("rg -ng '*.md' TOKEN ~/secrets", [])):
|
||||
for command, expected in (("rg -g '*.md' TOKEN ~/secrets", []), ("rg -g '*.md' -g '*.env' TOKEN ~/secrets", ["env-file-read"]), ("rg -g '!*.md' TOKEN ~/secrets", ["env-file-read"]), ("rg -ng '*.md' TOKEN ~/secrets", []), ("rg --glob '*.md' TOKEN ~/secrets", []), ("rg --iglob '*.md' TOKEN ~/secrets", []), ("rg TOKEN ~/secrets -g", [])):
|
||||
with self.subTest(command):
|
||||
self.assertEqual(self.breached("Bash", {"command": command}), expected)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user