securebox-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
securebox_cli/scan.py ADDED
@@ -0,0 +1,291 @@
1
+ """Run the scanners on a snapshot of the repository (securebox_cli/snapshot.py) and normalize
2
+ their results the way the SecureBox server does, with the same fingerprints for code and
3
+ dependency findings, so the team's false positives and accepted risks stay quiet here too.
4
+
5
+ The scanners only read the snapshot, run from outside it, and get explicit (empty) configs
6
+ and output files: nothing in the scanned repository can change what they report or where
7
+ they write. Secret values are never printed or kept: Gitleaks runs with --redact."""
8
+
9
+ import hashlib
10
+ import json
11
+ import subprocess
12
+ import tempfile
13
+ from collections.abc import Callable
14
+ from dataclasses import asdict, dataclass, field
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ import yaml
19
+
20
+ from securebox_cli import ignore, snapshot, tools
21
+
22
+ SEVERITIES = ("critical", "high", "medium", "low", "info")
23
+ RANK = {s: i for i, s in enumerate(SEVERITIES)}
24
+ # As the server maps rule severities (project rules may also say CRITICAL/HIGH/MEDIUM/LOW).
25
+ OPENGREP_SEVERITY = {"ERROR": "high", "CRITICAL": "high", "HIGH": "high", "WARNING": "medium",
26
+ "MEDIUM": "medium", "INFO": "low", "LOW": "low"} # fmt: skip
27
+ TRIVY_SEVERITY = {"CRITICAL": "critical", "HIGH": "high", "MEDIUM": "medium", "LOW": "low"}
28
+ MAX_REGION_LINES = 20 # as the server (backend normalize/sarif.py)
29
+ TIMEOUT_SECONDS = 600
30
+ # The server's test-code excludes (backend workers/sast/semgrep.py EXCLUDES).
31
+ EXCLUDES = ("*.spec.*", "*.test.*", "*_test.py", "test_*.py", "conftest.py", "*.stories.*",
32
+ "__tests__", "__mocks__", "e2e", "cypress", "playwright", "*-tests", "*_tests",
33
+ ".semgrep", ".claude", ".cursor") # fmt: skip
34
+ MANIFESTS = ("package.json", "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "bun.lock",
35
+ "requirements.txt", "poetry.lock", "uv.lock", "Pipfile.lock", "pyproject.toml",
36
+ "go.mod", "go.sum", "pom.xml", "build.gradle", "build.gradle.kts", "Gemfile.lock",
37
+ "Cargo.lock", "composer.lock", "packages.lock.json") # fmt: skip
38
+
39
+
40
+ @dataclass
41
+ class Finding:
42
+ tool: str # gitleaks | semgrep | trivy (the server's tool names)
43
+ rule_id: str
44
+ severity: str
45
+ title: str
46
+ path: str | None
47
+ line: int | None
48
+ category: str # secret | code | dependency
49
+ fingerprint: str | None = None
50
+ package: str | None = None
51
+ version: str | None = None
52
+ fixed_version: str | None = None
53
+
54
+
55
+ @dataclass
56
+ class Result:
57
+ findings: list[Finding] = field(default_factory=list)
58
+ suppressed: int = 0
59
+ ignored: int = 0
60
+ errors: dict[str, str] = field(default_factory=dict) # a scanner that should have run
61
+ warnings: list[str] = field(default_factory=list) # e.g. files a scanner could not parse
62
+ ran: list[str] = field(default_factory=list)
63
+ files: int = 0
64
+
65
+ def as_dict(self) -> dict[str, Any]:
66
+ return {"findings": [asdict(f) for f in self.findings], "suppressed": self.suppressed,
67
+ "ignored": self.ignored, "errors": self.errors, "warnings": self.warnings,
68
+ "ran": self.ran, "files": self.files} # fmt: skip
69
+
70
+
71
+ def fingerprint(*parts: str | None) -> str:
72
+ """The server's fingerprint (backend normalize/finding.py)."""
73
+ return hashlib.sha256("\x1f".join(p or "" for p in parts).encode()).hexdigest()
74
+
75
+
76
+ def _region(root: Path, path: str, start: int, end: int | None) -> str | None:
77
+ try:
78
+ target = (root / path).resolve()
79
+ if not target.is_relative_to(root.resolve()) or not target.is_file():
80
+ return None
81
+ lines = target.read_bytes().decode("utf-8", errors="replace").splitlines()
82
+ except OSError:
83
+ return None
84
+ stop = min(end or start, start + MAX_REGION_LINES - 1)
85
+ return "\n".join(lines[start - 1 : stop]) or None
86
+
87
+
88
+ def rule_ids(rule_files: list[Path]) -> set[str]:
89
+ """The ids of the rules we load (the engine prefixes them with their file's folder)."""
90
+ ids: set[str] = set()
91
+ for path in rule_files:
92
+ try:
93
+ data = yaml.safe_load(path.read_text()) or {}
94
+ except (OSError, yaml.YAMLError):
95
+ continue
96
+ rules = data.get("rules") if isinstance(data, dict) else None
97
+ for rule in rules if isinstance(rules, list) else []:
98
+ if isinstance(rule, dict) and rule.get("id"):
99
+ ids.add(str(rule["id"]))
100
+ return ids
101
+
102
+
103
+ def rule_id(check_id: str, known: set[str]) -> str:
104
+ """The rule's own id: the longest loaded id the engine's id ends with (whatever folder
105
+ prefix the engine added, wherever the rules live)."""
106
+ best = ""
107
+ for candidate in known:
108
+ matches = check_id == candidate or check_id.endswith("." + candidate)
109
+ if matches and len(candidate) > len(best):
110
+ best = candidate
111
+ return best or check_id
112
+
113
+
114
+ def _run(command: list[str], cwd: Path,
115
+ env: dict[str, str] | None = None) -> subprocess.CompletedProcess[str]: # fmt: skip
116
+ return subprocess.run(command, cwd=cwd, capture_output=True, text=True, encoding="utf-8",
117
+ errors="replace", check=False, timeout=TIMEOUT_SECONDS,
118
+ env=snapshot.git_env() | (env or {})) # fmt: skip
119
+
120
+
121
+ def run_gitleaks(snap: snapshot.Snapshot, staged: bool, use_path: bool,
122
+ work: Path) -> list[Finding]: # fmt: skip
123
+ binary = tools.ensure("gitleaks", use_path)
124
+ config = tools.gitleaks_config()
125
+ empty = work / "empty.gitleaksignore"
126
+ empty.touch()
127
+ report = work / "gitleaks.json"
128
+ done = _run([binary, "dir", "--config", str(config), "--gitleaks-ignore-path", str(empty),
129
+ "--report-format", "json", "--report-path", str(report), "--redact",
130
+ "--exit-code", "0", "--no-banner", "--log-level", "error",
131
+ str(snap.root)], work) # fmt: skip
132
+ if done.returncode != 0 or not report.is_file():
133
+ raise RuntimeError(f"gitleaks exited with {done.returncode}: {done.stderr.strip()[-300:]}")
134
+ findings = []
135
+ for leak in json.loads(report.read_text() or "[]"):
136
+ path = Path(str(leak.get("File") or ""))
137
+ try:
138
+ rel = path.resolve().relative_to(snap.root.resolve()).as_posix()
139
+ except ValueError:
140
+ rel = path.as_posix()
141
+ line = leak.get("StartLine") if isinstance(leak.get("StartLine"), int) else None
142
+ if staged:
143
+ added = snap.added.get(rel)
144
+ if added is not None and line is not None and line not in added:
145
+ continue # an existing line of a changed file: not what this commit adds
146
+ findings.append(Finding(
147
+ tool="gitleaks", rule_id=str(leak.get("RuleID")), severity="high",
148
+ title=f"Possible secret: {leak.get('RuleID')}", path=rel or None, line=line,
149
+ category="secret",
150
+ )) # fmt: skip
151
+ report.unlink(missing_ok=True)
152
+ return findings
153
+
154
+
155
+ def run_opengrep(snap: snapshot.Snapshot, rule_files: list[Path], use_path: bool,
156
+ result: "Result") -> list[Finding]: # fmt: skip
157
+ binary = tools.ensure("opengrep", use_path)
158
+ configs = [arg for f in rule_files for arg in ("--config", str(f.resolve()))]
159
+ excludes = [arg for p in EXCLUDES for arg in ("--exclude", p)]
160
+ known = rule_ids(rule_files)
161
+ # Its own settings folder: Opengrep stops when XDG_CONFIG_HOME names a missing folder, and
162
+ # the user's settings (a login, a registry) should not change what it reports.
163
+ settings = snap.root.parent / "opengrep-settings"
164
+ settings.mkdir(exist_ok=True)
165
+ env = {"XDG_CONFIG_HOME": str(settings), "SEMGREP_SETTINGS_FILE": str(settings / "s.yml")}
166
+ done = _run([binary, "scan", *configs, "--json", "--quiet", "--disable-nosem",
167
+ "--no-git-ignore", "--timeout", "30", *excludes, "--", "."],
168
+ snap.root, env) # fmt: skip
169
+ try:
170
+ data = json.loads(done.stdout or "{}")
171
+ except ValueError:
172
+ data = {}
173
+ if done.returncode not in (0, 1) or not isinstance(data, dict) or "results" not in data:
174
+ errors = [str(e.get("message", ""))[:200] for e in (data or {}).get("errors") or []
175
+ if isinstance(e, dict)] if isinstance(data, dict) else [] # fmt: skip
176
+ detail = "; ".join(errors[:2]) or done.stderr.strip()[-300:] or "no output"
177
+ raise RuntimeError(f"opengrep exited with {done.returncode}: {detail}")
178
+ skipped = [e for e in data.get("errors") or [] if isinstance(e, dict)]
179
+ if skipped:
180
+ result.warnings.append(f"opengrep could not read {len(skipped)} files or rules")
181
+ findings = []
182
+ for item in data.get("results", []):
183
+ rid = rule_id(str(item.get("check_id", "")), known)
184
+ path = str(item.get("path") or "").removeprefix("./")
185
+ start = (item.get("start") or {}).get("line")
186
+ end = (item.get("end") or {}).get("line")
187
+ extra = item.get("extra") or {}
188
+ region = _region(snap.root, path, start, end) if isinstance(start, int) else None
189
+ identity = " ".join(region.split()) if region else str(start)
190
+ findings.append(Finding(
191
+ tool="semgrep", rule_id=rid,
192
+ severity=OPENGREP_SEVERITY.get(str(extra.get("severity")).upper(), "medium"),
193
+ title=" ".join(str(extra.get("message") or rid).split())[:200], path=path,
194
+ line=start if isinstance(start, int) else None, category="code",
195
+ fingerprint=fingerprint("semgrep", rid, path, identity),
196
+ )) # fmt: skip
197
+ return findings
198
+
199
+
200
+ def run_trivy(snap: snapshot.Snapshot, use_path: bool, work: Path) -> list[Finding]:
201
+ binary = tools.ensure("trivy", use_path)
202
+ empty_config, empty_ignore = work / "trivy-empty.yaml", work / "trivy-empty.ignore"
203
+ empty_config.write_text("{}\n")
204
+ empty_ignore.touch()
205
+ report = work / "trivy.json"
206
+ done = _run([binary, "fs", "--scanners", "vuln", "--format", "json", "--quiet",
207
+ "--skip-version-check", "--config", str(empty_config),
208
+ "--ignorefile", str(empty_ignore), "--output", str(report),
209
+ "--cache-dir", str(tools.cache_dir() / "trivy"),
210
+ str(snap.root)], work) # fmt: skip
211
+ if done.returncode != 0 or not report.is_file():
212
+ raise RuntimeError(f"trivy exited with {done.returncode}: {done.stderr.strip()[-300:]}")
213
+ findings = []
214
+ for res in json.loads(report.read_text() or "{}").get("Results") or []:
215
+ target = str(res.get("Target") or "")
216
+ for vuln in res.get("Vulnerabilities") or []:
217
+ vid = str(vuln.get("VulnerabilityID"))
218
+ pkg, ver = vuln.get("PkgName"), vuln.get("InstalledVersion")
219
+ findings.append(Finding(
220
+ tool="trivy", rule_id=vid,
221
+ severity=TRIVY_SEVERITY.get(str(vuln.get("Severity")), "low"),
222
+ title=f"{pkg} {ver}: {vuln.get('Title') or vid}"[:200], path=target or None,
223
+ line=None, category="dependency", fingerprint=fingerprint("trivy", vid, pkg, ver),
224
+ package=pkg, version=ver, fixed_version=vuln.get("FixedVersion") or None,
225
+ )) # fmt: skip
226
+ return findings
227
+
228
+
229
+ def scan(
230
+ path: Path, rule_files: list[Path], staged: bool = False, use_path: bool = False,
231
+ suppressed: set[str] | None = None, progress: Callable[[str], None] = lambda m: None,
232
+ ) -> Result: # fmt: skip
233
+ """Every scanner that applies; a scanner that fails is reported in `errors`."""
234
+ result = Result()
235
+ repo = snapshot.repo_root(path)
236
+ base = repo or path
237
+ config = ignore.load(base)
238
+ if config.error:
239
+ result.warnings.append(config.error + " Nothing in it is applied.")
240
+ found: list[Finding] = []
241
+ with tempfile.TemporaryDirectory(prefix="securebox-") as tmp:
242
+ work = Path(tmp)
243
+ root = work / "snapshot"
244
+ root.mkdir()
245
+ try:
246
+ if staged:
247
+ if repo is None:
248
+ raise snapshot.SnapshotError("--staged needs a git repository.")
249
+ snap = snapshot.staged(repo, root)
250
+ else:
251
+ snap = snapshot.working(path, repo, root)
252
+ except (snapshot.SnapshotError, OSError) as exc:
253
+ result.errors["snapshot"] = str(exc)[:500]
254
+ return result
255
+ result.files = len(snap.files)
256
+ if not snap.files:
257
+ return result
258
+ deps = any(Path(f).name in MANIFESTS for f in snap.files)
259
+ steps: list[tuple[str, Callable[[], list[Finding]]]] = [
260
+ ("gitleaks", lambda: run_gitleaks(snap, staged, use_path, work)),
261
+ ("opengrep", lambda: run_opengrep(snap, rule_files, use_path, result)),
262
+ ]
263
+ if deps:
264
+ steps.append(("trivy", lambda: run_trivy(snap, use_path, work)))
265
+ for name, step in steps:
266
+ progress(f"Running {name}…")
267
+ try:
268
+ found += step()
269
+ result.ran.append(name)
270
+ except (tools.ToolError, RuntimeError, OSError, ValueError,
271
+ subprocess.TimeoutExpired) as exc: # fmt: skip
272
+ result.errors[name] = str(exc)[:500]
273
+ for finding in found:
274
+ secret = finding.category == "secret"
275
+ if ignore.ignored(config, finding.tool, finding.rule_id, finding.path, secret):
276
+ result.ignored += 1
277
+ elif finding.fingerprint and suppressed and finding.fingerprint in suppressed:
278
+ result.suppressed += 1
279
+ else:
280
+ result.findings.append(finding)
281
+ result.findings.sort(key=lambda f: (RANK.get(f.severity, 9), f.path or "", f.line or 0))
282
+ return result
283
+
284
+
285
+ def blocking(result: Result, fail_on: str) -> list[Finding]:
286
+ """What stops a commit or fails a build: every secret, and findings at or above fail_on."""
287
+ limit = RANK.get(fail_on)
288
+ return [
289
+ f for f in result.findings
290
+ if f.category == "secret" or (limit is not None and RANK.get(f.severity, 9) <= limit)
291
+ ] # fmt: skip
@@ -0,0 +1,221 @@
1
+ """What the scanners read: a snapshot of the repository in a temporary folder, never the
2
+ repository itself.
3
+
4
+ - `--staged`: the staged content of the staged files (raw blobs from the index: no smudge or
5
+ text-conversion filter runs), plus, for secrets, which lines the commit adds.
6
+ - otherwise: the tracked and new (not git-ignored) files of the working copy, or every file of
7
+ a folder that is not a git repository.
8
+
9
+ Symlinks and special files are left out, and so is every file a repository could use to change
10
+ what the scanners report (.semgrepignore, .trivyignore, trivy.yaml, .gitleaks.toml, …), as on
11
+ the SecureBox server. Every git command runs with the repository's settings that can run
12
+ programs switched off (fsmonitor, hooks, external diff, pager)."""
13
+
14
+ import os
15
+ import re
16
+ import subprocess
17
+ from dataclasses import dataclass, field
18
+ from pathlib import Path, PurePosixPath
19
+
20
+ # Read by scanners from the scanned folder; never honoured (as on the server).
21
+ SCANNER_CONFIG = frozenset({
22
+ ".semgrepignore", ".trivyignore", ".trivyignore.yaml", "trivy.yaml", "trivy.yml",
23
+ ".gitleaks.toml", ".gitleaksignore", ".gitleaks.yml", ".gitleaks.yaml",
24
+ }) # fmt: skip
25
+ # Never copied: installed dependencies and tool caches (the server's clone has none).
26
+ SKIP_DIRS = frozenset({
27
+ ".git", "node_modules", ".venv", "venv", "__pycache__", ".tox", ".nox", ".mypy_cache",
28
+ ".pytest_cache", ".ruff_cache", ".next", ".nuxt",
29
+ }) # fmt: skip
30
+ MAX_FILE_BYTES = 10 * 1024 * 1024
31
+ MAX_TOTAL_BYTES = 1024 * 1024 * 1024
32
+ MAX_FILES = 200_000
33
+ # Settings a repository's .git/config could use to run programs during our git calls.
34
+ SAFE_CONFIG = (
35
+ ("core.fsmonitor", "false"), ("core.hooksPath", os.devnull), ("diff.external", ""),
36
+ ("core.pager", "cat"), ("core.untrackedCache", "false"), ("core.quotePath", "false"),
37
+ ) # fmt: skip
38
+
39
+
40
+ class SnapshotError(Exception):
41
+ """The snapshot cannot be made; the message is safe to show."""
42
+
43
+
44
+ def git_env(hooks_path: bool = False) -> dict[str, str]:
45
+ """The environment for our git calls. `hooks_path=True` keeps the repository's own
46
+ core.hooksPath (only to find where the pre-commit hook belongs; no hook runs then)."""
47
+ env = dict(os.environ)
48
+ for name in ("GIT_EXTERNAL_DIFF", "GIT_PAGER", "GIT_DIFF_OPTS"):
49
+ env.pop(name, None)
50
+ settings = [(k, v) for k, v in SAFE_CONFIG if not (hooks_path and k == "core.hooksPath")]
51
+ env["GIT_CONFIG_COUNT"] = str(len(settings))
52
+ for i, (key, value) in enumerate(settings):
53
+ env[f"GIT_CONFIG_KEY_{i}"] = key
54
+ env[f"GIT_CONFIG_VALUE_{i}"] = value
55
+ env["GIT_TERMINAL_PROMPT"] = "0"
56
+ env["GIT_OPTIONAL_LOCKS"] = "0"
57
+ return env
58
+
59
+
60
+ def git(repo: Path, *args: str, stdin: bytes | None = None) -> bytes:
61
+ """A git command in the repository (bytes out; raises SnapshotError on failure)."""
62
+ done = subprocess.run(["git", "-C", str(repo), *args], input=stdin, capture_output=True,
63
+ env=git_env(), check=False, timeout=300) # fmt: skip
64
+ if done.returncode != 0:
65
+ message = done.stderr.decode("utf-8", "replace").strip().splitlines()[-1:] or [""]
66
+ raise SnapshotError(f"git {args[0]} failed: {message[0][:200]}")
67
+ return done.stdout
68
+
69
+
70
+ def repo_root(path: Path) -> Path | None:
71
+ try:
72
+ top = git(path, "rev-parse", "--show-toplevel").decode("utf-8", "surrogateescape")
73
+ except (SnapshotError, OSError):
74
+ return None
75
+ return Path(top.strip())
76
+
77
+
78
+ @dataclass
79
+ class Snapshot:
80
+ root: Path # the temporary folder: scanners read only this
81
+ files: list[str] = field(default_factory=list) # repo-relative POSIX paths
82
+ # --staged: new line numbers each staged file adds (None: the whole file is new).
83
+ added: dict[str, set[int] | None] = field(default_factory=dict)
84
+ skipped: int = 0 # symlinks, special or oversized files left out
85
+
86
+
87
+ def _safe_rel(path: str) -> str | None:
88
+ """A repo-relative path we can write under the snapshot (never outside it)."""
89
+ pure = PurePosixPath(path)
90
+ if not path or pure.is_absolute() or ".." in pure.parts or "\0" in path:
91
+ return None
92
+ return pure.as_posix()
93
+
94
+
95
+ def _write(snap: Snapshot, rel: str, data: bytes) -> None:
96
+ target = snap.root / rel
97
+ target.parent.mkdir(parents=True, exist_ok=True)
98
+ target.write_bytes(data)
99
+ snap.files.append(rel)
100
+
101
+
102
+ def _keep(rel: str) -> bool:
103
+ parts = PurePosixPath(rel).parts
104
+ return PurePosixPath(rel).name not in SCANNER_CONFIG and not any(
105
+ p in SKIP_DIRS for p in parts[:-1]
106
+ )
107
+
108
+
109
+ def _under(rel: str, prefix: str) -> bool:
110
+ return not prefix or rel == prefix or rel.startswith(prefix.rstrip("/") + "/")
111
+
112
+
113
+ def staged(repo: Path, root: Path) -> Snapshot:
114
+ """The staged content of the files a commit adds or changes."""
115
+ snap = Snapshot(root)
116
+ names = git(repo, "diff", "--cached", "--name-only", "--no-renames", "--diff-filter=ACMR",
117
+ "-z").split(b"\0") # fmt: skip
118
+ wanted = {os.fsdecode(n) for n in names if n}
119
+ if not wanted:
120
+ return snap
121
+ # The index entries (mode, blob) of those files: regular files only (no symlinks, no
122
+ # submodules), read raw with cat-file so no filter configured in the repository runs.
123
+ entries: list[tuple[str, str]] = []
124
+ for line in git(repo, "ls-files", "-s", "-z").split(b"\0"):
125
+ if b"\t" not in line:
126
+ continue
127
+ meta, raw = line.split(b"\t", 1)
128
+ name = os.fsdecode(raw)
129
+ mode, sha, _stage = meta.decode().split()
130
+ rel = _safe_rel(name)
131
+ if name not in wanted or rel is None or not _keep(rel):
132
+ continue
133
+ if mode not in ("100644", "100755"):
134
+ snap.skipped += 1
135
+ continue
136
+ entries.append((rel, sha))
137
+ if entries:
138
+ blobs = git(repo, "cat-file", "--batch",
139
+ stdin="".join(f"{sha}\n" for _, sha in entries).encode()) # fmt: skip
140
+ offset = 0
141
+ for rel, _sha in entries:
142
+ header_end = blobs.index(b"\n", offset)
143
+ header = blobs[offset:header_end].split()
144
+ if len(header) < 3: # "<sha> missing": nothing to read for this entry
145
+ offset = header_end + 1
146
+ snap.skipped += 1
147
+ continue
148
+ size = int(header[2])
149
+ data = blobs[header_end + 1 : header_end + 1 + size]
150
+ offset = header_end + 1 + size + 1
151
+ if size > MAX_FILE_BYTES:
152
+ snap.skipped += 1
153
+ continue
154
+ _write(snap, rel, data)
155
+ snap.added = added_lines(repo)
156
+ return snap
157
+
158
+
159
+ _HUNK = re.compile(rb"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@")
160
+
161
+
162
+ def added_lines(repo: Path) -> dict[str, set[int] | None]:
163
+ """Per staged file, the line numbers (in the staged content) the commit adds."""
164
+ diff = git(repo, "diff", "--cached", "--no-ext-diff", "--no-textconv", "--no-color",
165
+ "--no-renames", "--unified=0", "--diff-filter=ACMR") # fmt: skip
166
+ result: dict[str, set[int] | None] = {}
167
+ current: str | None = None
168
+ for line in diff.split(b"\n"):
169
+ if line.startswith(b"+++ "):
170
+ path = line[4:]
171
+ if path.startswith(b'"'):
172
+ current = None # a quoted (unusual) name: the whole file counts below
173
+ continue
174
+ current = os.fsdecode(path[2:]) if path.startswith(b"b/") else None
175
+ if current is not None:
176
+ result.setdefault(current, set())
177
+ elif current is not None and (match := _HUNK.match(line)):
178
+ start, count = int(match[1]), int(match[2] if match[2] is not None else 1)
179
+ lines = result[current]
180
+ if lines is not None:
181
+ lines.update(range(start, start + count))
182
+ return result
183
+
184
+
185
+ def working(path: Path, repo: Path | None, root: Path) -> Snapshot:
186
+ """The tracked and new files under `path` (all files when not in a git repository)."""
187
+ snap = Snapshot(root)
188
+ if repo is not None:
189
+ prefix = path.resolve().relative_to(repo.resolve()).as_posix()
190
+ prefix = "" if prefix == "." else prefix
191
+ listed = git(repo, "ls-files", "-z", "--cached", "--others", "--exclude-standard")
192
+ names = sorted({os.fsdecode(n) for n in listed.split(b"\0") if n})
193
+ base = repo
194
+ else:
195
+ prefix, base = "", path
196
+ names = []
197
+ for folder, dirs, files in os.walk(path):
198
+ dirs[:] = [d for d in dirs if d not in SKIP_DIRS]
199
+ for name in files:
200
+ names.append(Path(folder, name).relative_to(path).as_posix())
201
+ total = 0
202
+ for name in names:
203
+ rel = _safe_rel(name)
204
+ if rel is None or not _under(rel, prefix) or not _keep(rel):
205
+ continue
206
+ source = base / rel
207
+ try:
208
+ if source.is_symlink() or not source.is_file():
209
+ snap.skipped += 1
210
+ continue
211
+ size = source.stat().st_size
212
+ if size > MAX_FILE_BYTES:
213
+ snap.skipped += 1
214
+ continue
215
+ total += size
216
+ if total > MAX_TOTAL_BYTES or len(snap.files) >= MAX_FILES:
217
+ raise SnapshotError("The folder is too large to check here (over 1 GB).")
218
+ _write(snap, rel, source.read_bytes())
219
+ except OSError:
220
+ snap.skipped += 1
221
+ return snap