diff --git a/src/openultrasast/cli.py b/src/openultrasast/cli.py index b49edc99..4c1cbe9b 100644 --- a/src/openultrasast/cli.py +++ b/src/openultrasast/cli.py @@ -55,7 +55,7 @@ from .pairs import ( select_vendored, ) from .policy import assert_rules_resolve, load_policy -from .preprocess import FileTarget, preprocess_repository, write_preprocess_artifact +from .preprocess import FileTarget, count_skipped_source_files, preprocess_repository, write_preprocess_artifact from .profiling import start as start_profiling from .provenance import fingerprint from .rank import rank_obligations, rank_targets, write_rankings @@ -598,7 +598,7 @@ def _run_scan(path: Path, config_path: Path, mode: str, fail_on: str) -> ScanOut ) write_harness_config(config=config, path=run.root / "harness.json") runtime.start(mode=mode, target=run.target) - policy, ruleset, targets, entry_points = _map_scan_targets(runtime, run, config, mode) + policy, ruleset, targets, entry_points, left_out = _map_scan_targets(runtime, run, config, mode) ledger_path = run.target / CALIBRATION_DIR / "false_positive_learnings.json" provenance = runtime.run_stage("provenance", lambda: fingerprint(run.target)) rankings = runtime.run_stage("rank", lambda: rank_targets(targets)) @@ -731,7 +731,8 @@ def _run_scan(path: Path, config_path: Path, mode: str, fail_on: str) -> ScanOut for item in runtime.state["degradations"] if item.get("reason") == "language_not_covered" ) - + prune_notices, + + prune_notices + + _skipped_files_notices(Path(config.runs_dir), left_out), ) @@ -740,21 +741,23 @@ def _map_scan_targets( run: ScanRun, config: ResolvedConfig, mode: str, -) -> tuple[dict[str, CwePolicy], tuple[PatternRule, ...], list[FileTarget], list[EntryPointRecord]]: - """The policy and ruleset the scan runs under, and the targets and entry points every later stage reads.""" +) -> tuple[dict[str, CwePolicy], tuple[PatternRule, ...], list[FileTarget], list[EntryPointRecord], int]: + """The policy and ruleset the scan runs under, the targets and entry points every later stage reads, and how + many source files the skip left out.""" policy = runtime.run_stage("policy_load", load_policy) rule_ledger_path = run.target / CALIBRATION_DIR / "rule_policy.json" ruleset = runtime.run_stage("ruleset_load", lambda: load_ruleset(DEFAULT_RULESET_DIR, rule_ledger_path)) runtime.run_stage("policy_check", lambda: assert_rules_resolve(ruleset, policy)) static_hints = runtime.run_stage("static_mapping", lambda: _load_static_hints(config.static_analysis.sarif_paths)) write_static_hints(static_hints, run.root / "mapping" / "static_hints.json") + runs_dir = Path(config.runs_dir) snapshot, targets = runtime.run_stage( "preprocess", lambda: preprocess_repository( run.target, run.root / "preprocess" / "file_targets.json", static_hints, - skip=Path(config.runs_dir), + skip=runs_dir, ), ) # A language nothing here covers is named, never a silent zero (pre-push 17.2, Requirement 9.2). @@ -772,7 +775,17 @@ def _map_scan_targets( write_entry_points(entry_points, run.root / "mapping" / "entry_points.json") targets = attach_reachability_hints(targets, entry_points) write_preprocess_artifact(snapshot, targets, run.root / "preprocess" / "file_targets.json") - return policy, ruleset, targets, entry_points + # After the preprocess stage, so a tree whose ignore file cannot be read stops the scan inside that stage, as before. + left_out = count_skipped_source_files(run.target, runs_dir) + return policy, ruleset, targets, entry_points, left_out + + +def _skipped_files_notices(runs_dir: Path, left_out: int) -> tuple[str, ...]: + """What the scan says about the source files it left out under its runs directory: nothing when there are none.""" + if not left_out: + return () + files = "file" if left_out == 1 else "files" + return (f"skipped {left_out} source {files} under the runs directory {runs_dir}",) def _collect_findings( diff --git a/src/openultrasast/preprocess.py b/src/openultrasast/preprocess.py index 573b9cee..6169d999 100644 --- a/src/openultrasast/preprocess.py +++ b/src/openultrasast/preprocess.py @@ -105,20 +105,24 @@ def enumerate_source_files(root: Path, skip: Path | None = None) -> list[Path]: excluded = _excluded_directory(root, skip) paths: list[Path] = [] for path in root.rglob("*"): - if ( - path.is_symlink() - or not path.is_file() - or _has_ignored_dir(root, path) - or _is_ignored(root, path, patterns, tracked) - or _is_vendored(root, path) - or (excluded is not None and path.is_relative_to(excluded)) - ): + if (excluded is not None and path.is_relative_to(excluded)) or not _is_read_as_source(root, path, patterns, tracked): continue - if detect_language(path) != "unknown": - paths.append(path) + paths.append(path) return sorted(paths, key=lambda item: item.relative_to(root).as_posix()) +def _is_read_as_source(root: Path, path: Path, patterns: list[_IgnoreRule], tracked: set[str] | None) -> bool: + """Whether `root`'s rules let a scan read `path` as source.""" + kept = not ( + path.is_symlink() + or not path.is_file() + or _has_ignored_dir(root, path) + or _is_ignored(root, path, patterns, tracked) + or _is_vendored(root, path) + ) + return kept and detect_language(path) != "unknown" + + def _excluded_directory(root: Path, skip: Path | None) -> Path | None: """`skip` as a path under `root`, or None when there is nothing to skip: no `skip` was given, or it is `root` itself or lies above it, which leaves the tree read as it was.""" @@ -130,6 +134,20 @@ def _excluded_directory(root: Path, skip: Path | None) -> Path | None: return root / named.relative_to(resolved) +def count_skipped_source_files(root: Path, skip: Path | None) -> int: + """How many source files `skip` leaves out of `enumerate_source_files(root, skip)`, for a scan to say so. + + The files under the skipped directory that `root`'s own rules let a scan read, since those are the ones + the skip takes from it; 0 when `skip` keeps nothing out. + """ + excluded = _excluded_directory(root, skip) + if excluded is None: + return 0 + patterns = _load_ignore_patterns(root) + tracked = _tracked_files(root) if patterns else None + return sum(1 for path in excluded.rglob("*") if _is_read_as_source(root, path, patterns, tracked)) + + def build_file_target(root: Path, path: Path) -> FileTarget: language = detect_language(path) text = _read_text(path) diff --git a/tests/test_scan_output_location.py b/tests/test_scan_output_location.py index b53f4119..bac701a1 100644 --- a/tests/test_scan_output_location.py +++ b/tests/test_scan_output_location.py @@ -13,7 +13,7 @@ import pytest from openultrasast import cli from openultrasast.cli import main -from openultrasast.config import ResolvedConfig +from openultrasast.config import ResolvedConfig, load_config from openultrasast.preprocess import enumerate_source_files LEDGER = ".openultrasast/calibration/false_positive_learnings.json" @@ -300,8 +300,11 @@ def test_a_target_that_lies_inside_the_runs_directory_is_read_as_it_was( assert _scan(repo) == 0 - (printed,) = re.findall(r"^run_dir=(.+)$", capsys.readouterr().out, flags=re.MULTILINE) + out = capsys.readouterr().out + (printed,) = re.findall(r"^run_dir=(.+)$", out, flags=re.MULTILINE) assert _files_read(Path(printed)) == ["app.py", "pkg/lib.py"] + # Nothing is left out there, so nothing is said. + assert "notice:" not in out def test_the_runs_directory_is_found_under_a_relative_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: @@ -318,3 +321,113 @@ def test_no_test_can_write_a_scan_run_into_the_developers_cache(tmp_path_factory """tests/conftest.py redirects the override for every test, so one that forgets to name a location cannot write into the real `~/.cache/openultrasast/runs`.""" assert Path(ResolvedConfig().runs_dir).is_relative_to(tmp_path_factory.getbasetemp()) + + +def _notices(capsys: pytest.CaptureFixture[str]) -> list[str]: + return re.findall(r"^notice: (.+)$", capsys.readouterr().out, flags=re.MULTILINE) + + +@pytest.mark.parametrize("form", ["override", "default_location", "symlinked_override"]) +@pytest.mark.parametrize("left_out", [2, 1]) +def test_a_scan_says_how_many_source_files_it_left_out_under_its_runs_directory( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], form: str, left_out: int +) -> None: + repo = _target(tmp_path) + runs = _runs_inside(repo, tmp_path, monkeypatch, form) + (runs / "earlier").mkdir() + (runs / "earlier" / "copy.py").write_text((repo / "app.py").read_text()) + # What a run keeps: no source file, so none of these is counted. + (runs / "earlier" / "report.md").write_text("# report\n") + (runs / "earlier" / "findings.json").write_text("{}\n") + if left_out == 2: + (runs / "earlier" / "pkg").mkdir() + (runs / "earlier" / "pkg" / "lib.py").write_text((repo / "pkg" / "lib.py").read_text()) + + assert _scan(repo) == 0 + + runs_dir = load_config(None).runs_dir + files = "file" if left_out == 1 else "files" + assert _notices(capsys) == [f"skipped {left_out} source {files} under the runs directory {runs_dir}"] + + +@pytest.mark.parametrize("where", ["inside", "outside"]) +def test_nothing_is_said_when_no_source_file_is_left_out( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], where: str +) -> None: + # Inside the scanned path a run keeps no source file, and outside it nothing is skipped: neither is said. + repo = _target(tmp_path) + if where == "inside": + runs = _runs_inside(repo, tmp_path, monkeypatch, "override") + kept = ("report.md", "findings.json") + else: + runs = tmp_path / "elsewhere" / "runs" + runs.mkdir(parents=True) + monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(runs)) + kept = ("copy.py",) + (runs / "earlier").mkdir() + for name in kept: + (runs / "earlier" / name).write_text("x = 1\n") + + assert _scan(repo) == 0 + + assert _notices(capsys) == [] + + +def _left_out_copy(repo: Path, runs: Path) -> None: + """A source file under the runs directory, where a run of this package keeps none.""" + (runs / "earlier").mkdir(parents=True) + (runs / "earlier" / "copy.py").write_text((repo / "app.py").read_text()) + + +def test_a_gitignore_inside_the_runs_directory_does_not_hide_what_the_scan_left_out( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + # The scan reads the target's root .gitignore and no other: one inside the runs directory hides nothing from + # the count. + repo = _target(tmp_path) + runs = repo / "pkg" + (runs / ".gitignore").write_text("*.py\n") + monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(runs)) + + assert _scan(repo) == 0 + + assert _notices(capsys) == [f"skipped 1 source file under the runs directory {runs}"] + + +def test_nothing_is_left_out_where_the_target_already_ignores_the_runs_directory( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + repo = _target(tmp_path) + (repo / ".gitignore").write_text("__pycache__/\n.runs/\n") + runs = _runs_inside(repo, tmp_path, monkeypatch, "override") + _left_out_copy(repo, runs) + + assert _scan(repo) == 0 + + assert _notices(capsys) == [] + + +def test_nothing_is_left_out_under_a_directory_the_scan_ignores( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + repo = _target(tmp_path) + runs = repo / ".openultrasast" / "runs" + _left_out_copy(repo, runs) + monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(runs)) + + assert _scan(repo) == 0 + + assert _notices(capsys) == [] + + +def test_a_directory_named_gitignore_in_the_runs_directory_costs_the_scan_nothing( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + # The count reads what the preprocess stage read, and nothing of its own under the runs directory. + repo = _target(tmp_path) + runs = _runs_inside(repo, tmp_path, monkeypatch, "override") + (runs / ".gitignore").mkdir() + + assert _scan(repo) == 0 + + assert _notices(capsys) == []