strata-python 0.2.4__py3-none-any.whl → 0.2.6__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.
- strata_python/cli.py +45 -2
- strata_python/contracts.py +9 -0
- strata_python/db/__init__.py +7 -1
- strata_python/db/cli.py +23 -9
- strata_python/db/config.py +28 -4
- strata_python/db/engine.py +4 -0
- strata_python/db/project.py +58 -7
- strata_python/db/web.py +103 -0
- strata_python/files.py +247 -0
- strata_python/http.py +326 -0
- strata_python/images.py +107 -0
- strata_python/media.py +323 -0
- strata_python/public_check.py +122 -19
- strata_python/settings.py +99 -25
- strata_python/stats.py +196 -0
- strata_python/tasks/__init__.py +2 -1
- strata_python/tasks/status.py +1 -16
- strata_python/testing.py +13 -0
- strata_python/web.py +10 -1
- {strata_python-0.2.4.dist-info → strata_python-0.2.6.dist-info}/METADATA +84 -21
- {strata_python-0.2.4.dist-info → strata_python-0.2.6.dist-info}/RECORD +24 -18
- {strata_python-0.2.4.dist-info → strata_python-0.2.6.dist-info}/WHEEL +0 -0
- {strata_python-0.2.4.dist-info → strata_python-0.2.6.dist-info}/entry_points.txt +0 -0
- {strata_python-0.2.4.dist-info → strata_python-0.2.6.dist-info}/licenses/LICENSE +0 -0
strata_python/media.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
"""ffprobe and ffmpeg, called one way: a typed probe, a duration, and ffmpeg runs that fail with the tool's own words.
|
|
2
|
+
|
|
3
|
+
strata-360 calls ffprobe in 16 places, listory has three separate wrappers (`process/probe.py`, `store/filegroups.py`,
|
|
4
|
+
`details.py`) and strata-models two (`workers/video.py`, `workers/audio.py`). They differ in the `-v` level, the
|
|
5
|
+
timeout and what a failure is (None, a `ToolError`, a `RuntimeError`, a `ParamError`), and each picks a few fields out
|
|
6
|
+
of the JSON by hand. Here:
|
|
7
|
+
|
|
8
|
+
info = probe(path) # Probe: duration, format, size, bit_rate, tags, streams, chapters, raw
|
|
9
|
+
info.audio.sample_rate; info.video.fps; info.chapters[0].title; info.warnings # ffprobe's own complaints
|
|
10
|
+
duration(path) # seconds, float
|
|
11
|
+
ffmpeg(["-i", src, "-ac", "1", out]) # -nostdin -hide_banner -v error -y; MediaError with stderr's tail
|
|
12
|
+
ffmpeg([...], progress=lambda s: ...) # seconds of output written so far, from -progress
|
|
13
|
+
available() # {"ffmpeg": True, "ffprobe": False}
|
|
14
|
+
|
|
15
|
+
`MediaError` is a `RuntimeError` for a missing tool, a file ffprobe cannot read, a timeout or a failed ffmpeg run. Its
|
|
16
|
+
message ends with the last lines ffmpeg wrote, because that is the only place the reason is.
|
|
17
|
+
|
|
18
|
+
Durations: the container's, else the longest stream's (some MP3s and raw streams have no container duration). A wrong
|
|
19
|
+
VBR header still gives a wrong number; `info.warnings` carries ffprobe's "estimating duration from bitrate" so an app
|
|
20
|
+
that cares (listory) can decode and count instead. The tools are found on the PATH, or `STRATA_FFMPEG`/`STRATA_FFPROBE`
|
|
21
|
+
when set (a build with more codecs). Standard library only; `run` is injectable, but tests should prefer the real
|
|
22
|
+
tools on a tiny generated file."""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import contextlib
|
|
27
|
+
import json
|
|
28
|
+
import os
|
|
29
|
+
import shutil
|
|
30
|
+
import subprocess
|
|
31
|
+
import threading
|
|
32
|
+
from collections.abc import Callable, Sequence
|
|
33
|
+
from dataclasses import dataclass, field
|
|
34
|
+
from typing import Any, cast
|
|
35
|
+
|
|
36
|
+
from strata_python import oslib
|
|
37
|
+
|
|
38
|
+
Json = dict[str, Any]
|
|
39
|
+
ENV = {"ffmpeg": "STRATA_FFMPEG", "ffprobe": "STRATA_FFPROBE"}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class MediaError(RuntimeError):
|
|
43
|
+
"""ffmpeg or ffprobe is missing, could not read the file, ran out of time or failed."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def tool(name: str) -> str:
|
|
47
|
+
"""The path of `ffmpeg` or `ffprobe`: `STRATA_FFMPEG` / `STRATA_FFPROBE` when set, else the PATH."""
|
|
48
|
+
found = os.environ.get(ENV.get(name, "")) or shutil.which(name)
|
|
49
|
+
if not found:
|
|
50
|
+
raise MediaError(f"{name} is not installed (or not on the PATH): install ffmpeg, or set {ENV.get(name, name)}")
|
|
51
|
+
return found
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def available() -> dict[str, bool]:
|
|
55
|
+
"""Which of the tools can be found, for a doctor row."""
|
|
56
|
+
out: dict[str, bool] = {}
|
|
57
|
+
for name in ENV:
|
|
58
|
+
try:
|
|
59
|
+
tool(name)
|
|
60
|
+
out[name] = True
|
|
61
|
+
except MediaError:
|
|
62
|
+
out[name] = False
|
|
63
|
+
return out
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _tail(text: str | bytes | None, n: int = 600) -> str:
|
|
67
|
+
if isinstance(text, bytes):
|
|
68
|
+
text = text.decode(errors="replace")
|
|
69
|
+
return (text or "").strip()[-n:]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _num(v: object, cast_to: Callable[[Any], Any] = float) -> Any:
|
|
73
|
+
try:
|
|
74
|
+
return cast_to(v)
|
|
75
|
+
except (TypeError, ValueError):
|
|
76
|
+
return None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _rate(v: object) -> float | None:
|
|
80
|
+
"""ffprobe's "30000/1001" (or "25") as a number; None for "0/0"."""
|
|
81
|
+
num, _, den = str(v or "").partition("/")
|
|
82
|
+
n, d = _num(num), _num(den or 1)
|
|
83
|
+
return n / d if n and d else None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass
|
|
87
|
+
class Stream:
|
|
88
|
+
index: int
|
|
89
|
+
kind: str # video | audio | subtitle | data | attachment
|
|
90
|
+
codec: str
|
|
91
|
+
duration: float | None
|
|
92
|
+
bit_rate: int | None
|
|
93
|
+
width: int | None = None
|
|
94
|
+
height: int | None = None
|
|
95
|
+
fps: float | None = None # avg_frame_rate, else r_frame_rate
|
|
96
|
+
frames: int | None = None
|
|
97
|
+
pix_fmt: str | None = None
|
|
98
|
+
sample_rate: int | None = None
|
|
99
|
+
channels: int | None = None
|
|
100
|
+
channel_layout: str | None = None
|
|
101
|
+
tags: dict[str, str] = field(default_factory=lambda: {}) # keys lower-cased
|
|
102
|
+
raw: Json = field(default_factory=lambda: {})
|
|
103
|
+
|
|
104
|
+
@classmethod
|
|
105
|
+
def from_json(cls, s: Json) -> Stream:
|
|
106
|
+
return cls(
|
|
107
|
+
index=int(s.get("index", 0)),
|
|
108
|
+
kind=str(s.get("codec_type", "")),
|
|
109
|
+
codec=str(s.get("codec_name", "")),
|
|
110
|
+
duration=_num(s.get("duration")),
|
|
111
|
+
bit_rate=_num(s.get("bit_rate"), int),
|
|
112
|
+
width=_num(s.get("width"), int),
|
|
113
|
+
height=_num(s.get("height"), int),
|
|
114
|
+
fps=_rate(s.get("avg_frame_rate")) or _rate(s.get("r_frame_rate")),
|
|
115
|
+
frames=_num(s.get("nb_frames"), int),
|
|
116
|
+
pix_fmt=s.get("pix_fmt"),
|
|
117
|
+
sample_rate=_num(s.get("sample_rate"), int),
|
|
118
|
+
channels=_num(s.get("channels"), int),
|
|
119
|
+
channel_layout=s.get("channel_layout"),
|
|
120
|
+
tags={str(k).lower(): str(v) for k, v in cast("Json", s.get("tags") or {}).items()},
|
|
121
|
+
raw=s,
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@dataclass
|
|
126
|
+
class Chapter:
|
|
127
|
+
start: float
|
|
128
|
+
end: float
|
|
129
|
+
title: str
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@dataclass
|
|
133
|
+
class Probe:
|
|
134
|
+
path: str
|
|
135
|
+
duration: float | None
|
|
136
|
+
format: str # format_name, e.g. "mov,mp4,m4a,3gp,3g2,mj2"
|
|
137
|
+
size: int | None
|
|
138
|
+
bit_rate: int | None
|
|
139
|
+
tags: dict[str, str] # container tags, keys lower-cased
|
|
140
|
+
streams: list[Stream]
|
|
141
|
+
chapters: list[Chapter]
|
|
142
|
+
warnings: str # what ffprobe wrote on stderr at -v warning
|
|
143
|
+
raw: Json # the whole ffprobe answer
|
|
144
|
+
|
|
145
|
+
def first(self, kind: str) -> Stream | None:
|
|
146
|
+
return next((s for s in self.streams if s.kind == kind), None)
|
|
147
|
+
|
|
148
|
+
@property
|
|
149
|
+
def video(self) -> Stream | None:
|
|
150
|
+
return self.first("video")
|
|
151
|
+
|
|
152
|
+
@property
|
|
153
|
+
def audio(self) -> Stream | None:
|
|
154
|
+
return self.first("audio")
|
|
155
|
+
|
|
156
|
+
@classmethod
|
|
157
|
+
def from_json(cls, path: str, d: Json, warnings: str = "") -> Probe:
|
|
158
|
+
fmt = cast("Json", d.get("format") or {})
|
|
159
|
+
streams = [Stream.from_json(s) for s in cast("list[Json]", d.get("streams") or [])]
|
|
160
|
+
dur = _num(fmt.get("duration")) or max((s.duration or 0.0 for s in streams), default=0.0) or None
|
|
161
|
+
chapters = [
|
|
162
|
+
Chapter(
|
|
163
|
+
float(c.get("start_time", 0)),
|
|
164
|
+
float(c.get("end_time", 0)),
|
|
165
|
+
str(cast("Json", c.get("tags") or {}).get("title", "")),
|
|
166
|
+
)
|
|
167
|
+
for c in cast("list[Json]", d.get("chapters") or [])
|
|
168
|
+
]
|
|
169
|
+
return cls(
|
|
170
|
+
path=path,
|
|
171
|
+
duration=dur,
|
|
172
|
+
format=str(fmt.get("format_name", "")),
|
|
173
|
+
size=_num(fmt.get("size"), int),
|
|
174
|
+
bit_rate=_num(fmt.get("bit_rate"), int),
|
|
175
|
+
tags={str(k).lower(): str(v) for k, v in cast("Json", fmt.get("tags") or {}).items()},
|
|
176
|
+
streams=streams,
|
|
177
|
+
chapters=chapters,
|
|
178
|
+
warnings=warnings.strip(),
|
|
179
|
+
raw=d,
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
Run = Callable[..., "subprocess.CompletedProcess[Any]"]
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def probe(path: str | os.PathLike[str], *, timeout: float = 120, run: Run = subprocess.run) -> Probe:
|
|
187
|
+
"""Everything ffprobe says about a file: format, every stream, chapters and tags. MediaError when it cannot."""
|
|
188
|
+
p = os.fspath(path)
|
|
189
|
+
cmd = [
|
|
190
|
+
tool("ffprobe"),
|
|
191
|
+
"-v",
|
|
192
|
+
"warning",
|
|
193
|
+
"-print_format",
|
|
194
|
+
"json",
|
|
195
|
+
"-show_format",
|
|
196
|
+
"-show_streams",
|
|
197
|
+
"-show_chapters",
|
|
198
|
+
p,
|
|
199
|
+
]
|
|
200
|
+
try:
|
|
201
|
+
r = run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout)
|
|
202
|
+
except subprocess.TimeoutExpired:
|
|
203
|
+
raise MediaError(f"ffprobe took longer than {timeout:g} s on {p}") from None
|
|
204
|
+
except OSError as e:
|
|
205
|
+
raise MediaError(f"ffprobe could not start: {e}") from None
|
|
206
|
+
if r.returncode or not (r.stdout or "").strip():
|
|
207
|
+
raise MediaError(f"ffprobe cannot read {p}: {_tail(r.stderr) or f'exit {r.returncode}'}")
|
|
208
|
+
try:
|
|
209
|
+
d = json.loads(r.stdout)
|
|
210
|
+
except ValueError:
|
|
211
|
+
raise MediaError(f"ffprobe gave no JSON for {p}: {_tail(r.stdout, 200)}") from None
|
|
212
|
+
return Probe.from_json(p, d, r.stderr or "")
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def duration(path: str | os.PathLike[str], *, timeout: float = 120, run: Run = subprocess.run) -> float:
|
|
216
|
+
"""The file's length in seconds; MediaError when ffprobe cannot tell."""
|
|
217
|
+
d = probe(path, timeout=timeout, run=run).duration
|
|
218
|
+
if d is None:
|
|
219
|
+
raise MediaError(f"ffprobe found no duration in {os.fspath(path)}")
|
|
220
|
+
return d
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def ffmpeg(
|
|
224
|
+
args: Sequence[str | os.PathLike[str]],
|
|
225
|
+
*,
|
|
226
|
+
input: bytes | None = None,
|
|
227
|
+
timeout: float | None = None,
|
|
228
|
+
progress: Callable[[float], None] | None = None,
|
|
229
|
+
level: str = "error",
|
|
230
|
+
cwd: str | None = None,
|
|
231
|
+
) -> bytes:
|
|
232
|
+
"""Run `ffmpeg -nostdin -hide_banner -v <level> -y <args>` and return its stdout (for `-f ... -` output).
|
|
233
|
+
`progress(seconds)` is called as output is written (from `-progress`); then stdout is not returned. MediaError with
|
|
234
|
+
the tail of stderr when it fails or passes `timeout`."""
|
|
235
|
+
exe = tool("ffmpeg")
|
|
236
|
+
base = [exe, "-hide_banner", "-v", level, "-y"]
|
|
237
|
+
if input is None:
|
|
238
|
+
base.insert(1, "-nostdin")
|
|
239
|
+
cmd = [*base, *(os.fspath(a) for a in args)]
|
|
240
|
+
if progress is None:
|
|
241
|
+
proc = subprocess.Popen( # noqa: S603 - our own ffmpeg command
|
|
242
|
+
cmd,
|
|
243
|
+
stdin=subprocess.DEVNULL if input is None else subprocess.PIPE,
|
|
244
|
+
stdout=subprocess.PIPE,
|
|
245
|
+
stderr=subprocess.PIPE,
|
|
246
|
+
cwd=cwd,
|
|
247
|
+
)
|
|
248
|
+
try:
|
|
249
|
+
out, err = proc.communicate(input, timeout=timeout)
|
|
250
|
+
except subprocess.TimeoutExpired:
|
|
251
|
+
_kill(proc)
|
|
252
|
+
raise MediaError(f"ffmpeg took longer than {timeout:g} s") from None
|
|
253
|
+
if proc.returncode:
|
|
254
|
+
raise MediaError(f"ffmpeg failed (exit {proc.returncode}): {_tail(err)}")
|
|
255
|
+
return out
|
|
256
|
+
return _with_progress([*base, "-progress", "pipe:1", "-nostats", *cmd[len(base) :]], progress, timeout, cwd, input)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _kill(proc: subprocess.Popen[bytes], reap: bool = True) -> None:
|
|
260
|
+
"""Stop ffmpeg and anything it started. On Windows a package manager's `ffmpeg.exe` is often a shim that starts the
|
|
261
|
+
real one; killing only the shim leaves the real one holding the pipes, and the read waits for ever."""
|
|
262
|
+
oslib.kill_tree(proc.pid, 9)
|
|
263
|
+
with contextlib.suppress(OSError):
|
|
264
|
+
proc.kill()
|
|
265
|
+
if reap: # the progress reader's threads read the pipes themselves
|
|
266
|
+
with contextlib.suppress(subprocess.TimeoutExpired, OSError, ValueError):
|
|
267
|
+
proc.communicate(timeout=10)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _with_progress(
|
|
271
|
+
cmd: list[str], progress: Callable[[float], None], timeout: float | None, cwd: str | None, data: bytes | None
|
|
272
|
+
) -> bytes:
|
|
273
|
+
"""Read `-progress pipe:1` lines (`out_time_us=...`) and report seconds; stderr is drained on a thread so a chatty
|
|
274
|
+
ffmpeg cannot fill its pipe and stall."""
|
|
275
|
+
proc = subprocess.Popen( # noqa: S603 - our own ffmpeg command
|
|
276
|
+
cmd,
|
|
277
|
+
stdin=subprocess.DEVNULL if data is None else subprocess.PIPE,
|
|
278
|
+
stdout=subprocess.PIPE,
|
|
279
|
+
stderr=subprocess.PIPE,
|
|
280
|
+
cwd=cwd,
|
|
281
|
+
) # bytes, so the input can be written as it is
|
|
282
|
+
out, errs = proc.stdout, proc.stderr
|
|
283
|
+
if out is None or errs is None: # pragma: no cover - both are pipes above
|
|
284
|
+
raise MediaError("ffmpeg's output pipes did not open")
|
|
285
|
+
err: list[str] = []
|
|
286
|
+
drain = threading.Thread(target=lambda: err.append(errs.read().decode(errors="replace")), daemon=True)
|
|
287
|
+
drain.start()
|
|
288
|
+
if data is not None and proc.stdin is not None: # fed on a thread: ffmpeg reads input while it writes progress
|
|
289
|
+
feed_pipe = proc.stdin
|
|
290
|
+
|
|
291
|
+
def feed() -> None:
|
|
292
|
+
with contextlib.suppress(BrokenPipeError, OSError, ValueError):
|
|
293
|
+
feed_pipe.write(data)
|
|
294
|
+
with contextlib.suppress(OSError):
|
|
295
|
+
feed_pipe.close()
|
|
296
|
+
|
|
297
|
+
threading.Thread(target=feed, daemon=True).start()
|
|
298
|
+
fired = threading.Event()
|
|
299
|
+
|
|
300
|
+
def kill() -> None:
|
|
301
|
+
fired.set()
|
|
302
|
+
_kill(proc, reap=False)
|
|
303
|
+
|
|
304
|
+
timer = threading.Timer(timeout, kill) if timeout else None
|
|
305
|
+
if timer:
|
|
306
|
+
timer.start()
|
|
307
|
+
try:
|
|
308
|
+
for raw in out:
|
|
309
|
+
key, _, value = raw.decode(errors="replace").strip().partition("=")
|
|
310
|
+
if key in ("out_time_us", "out_time_ms"): # both are microseconds (out_time_ms is misnamed by ffmpeg)
|
|
311
|
+
us = _num(value, int)
|
|
312
|
+
if us is not None and us >= 0:
|
|
313
|
+
progress(us / 1e6)
|
|
314
|
+
code = proc.wait()
|
|
315
|
+
finally:
|
|
316
|
+
if timer:
|
|
317
|
+
timer.cancel()
|
|
318
|
+
drain.join(5)
|
|
319
|
+
if fired.is_set():
|
|
320
|
+
raise MediaError(f"ffmpeg took longer than {timeout:g} s")
|
|
321
|
+
if code:
|
|
322
|
+
raise MediaError(f"ffmpeg failed (exit {code}): {_tail(''.join(err))}")
|
|
323
|
+
return b""
|
strata_python/public_check.py
CHANGED
|
@@ -13,6 +13,16 @@ False positives left after that are silenced in the repo, where a reviewer sees
|
|
|
13
13
|
`pkg-1.0/web/package-lock.json` matches too). An excluded file skips the built-in patterns only.
|
|
14
14
|
- `strata-public-check: ignore` anywhere on a line skips the built-in patterns on that line. Never the owner's
|
|
15
15
|
`STRATA_PUBLIC_DENY` patterns: a name the owner listed is never one to publish.
|
|
16
|
+
|
|
17
|
+
Patterns about the *shape* of a detail (an age, a birth date) are safe to publish and belong with the code, so every
|
|
18
|
+
contributor and every local run gets them: `[tool.strata-public-check] deny = ["\\bdate of birth\\b"]`, each a
|
|
19
|
+
case-insensitive regex or a `{pattern = "...", kind = "age"}` table naming what it reports. They behave like the
|
|
20
|
+
built-in ones (an exclude and the ignore comment skip them, and the match is printed), unlike the owner's secret ones.
|
|
21
|
+
|
|
22
|
+
What is read: source and config text by suffix (Python, TypeScript and JavaScript, CSS, HTML, MDX, SVG, Markdown,
|
|
23
|
+
TOML, JSON, YAML...) and files with no suffix unless they look binary. In a git checkout only the files git would
|
|
24
|
+
commit are read (`git ls-files -co --exclude-standard`), so tool output such as `.coverage`, a SQLite file full of
|
|
25
|
+
absolute paths, is never scanned on a local run.
|
|
16
26
|
"""
|
|
17
27
|
|
|
18
28
|
from __future__ import annotations
|
|
@@ -21,6 +31,8 @@ import argparse
|
|
|
21
31
|
import io
|
|
22
32
|
import os
|
|
23
33
|
import re
|
|
34
|
+
import shutil
|
|
35
|
+
import subprocess
|
|
24
36
|
import sys
|
|
25
37
|
import tarfile
|
|
26
38
|
import tomllib
|
|
@@ -52,14 +64,25 @@ BUILT_IN: dict[str, re.Pattern[str]] = {
|
|
|
52
64
|
"home folder path": re.compile(r"(?:/home/|/Users/|[A-Za-z]:\\+Users\\+)(?P<user>[A-Za-z0-9._-]+)"),
|
|
53
65
|
}
|
|
54
66
|
|
|
55
|
-
# Text files only: a binary (an image, a compiled extension) is skipped rather than decoded into noise.
|
|
56
|
-
|
|
67
|
+
# Text files only: a binary (an image, a compiled extension) is skipped rather than decoded into noise. Every strata app
|
|
68
|
+
# with a web front end keeps most of its code, stories and mock fixtures in the web suffixes (issue #37).
|
|
69
|
+
TEXT_SUFFIXES = {
|
|
70
|
+
*(".py", ".pyi", ".md", ".txt", ".toml", ".cfg", ".ini", ".json", ".yml", ".yaml", ".typed", ".sh", ""),
|
|
71
|
+
*(".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs", ".mdx", ".css", ".html", ".svg", ".vue"),
|
|
72
|
+
}
|
|
73
|
+
TEXT_NAMES = {".env.example"} # a template of the settings an app reads, committed on purpose
|
|
57
74
|
SKIP_PARTS = {
|
|
58
75
|
"__pycache__",
|
|
59
76
|
"node_modules",
|
|
60
77
|
"dist",
|
|
61
78
|
"build",
|
|
79
|
+
"storybook-static",
|
|
80
|
+
"baselines", # strata-visual's screenshots
|
|
62
81
|
} # and hidden folders (.git, .venv, caches), but not .github
|
|
82
|
+
# A file with no suffix is read only when it looks like text: no NUL byte in its start, so `.coverage` (SQLite) or a
|
|
83
|
+
# compiled tool is skipped even outside a git checkout.
|
|
84
|
+
SNIFF = 8192
|
|
85
|
+
DENY_KIND = f"matches [tool.{TABLE}] deny pattern"
|
|
63
86
|
|
|
64
87
|
|
|
65
88
|
@dataclass(frozen=True)
|
|
@@ -80,12 +103,19 @@ def deny_patterns(env: str | None = None) -> list[re.Pattern[str]]:
|
|
|
80
103
|
|
|
81
104
|
|
|
82
105
|
def scan_text(
|
|
83
|
-
where: str,
|
|
106
|
+
where: str,
|
|
107
|
+
text: str,
|
|
108
|
+
extra: Iterable[re.Pattern[str]] = (),
|
|
109
|
+
*,
|
|
110
|
+
built_in: bool = True,
|
|
111
|
+
repo: Iterable[tuple[str, re.Pattern[str]]] = (),
|
|
84
112
|
) -> Iterator[Finding]:
|
|
85
|
-
"""Findings in one file's text. `
|
|
113
|
+
"""Findings in one file's text. `repo` is `(kind, pattern)` pairs from the repo's `deny`, checked like the built-in
|
|
114
|
+
patterns; `built_in=False` (an excluded file) checks only the owner's patterns."""
|
|
86
115
|
extra = list(extra)
|
|
116
|
+
patterns = [*BUILT_IN.items(), *repo]
|
|
87
117
|
for number, line in enumerate(text.splitlines(), 1):
|
|
88
|
-
for kind, pattern in
|
|
118
|
+
for kind, pattern in patterns if built_in and IGNORE not in line else ():
|
|
89
119
|
for match in pattern.finditer(line):
|
|
90
120
|
if kind == "home folder path" and match.group("user").lower() in PLACEHOLDER_USERS:
|
|
91
121
|
continue
|
|
@@ -101,26 +131,88 @@ def excluded(name: str, patterns: Iterable[str]) -> bool:
|
|
|
101
131
|
return any(fnmatchcase(name, p) or fnmatchcase(name, "*/" + p) for p in patterns)
|
|
102
132
|
|
|
103
133
|
|
|
104
|
-
def
|
|
105
|
-
"""`exclude` from `[tool.strata-public-check]` in root's (default: the current folder's) pyproject.toml."""
|
|
134
|
+
def _config(root: Path | None) -> dict[str, Any]:
|
|
106
135
|
f = (root or Path()) / "pyproject.toml"
|
|
107
136
|
if not f.is_file():
|
|
108
|
-
return
|
|
137
|
+
return {}
|
|
109
138
|
tool = cast("dict[str, Any]", tomllib.loads(f.read_text(encoding="utf-8")).get("tool", {}))
|
|
110
|
-
return
|
|
139
|
+
return cast("dict[str, Any]", tool.get(TABLE, {}))
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def config_excludes(root: Path | None = None) -> list[str]:
|
|
143
|
+
"""`exclude` from `[tool.strata-public-check]` in root's (default: the current folder's) pyproject.toml."""
|
|
144
|
+
return [str(p) for p in _config(root).get("exclude", [])]
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def config_deny(root: Path | None = None) -> list[tuple[str, re.Pattern[str]]]:
|
|
148
|
+
"""`deny` from `[tool.strata-public-check]`: `(kind, pattern)` pairs, each a regex string or a `{pattern, kind}`
|
|
149
|
+
table, compiled case-insensitive. A bad regex or entry raises ValueError naming it."""
|
|
150
|
+
out: list[tuple[str, re.Pattern[str]]] = []
|
|
151
|
+
for entry in cast("list[Any]", _config(root).get("deny", [])):
|
|
152
|
+
if isinstance(entry, str):
|
|
153
|
+
raw, kind = entry, DENY_KIND
|
|
154
|
+
elif isinstance(entry, dict) and isinstance(cast("dict[str, Any]", entry).get("pattern"), str):
|
|
155
|
+
table = cast("dict[str, Any]", entry)
|
|
156
|
+
raw, kind = str(table["pattern"]), str(table.get("kind", DENY_KIND))
|
|
157
|
+
else:
|
|
158
|
+
raise ValueError(f'[tool.{TABLE}] deny: {entry!r} is neither a regex nor {{pattern = "...", kind = "..."}}')
|
|
159
|
+
try:
|
|
160
|
+
out.append((kind, re.compile(raw, re.IGNORECASE)))
|
|
161
|
+
except re.error as e:
|
|
162
|
+
raise ValueError(f"[tool.{TABLE}] deny: {raw!r} is not a valid regex: {e}") from e
|
|
163
|
+
return out
|
|
111
164
|
|
|
112
165
|
|
|
113
166
|
def _is_text(name: str) -> bool:
|
|
114
167
|
path = Path(name)
|
|
115
168
|
hidden = any(part.startswith(".") and part != ".github" for part in path.parts[:-1])
|
|
116
|
-
|
|
169
|
+
readable = path.suffix in TEXT_SUFFIXES or path.name in TEXT_NAMES
|
|
170
|
+
return readable and not hidden and not (set(path.parts) & SKIP_PARTS)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _looks_binary(name: str, data: bytes) -> bool:
|
|
174
|
+
"""A file with no suffix whose start holds a NUL byte (SQLite's `.coverage`, an executable) is not text."""
|
|
175
|
+
return not Path(name).suffix and b"\0" in data[:SNIFF]
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _git(folder: Path, *args: str) -> subprocess.CompletedProcess[bytes] | None:
|
|
179
|
+
git = shutil.which("git")
|
|
180
|
+
if git is None:
|
|
181
|
+
return None
|
|
182
|
+
try:
|
|
183
|
+
return subprocess.run([git, "-C", str(folder), *args], capture_output=True, check=False) # noqa: S603 - git on PATH, fixed arguments
|
|
184
|
+
except OSError:
|
|
185
|
+
return None
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _git_files(folder: Path) -> list[str] | None:
|
|
189
|
+
"""The files git would commit under `folder` (tracked, plus untracked ones not ignored), or None when git is not
|
|
190
|
+
installed, the folder is not in a checkout, or the folder is itself ignored (`strata-public-check dist` asks for
|
|
191
|
+
the built files, which a checkout ignores), so the caller walks the folder instead."""
|
|
192
|
+
listed = _git(folder, "ls-files", "-co", "--exclude-standard", "-z")
|
|
193
|
+
if listed is None or listed.returncode != 0:
|
|
194
|
+
return None
|
|
195
|
+
ignored = _git(folder.resolve().parent, "check-ignore", "-q", folder.resolve().name)
|
|
196
|
+
if ignored is not None and ignored.returncode == 0:
|
|
197
|
+
return None
|
|
198
|
+
return sorted({name for name in listed.stdout.decode("utf-8", "surrogateescape").split("\0") if name})
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _files(folder: Path) -> Iterator[tuple[str, Path]]:
|
|
202
|
+
names = _git_files(folder)
|
|
203
|
+
if names is None:
|
|
204
|
+
for file in sorted(folder.rglob("*")):
|
|
205
|
+
yield file.relative_to(folder).as_posix(), file
|
|
206
|
+
else:
|
|
207
|
+
for name in names:
|
|
208
|
+
yield name, folder / name
|
|
117
209
|
|
|
118
210
|
|
|
119
211
|
def _members(path: Path) -> Iterator[tuple[str, bytes]]:
|
|
120
212
|
if path.is_dir():
|
|
121
|
-
for file in
|
|
122
|
-
|
|
123
|
-
if
|
|
213
|
+
for relative, file in _files(path):
|
|
214
|
+
# a tracked file deleted from the work tree is listed by git but gone; a symlink to a folder is not a file
|
|
215
|
+
if _is_text(relative) and file.is_file():
|
|
124
216
|
yield relative, file.read_bytes()
|
|
125
217
|
elif path.name.endswith((".tar.gz", ".tgz")):
|
|
126
218
|
with tarfile.open(path) as archive:
|
|
@@ -137,19 +229,25 @@ def _members(path: Path) -> Iterator[tuple[str, bytes]]:
|
|
|
137
229
|
yield path.as_posix(), path.read_bytes()
|
|
138
230
|
|
|
139
231
|
|
|
140
|
-
def scan(
|
|
141
|
-
|
|
142
|
-
extra
|
|
232
|
+
def scan(
|
|
233
|
+
paths: Iterable[Path],
|
|
234
|
+
extra: Iterable[re.Pattern[str]] = (),
|
|
235
|
+
exclude: Iterable[str] = (),
|
|
236
|
+
repo: Iterable[tuple[str, re.Pattern[str]]] = (),
|
|
237
|
+
) -> list[Finding]:
|
|
238
|
+
"""Every finding in the given folders, files, sdists (.tar.gz) and wheels (.whl), less the excluded files.
|
|
239
|
+
`extra` is the owner's secret patterns, `repo` the `(kind, pattern)` pairs from the repo's `deny`."""
|
|
240
|
+
extra, exclude, repo = list(extra), list(exclude), list(repo)
|
|
143
241
|
findings: list[Finding] = []
|
|
144
242
|
for path in paths:
|
|
145
243
|
for where, data in _members(path):
|
|
146
244
|
skip = excluded(where, exclude)
|
|
147
|
-
if skip and not extra:
|
|
245
|
+
if (skip and not extra) or _looks_binary(where, data):
|
|
148
246
|
continue
|
|
149
247
|
text = io.TextIOWrapper(io.BytesIO(data), encoding="utf-8", errors="replace").read()
|
|
150
248
|
# an excluded file is still checked against the owner's patterns: an exclude is for false positives of the
|
|
151
249
|
# built-in ones, and a name the owner listed is never one to publish (review finding)
|
|
152
|
-
findings.extend(scan_text(where, text, extra, built_in=not skip))
|
|
250
|
+
findings.extend(scan_text(where, text, extra, built_in=not skip, repo=repo))
|
|
153
251
|
return findings
|
|
154
252
|
|
|
155
253
|
|
|
@@ -166,7 +264,12 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
166
264
|
help=f"skip matching files, as well as [tool.{TABLE}] exclude in ./pyproject.toml",
|
|
167
265
|
)
|
|
168
266
|
args = parser.parse_args(argv)
|
|
169
|
-
|
|
267
|
+
try:
|
|
268
|
+
repo = config_deny()
|
|
269
|
+
except ValueError as e:
|
|
270
|
+
print(e, file=sys.stderr)
|
|
271
|
+
return 2
|
|
272
|
+
findings = scan(args.paths, deny_patterns(), [*config_excludes(), *args.exclude], repo)
|
|
170
273
|
for finding in findings:
|
|
171
274
|
print(finding, file=sys.stderr)
|
|
172
275
|
if findings:
|