strata-python 0.2.5__py3-none-any.whl → 0.2.7__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 +19 -8
- 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/mediatime.py +232 -0
- strata_python/public_check.py +122 -19
- strata_python/settings.py +99 -25
- strata_python/testing.py +13 -0
- strata_python/web.py +50 -7
- {strata_python-0.2.5.dist-info → strata_python-0.2.7.dist-info}/METADATA +30 -8
- {strata_python-0.2.5.dist-info → strata_python-0.2.7.dist-info}/RECORD +18 -16
- {strata_python-0.2.5.dist-info → strata_python-0.2.7.dist-info}/WHEEL +0 -0
- {strata_python-0.2.5.dist-info → strata_python-0.2.7.dist-info}/entry_points.txt +0 -0
- {strata_python-0.2.5.dist-info → strata_python-0.2.7.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
"""Exact time for media: rational seconds, frame rates, half-open spans and the map from an edit's output time back to its sources.
|
|
2
|
+
|
|
3
|
+
An editor that keeps time as float seconds drifts: 1001/30000 s is not a float, a frame found by `int(t * fps)` lands one early when `t` came
|
|
4
|
+
back from a sum, and a cut moved twice is no longer on a frame. strata-reels (the video editor) and strata-360 both needed the same answer,
|
|
5
|
+
which is the one OpenTimelineIO and every NLE use: time is a rational number of seconds, a rate is a rational number of frames a second,
|
|
6
|
+
and a stretch of time is half-open, [start, end), so two shots that meet share no frame. Here:
|
|
7
|
+
|
|
8
|
+
t = rational("1001/30000") # Fraction; also from an int, a Decimal, a str ("12.04") or a float (by its shortest repr)
|
|
9
|
+
pal = Rate.parse("25/1"); ntsc = Rate.parse("30000/1001") # ffprobe's r_frame_rate / avg_frame_rate text
|
|
10
|
+
ntsc.frame_at(t); ntsc.time_of(120); ntsc.snap(t) # the frame showing at t; when frame 120 starts; the nearest frame start
|
|
11
|
+
s = Span(rational(2), rational(5)); s.duration; s & Span(...) # [2, 5): 3 s; the overlap, or None
|
|
12
|
+
m = TimeMap.sequence([("tape1", Span(...)), ("tape1", Span(...))]) # source ranges played end to end
|
|
13
|
+
m.to_source(rational(4)) -> ("tape1", Fraction(...)); m.to_output("tape1", t) -> [output times]
|
|
14
|
+
text(t) -> "1001/30000"; m.to_json(); TimeMap.from_json(...) # exact in JSON: rationals as strings
|
|
15
|
+
|
|
16
|
+
A float never goes in silently: `rational(0.1)` is 1/10 (the float's shortest repr), not 3602879701896397/36028797018963968, and a value that
|
|
17
|
+
is not a number raises ValueError. Standard library only."""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import bisect
|
|
22
|
+
import itertools
|
|
23
|
+
import math
|
|
24
|
+
from collections.abc import Iterable, Sequence
|
|
25
|
+
from dataclasses import dataclass, field
|
|
26
|
+
from decimal import Decimal
|
|
27
|
+
from fractions import Fraction
|
|
28
|
+
from typing import Any
|
|
29
|
+
|
|
30
|
+
Number = int | float | str | Decimal | Fraction
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def rational(value: Number) -> Fraction:
|
|
34
|
+
"""Exact seconds (or any quantity) from an int, Fraction, Decimal, "p/q" or decimal text, or a float by its shortest repr."""
|
|
35
|
+
if isinstance(value, bool):
|
|
36
|
+
raise ValueError(f"not a number: {value!r}")
|
|
37
|
+
if isinstance(value, float):
|
|
38
|
+
if not math.isfinite(value):
|
|
39
|
+
raise ValueError(f"not a finite number: {value!r}")
|
|
40
|
+
return Fraction(
|
|
41
|
+
repr(value)
|
|
42
|
+
) # 0.1 -> 1/10: the number the person or file wrote, not the float's binary expansion
|
|
43
|
+
try:
|
|
44
|
+
return Fraction(value)
|
|
45
|
+
except (ValueError, ZeroDivisionError, TypeError) as e:
|
|
46
|
+
raise ValueError(f"not a number: {value!r}") from e
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def text(value: Fraction) -> str:
|
|
50
|
+
"""A rational as JSON-safe text: "3" or "1001/30000"; `rational` reads it back exactly."""
|
|
51
|
+
return str(value)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True, order=True)
|
|
55
|
+
class Rate:
|
|
56
|
+
"""Frames a second, exact: 25, 50, 30000/1001. Frame n starts at n / rate and shows until frame n + 1 starts."""
|
|
57
|
+
|
|
58
|
+
fps: Fraction
|
|
59
|
+
|
|
60
|
+
def __post_init__(self) -> None:
|
|
61
|
+
if self.fps <= 0:
|
|
62
|
+
raise ValueError(f"a frame rate must be above 0: {self.fps}")
|
|
63
|
+
|
|
64
|
+
@classmethod
|
|
65
|
+
def parse(cls, value: Number) -> Rate:
|
|
66
|
+
"""From ffprobe's "30000/1001" (or "25", 25, 29.97 as written)."""
|
|
67
|
+
return cls(rational(value))
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def frame_s(self) -> Fraction:
|
|
71
|
+
"""How long one frame lasts."""
|
|
72
|
+
return 1 / self.fps
|
|
73
|
+
|
|
74
|
+
def frame_at(self, t: Fraction) -> int:
|
|
75
|
+
"""The frame showing at `t` (a time on a frame's start is that frame): floor(t * fps)."""
|
|
76
|
+
return math.floor(t * self.fps)
|
|
77
|
+
|
|
78
|
+
def time_of(self, frame: int) -> Fraction:
|
|
79
|
+
"""When `frame` starts."""
|
|
80
|
+
return frame / self.fps
|
|
81
|
+
|
|
82
|
+
def snap(self, t: Fraction) -> Fraction:
|
|
83
|
+
"""The frame start nearest `t`; exactly halfway goes to the earlier frame, so snapping never moves a cut past the frame it was in."""
|
|
84
|
+
n = t * self.fps
|
|
85
|
+
lower = math.floor(n)
|
|
86
|
+
return self.time_of(lower if n - lower <= Fraction(1, 2) else lower + 1)
|
|
87
|
+
|
|
88
|
+
def __str__(self) -> str:
|
|
89
|
+
return text(self.fps)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass(frozen=True, order=True)
|
|
93
|
+
class Span:
|
|
94
|
+
"""A stretch of time, half-open: [start, end). Two spans that meet (one's end is the other's start) do not overlap."""
|
|
95
|
+
|
|
96
|
+
start: Fraction
|
|
97
|
+
end: Fraction
|
|
98
|
+
|
|
99
|
+
def __post_init__(self) -> None:
|
|
100
|
+
if self.end < self.start:
|
|
101
|
+
raise ValueError(f"a span cannot end before it starts: [{self.start}, {self.end})")
|
|
102
|
+
|
|
103
|
+
@classmethod
|
|
104
|
+
def of(cls, start: Number, end: Number) -> Span:
|
|
105
|
+
return cls(rational(start), rational(end))
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def duration(self) -> Fraction:
|
|
109
|
+
return self.end - self.start
|
|
110
|
+
|
|
111
|
+
def __contains__(self, t: object) -> bool:
|
|
112
|
+
return isinstance(t, (int, Fraction)) and self.start <= t < self.end
|
|
113
|
+
|
|
114
|
+
def overlaps(self, other: Span) -> bool:
|
|
115
|
+
"""They share some time; an empty span shares none, even inside another (the same answer as `&`)."""
|
|
116
|
+
return (self & other) is not None
|
|
117
|
+
|
|
118
|
+
def __and__(self, other: Span) -> Span | None:
|
|
119
|
+
"""The overlap of two spans, or None when they share no time."""
|
|
120
|
+
start, end = max(self.start, other.start), min(self.end, other.end)
|
|
121
|
+
return Span(start, end) if start < end else None
|
|
122
|
+
|
|
123
|
+
def shift(self, by: Fraction) -> Span:
|
|
124
|
+
return Span(self.start + by, self.end + by)
|
|
125
|
+
|
|
126
|
+
def frames(self, rate: Rate) -> range:
|
|
127
|
+
"""The frames whose start lies in the span: the frames a cut [start, end) keeps."""
|
|
128
|
+
first = math.ceil(self.start * rate.fps)
|
|
129
|
+
last = math.ceil(self.end * rate.fps)
|
|
130
|
+
return range(first, last)
|
|
131
|
+
|
|
132
|
+
def to_json(self) -> list[str]:
|
|
133
|
+
return [text(self.start), text(self.end)]
|
|
134
|
+
|
|
135
|
+
@classmethod
|
|
136
|
+
def from_json(cls, value: Sequence[Number]) -> Span:
|
|
137
|
+
if len(value) != 2:
|
|
138
|
+
raise ValueError(f"a span is [start, end]: {value!r}")
|
|
139
|
+
return cls.of(value[0], value[1])
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@dataclass(frozen=True)
|
|
143
|
+
class Piece:
|
|
144
|
+
"""One stretch of a source placed in the output: `source` from `src.start` to `src.end` plays from output time `at`, at `speed` (2 = twice as
|
|
145
|
+
fast, so it lasts half as long in the output). A freeze frame is not a speed of 0: give it its own piece of one frame and a slow speed."""
|
|
146
|
+
|
|
147
|
+
source: str
|
|
148
|
+
src: Span
|
|
149
|
+
at: Fraction
|
|
150
|
+
speed: Fraction = Fraction(1)
|
|
151
|
+
|
|
152
|
+
def __post_init__(self) -> None:
|
|
153
|
+
if self.speed <= 0:
|
|
154
|
+
raise ValueError(f"speed must be above 0: {self.speed}")
|
|
155
|
+
if self.src.duration == 0:
|
|
156
|
+
raise ValueError(f"a piece of {self.source} plays nothing: {self.src}")
|
|
157
|
+
|
|
158
|
+
@property
|
|
159
|
+
def out(self) -> Span:
|
|
160
|
+
"""Where the piece sits in the output."""
|
|
161
|
+
return Span(self.at, self.at + self.src.duration / self.speed)
|
|
162
|
+
|
|
163
|
+
def to_source(self, t: Fraction) -> Fraction:
|
|
164
|
+
return self.src.start + (t - self.at) * self.speed
|
|
165
|
+
|
|
166
|
+
def to_output(self, s: Fraction) -> Fraction:
|
|
167
|
+
return self.at + (s - self.src.start) / self.speed
|
|
168
|
+
|
|
169
|
+
def to_json(self) -> dict[str, Any]:
|
|
170
|
+
d: dict[str, Any] = {"source": self.source, "src": self.src.to_json(), "at": text(self.at)}
|
|
171
|
+
if self.speed != 1:
|
|
172
|
+
d["speed"] = text(self.speed)
|
|
173
|
+
return d
|
|
174
|
+
|
|
175
|
+
@classmethod
|
|
176
|
+
def from_json(cls, d: dict[str, Any]) -> Piece:
|
|
177
|
+
return cls(str(d["source"]), Span.from_json(d["src"]), rational(d["at"]), rational(d.get("speed", 1)))
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
@dataclass(frozen=True)
|
|
181
|
+
class TimeMap:
|
|
182
|
+
"""Output time to source time for one track of an edit: pieces in output order, never overlapping in the output (gaps are allowed: nothing
|
|
183
|
+
plays there). `to_source` answers what is showing; `to_output` answers every place a source moment is used (it may be used twice)."""
|
|
184
|
+
|
|
185
|
+
pieces: tuple[Piece, ...] = ()
|
|
186
|
+
_starts: tuple[Fraction, ...] = field(default=(), init=False, repr=False, compare=False)
|
|
187
|
+
|
|
188
|
+
def __post_init__(self) -> None:
|
|
189
|
+
ordered = tuple(sorted(self.pieces, key=lambda p: p.at))
|
|
190
|
+
for a, b in itertools.pairwise(ordered):
|
|
191
|
+
if a.out.overlaps(b.out):
|
|
192
|
+
raise ValueError(f"pieces overlap in the output: {a.out} and {b.out}")
|
|
193
|
+
object.__setattr__(self, "pieces", ordered)
|
|
194
|
+
object.__setattr__(self, "_starts", tuple(p.at for p in ordered))
|
|
195
|
+
|
|
196
|
+
@classmethod
|
|
197
|
+
def sequence(cls, ranges: Iterable[tuple[str, Span]], start: Fraction = Fraction(0)) -> TimeMap:
|
|
198
|
+
"""Source ranges played one after the other with no gap, from output time `start`: a cut list."""
|
|
199
|
+
pieces: list[Piece] = []
|
|
200
|
+
at = start
|
|
201
|
+
for source, src in ranges:
|
|
202
|
+
pieces.append(Piece(source, src, at))
|
|
203
|
+
at += src.duration
|
|
204
|
+
return cls(tuple(pieces))
|
|
205
|
+
|
|
206
|
+
@property
|
|
207
|
+
def duration(self) -> Fraction:
|
|
208
|
+
"""The end of the last piece (gaps included)."""
|
|
209
|
+
return self.pieces[-1].out.end if self.pieces else Fraction(0)
|
|
210
|
+
|
|
211
|
+
def piece_at(self, t: Fraction) -> Piece | None:
|
|
212
|
+
i = bisect.bisect_right(self._starts, t) - 1
|
|
213
|
+
if i < 0:
|
|
214
|
+
return None
|
|
215
|
+
p = self.pieces[i]
|
|
216
|
+
return p if t in p.out else None
|
|
217
|
+
|
|
218
|
+
def to_source(self, t: Fraction) -> tuple[str, Fraction] | None:
|
|
219
|
+
"""(source, source time) showing at output time `t`, or None in a gap or past the end."""
|
|
220
|
+
p = self.piece_at(t)
|
|
221
|
+
return None if p is None else (p.source, p.to_source(t))
|
|
222
|
+
|
|
223
|
+
def to_output(self, source: str, s: Fraction) -> list[Fraction]:
|
|
224
|
+
"""Every output time at which `source` time `s` plays, earliest first (none when the edit leaves it out)."""
|
|
225
|
+
return [p.to_output(s) for p in self.pieces if p.source == source and s in p.src]
|
|
226
|
+
|
|
227
|
+
def to_json(self) -> list[dict[str, Any]]:
|
|
228
|
+
return [p.to_json() for p in self.pieces]
|
|
229
|
+
|
|
230
|
+
@classmethod
|
|
231
|
+
def from_json(cls, value: Iterable[dict[str, Any]]) -> TimeMap:
|
|
232
|
+
return cls(tuple(Piece.from_json(d) for d in value))
|
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:
|
strata_python/settings.py
CHANGED
|
@@ -5,6 +5,7 @@ An app declares its settings once (`Setting`: key, default, optional normaliser)
|
|
|
5
5
|
SETTINGS = Settings("myapp", [Setting("data_dir", default=lambda: "/srv/data", normalise=absolute_path),
|
|
6
6
|
Setting("greeting", default="Hello", normalise=non_empty),
|
|
7
7
|
Setting("workers", default="2", normalise=whole_between(1, 16)),
|
|
8
|
+
Setting("mode", default="mixed", choices=["mixed", "review", "new"]),
|
|
8
9
|
ListSetting("source_roots", item=absolute_path)])
|
|
9
10
|
SETTINGS.get("greeting") # MYAPP_GREETING, else the file, else the default
|
|
10
11
|
SETTINGS.get_int("workers") # typed getters: get_int, get_float, get_bool, get_list
|
|
@@ -14,6 +15,11 @@ Order of precedence: environment variable (`<APP>_<KEY>`, upper-cased, or the na
|
|
|
14
15
|
with `<APP>_HOME`. A stored or environment value that fails its normaliser is ignored (the default applies) rather than crashing the app at start; only `save` raises.
|
|
15
16
|
Values are canonical strings (a normaliser returns the one spelling it accepts), and lists of them: the file is edited by hand as well as by the app.
|
|
16
17
|
|
|
18
|
+
`Settings.model()` describes them for `/api/openapi.json`: a setting with `choices` (or `normalise=one_of(...)`) is a
|
|
19
|
+
`Literal` of them, so the schema has an `enum` and the web app's generated type is the union. `Settings(...,
|
|
20
|
+
numbers=True)` also sends `whole_between` and `number_between` settings as JSON numbers with their range in the schema.
|
|
21
|
+
It is off by default because it changes what `GET /api/settings` sends, so an app turns it on with its web app.
|
|
22
|
+
|
|
17
23
|
Where the values live is a `SettingsStore`: the JSON file by default; `Settings.bind(store)` moves an app onto another one at run time (its database's `settings` table,
|
|
18
24
|
`strata_python.db.settings.TableStore`), copying the file's values in once. The CLI and tests without a database keep the file."""
|
|
19
25
|
|
|
@@ -26,7 +32,7 @@ import tempfile
|
|
|
26
32
|
import threading
|
|
27
33
|
from collections.abc import Callable, Mapping, Sequence
|
|
28
34
|
from dataclasses import dataclass
|
|
29
|
-
from typing import Any, Protocol, cast
|
|
35
|
+
from typing import Any, Literal, Protocol, cast
|
|
30
36
|
|
|
31
37
|
from strata_python.oslib import file_lock
|
|
32
38
|
|
|
@@ -47,34 +53,61 @@ def absolute_path(value: str) -> str:
|
|
|
47
53
|
return os.path.abspath(p)
|
|
48
54
|
|
|
49
55
|
|
|
50
|
-
|
|
51
|
-
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class number_between: # lower case: used as a normaliser function, and was one before it carried its range
|
|
58
|
+
"""Normaliser: a finite number from `lo` to `hi` (GB of memory, a budget in dollars), written the shortest way
|
|
59
|
+
(`"8"`, `"8.5"`). Its range is visible, so `Settings(numbers=True)` puts it in the schema."""
|
|
52
60
|
|
|
53
|
-
|
|
61
|
+
lo: float
|
|
62
|
+
hi: float
|
|
63
|
+
|
|
64
|
+
def __call__(self, value: str) -> str:
|
|
54
65
|
try:
|
|
55
66
|
x = float(value.strip())
|
|
56
67
|
except ValueError:
|
|
57
68
|
raise ValueError("must be a number") from None
|
|
58
|
-
if not math.isfinite(x) or not lo <= x <= hi:
|
|
59
|
-
raise ValueError(f"must be a number from {_num(lo)} to {_num(hi)}")
|
|
69
|
+
if not math.isfinite(x) or not self.lo <= x <= self.hi:
|
|
70
|
+
raise ValueError(f"must be a number from {_num(self.lo)} to {_num(self.hi)}")
|
|
60
71
|
return _num(x)
|
|
61
72
|
|
|
62
|
-
return normalise
|
|
63
73
|
|
|
74
|
+
@dataclass(frozen=True)
|
|
75
|
+
class whole_between: # lower case: as number_between
|
|
76
|
+
"""Normaliser: a whole number from `lo` to `hi` (job slots, a port). Its range is visible, so
|
|
77
|
+
`Settings(numbers=True)` puts it in the schema."""
|
|
64
78
|
|
|
65
|
-
|
|
66
|
-
|
|
79
|
+
lo: int
|
|
80
|
+
hi: int
|
|
67
81
|
|
|
68
|
-
def
|
|
82
|
+
def __call__(self, value: str) -> str:
|
|
69
83
|
try:
|
|
70
84
|
x = int(value.strip())
|
|
71
85
|
except ValueError:
|
|
72
86
|
raise ValueError("must be a whole number") from None
|
|
73
|
-
if not lo <= x <= hi:
|
|
74
|
-
raise ValueError(f"must be a whole number from {lo} to {hi}")
|
|
87
|
+
if not self.lo <= x <= self.hi:
|
|
88
|
+
raise ValueError(f"must be a whole number from {self.lo} to {self.hi}")
|
|
75
89
|
return str(x)
|
|
76
90
|
|
|
77
|
-
|
|
91
|
+
|
|
92
|
+
@dataclass(frozen=True)
|
|
93
|
+
class one_of: # lower case: as number_between
|
|
94
|
+
"""Normaliser: one of `choices`, matched without regard to case and surrounding space and returned as the choice
|
|
95
|
+
is spelled; anything else is refused with the list. `Setting(choices=...)` is the short form. `Settings.model()`
|
|
96
|
+
sees the choices and types the setting as a `Literal` of them."""
|
|
97
|
+
|
|
98
|
+
choices: tuple[str, ...]
|
|
99
|
+
|
|
100
|
+
def __init__(self, choices: Sequence[str]) -> None:
|
|
101
|
+
if not choices:
|
|
102
|
+
raise ValueError("one_of needs at least one choice")
|
|
103
|
+
object.__setattr__(self, "choices", tuple(choices))
|
|
104
|
+
|
|
105
|
+
def __call__(self, value: str) -> str:
|
|
106
|
+
v = value.strip().casefold()
|
|
107
|
+
for choice in self.choices:
|
|
108
|
+
if choice.casefold() == v:
|
|
109
|
+
return choice
|
|
110
|
+
raise ValueError(f"must be one of {', '.join(self.choices)}")
|
|
78
111
|
|
|
79
112
|
|
|
80
113
|
_DATE = re.compile(r"\d{4}-\d{2}-\d{2}")
|
|
@@ -120,10 +153,18 @@ def _identity(value: str) -> str:
|
|
|
120
153
|
|
|
121
154
|
@dataclass(frozen=True)
|
|
122
155
|
class Setting:
|
|
156
|
+
"""One setting. `normalise` turns a value into its one spelling or raises ValueError; `choices` limits it to a
|
|
157
|
+
fixed set (`one_of`, applied after `normalise`), which `set` shows and the API schema types as an enum."""
|
|
158
|
+
|
|
123
159
|
key: str
|
|
124
160
|
default: str | Callable[[], str]
|
|
125
161
|
normalise: Callable[[str], str] = _identity
|
|
126
162
|
env: str | None = None # environment variable; default `<APP>_<KEY>`
|
|
163
|
+
choices: Sequence[str] | None = None
|
|
164
|
+
|
|
165
|
+
def __post_init__(self) -> None:
|
|
166
|
+
if self.choices is not None:
|
|
167
|
+
object.__setattr__(self, "choices", one_of(self.choices).choices) # a tuple, and refuses an empty list
|
|
127
168
|
|
|
128
169
|
def default_value(self) -> str:
|
|
129
170
|
d = self.default
|
|
@@ -133,7 +174,15 @@ class Setting:
|
|
|
133
174
|
"""A stored, environment or saved value as its canonical string; ValueError when it is not acceptable."""
|
|
134
175
|
if not isinstance(raw, str):
|
|
135
176
|
raise ValueError("must be text") # str(5) would pass a hand-edited number off as a deliberate string
|
|
136
|
-
|
|
177
|
+
v = self.normalise(raw)
|
|
178
|
+
return v if self.choices is None else one_of(self.choices)(v)
|
|
179
|
+
|
|
180
|
+
def allowed(self) -> tuple[str, ...] | None:
|
|
181
|
+
"""The fixed set of values, from `choices` or a `one_of` normaliser, else None."""
|
|
182
|
+
if self.choices is not None:
|
|
183
|
+
return tuple(self.choices)
|
|
184
|
+
n = self.normalise
|
|
185
|
+
return n.choices if isinstance(n, one_of) else None
|
|
137
186
|
|
|
138
187
|
|
|
139
188
|
def _no_list() -> list[str]:
|
|
@@ -231,11 +280,19 @@ class JsonFileStore:
|
|
|
231
280
|
|
|
232
281
|
class Settings:
|
|
233
282
|
def __init__(
|
|
234
|
-
self,
|
|
283
|
+
self,
|
|
284
|
+
app: str,
|
|
285
|
+
settings: Sequence[AnySetting],
|
|
286
|
+
*,
|
|
287
|
+
prefix: str | None = None,
|
|
288
|
+
store: SettingsStore | None = None,
|
|
289
|
+
numbers: bool = False,
|
|
235
290
|
) -> None:
|
|
236
291
|
"""`prefix` names the environment variables (`<PREFIX>_HOME`, `<PREFIX>_<KEY>`); default the upper-cased app name with `-` as `_`.
|
|
237
|
-
Give it when an app's variables already have a short form that deployed services use. `store` is where values live (default: the JSON file).
|
|
292
|
+
Give it when an app's variables already have a short form that deployed services use. `store` is where values live (default: the JSON file).
|
|
293
|
+
`numbers=True` makes `model()` type `whole_between`/`number_between` settings as numbers (see the module notes)."""
|
|
238
294
|
self.app = app
|
|
295
|
+
self.numbers = numbers
|
|
239
296
|
self.prefix = prefix or app.upper().replace("-", "_")
|
|
240
297
|
self._by_key: dict[str, AnySetting] = {s.key: s for s in settings}
|
|
241
298
|
self.file = JsonFileStore(self.path)
|
|
@@ -308,6 +365,11 @@ class Settings:
|
|
|
308
365
|
s = self._by_key[key]
|
|
309
366
|
return s.sep.join(v) if isinstance(s, ListSetting) and isinstance(v, list) else cast("str", v)
|
|
310
367
|
|
|
368
|
+
def allowed(self, key: str) -> tuple[str, ...] | None:
|
|
369
|
+
"""The values setting `key` may take, when it has a fixed set (`choices` or `one_of`), else None."""
|
|
370
|
+
s = self._by_key[key]
|
|
371
|
+
return s.allowed() if isinstance(s, Setting) else None
|
|
372
|
+
|
|
311
373
|
def get_list(self, key: str) -> list[str]:
|
|
312
374
|
s = self._by_key[key]
|
|
313
375
|
if not isinstance(s, ListSetting):
|
|
@@ -327,18 +389,30 @@ class Settings:
|
|
|
327
389
|
return {k: self.value(k) for k in self._by_key}
|
|
328
390
|
|
|
329
391
|
def model(self) -> type[Any]:
|
|
330
|
-
"""The settings as a pydantic model
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
a
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
}
|
|
392
|
+
"""The settings as a pydantic model, named `<App>Settings`: a field per setting, `str` (a `Literal` of its
|
|
393
|
+
choices when it has them; with `numbers=True`, `int` or `float` with its range for `whole_between` and
|
|
394
|
+
`number_between`), or `list[str]` for a `ListSetting`. `web.base_app` declares it as the settings routes'
|
|
395
|
+
response, so `/api/openapi.json` describes each setting and a web app's types can be generated from it. Built
|
|
396
|
+
on each call; pydantic is imported here, so a CLI that only reads settings does not load it."""
|
|
397
|
+
from pydantic import Field, create_model
|
|
398
|
+
|
|
399
|
+
fields: dict[str, Any] = {k: self._field(s, Field) for k, s in self._by_key.items()}
|
|
339
400
|
name = "".join(p.capitalize() for p in re.split(r"[^0-9A-Za-z]+", self.app) if p) + "Settings"
|
|
340
401
|
return create_model(name, **fields)
|
|
341
402
|
|
|
403
|
+
def _field(self, s: AnySetting, field: Callable[..., Any]) -> tuple[Any, Any]:
|
|
404
|
+
if isinstance(s, ListSetting):
|
|
405
|
+
return list[str], ...
|
|
406
|
+
allowed = s.allowed()
|
|
407
|
+
if allowed is not None:
|
|
408
|
+
return Literal[allowed], ... # pyright: ignore[reportInvalidTypeForm] - a Literal built at run time # ty: ignore[invalid-type-form]
|
|
409
|
+
n = s.normalise
|
|
410
|
+
if self.numbers and isinstance(n, whole_between):
|
|
411
|
+
return int, field(..., ge=n.lo, le=n.hi)
|
|
412
|
+
if self.numbers and isinstance(n, number_between):
|
|
413
|
+
return float, field(..., ge=n.lo, le=n.hi)
|
|
414
|
+
return str, ...
|
|
415
|
+
|
|
342
416
|
def folder(self, key: str) -> str:
|
|
343
417
|
"""The setting `key` as a folder that exists (created when asked for)."""
|
|
344
418
|
p = self.get(key)
|