strata-python 0.2.1__py3-none-any.whl → 0.2.2__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 +99 -20
- strata_python/clients/__init__.py +2 -0
- strata_python/clients/models.py +780 -0
- strata_python/db/__init__.py +6 -3
- strata_python/db/models.py +15 -3
- strata_python/db/project.py +29 -16
- strata_python/db/pytest_plugin.py +63 -9
- strata_python/db/settings.py +63 -0
- strata_python/oslib.py +44 -5
- strata_python/pages/__init__.py +21 -0
- strata_python/pages/model.py +241 -0
- strata_python/pages/render.py +273 -0
- strata_python/public_check.py +54 -8
- strata_python/settings.py +243 -42
- strata_python/web.py +15 -6
- {strata_python-0.2.1.dist-info → strata_python-0.2.2.dist-info}/METADATA +78 -18
- {strata_python-0.2.1.dist-info → strata_python-0.2.2.dist-info}/RECORD +20 -14
- {strata_python-0.2.1.dist-info → strata_python-0.2.2.dist-info}/WHEEL +0 -0
- {strata_python-0.2.1.dist-info → strata_python-0.2.2.dist-info}/entry_points.txt +0 -0
- {strata_python-0.2.1.dist-info → strata_python-0.2.2.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
"""Draw page descriptions as a PDF with real text, and read a PDF back as pixels and text (the `[pdf]` extra).
|
|
2
|
+
|
|
3
|
+
pdf = render(page, fonts={"old-standard": "/srv/fonts/OldStandardTT-Regular.ttf"})
|
|
4
|
+
img = rasterise(pdf, dpi=page.dpi) # the same pixels as the scan, to compare ink
|
|
5
|
+
text = read_text(pdf) # what a reader of the PDF gets, in reading order
|
|
6
|
+
|
|
7
|
+
What the renderer does with a description, so a reader knows what to give it:
|
|
8
|
+
- Each line is set on its baseline, from the left of its box (centred or right-aligned in the box for a block aligned
|
|
9
|
+
so), span after span. Blocks are drawn in reading order, so the PDF's text reads back in that order.
|
|
10
|
+
- A span's size is its `size_pt`, else its line's, else `SIZE_OF_BOX` times the line box's height.
|
|
11
|
+
- `tracking_em`, `hscale` and `stroke_em` (a stroke round the glyphs) are applied as given, and a span's own `x`
|
|
12
|
+
and `baseline_y` (a font matcher's per-word fit) place it; a line with placed spans is not fitted again. With `fit` (the default) the glyph spacing of the line is then
|
|
13
|
+
nudged, by at most `FIT_LIMIT_EM` a glyph, so the line fills its box: a near face then lands where the print was
|
|
14
|
+
without the glyphs themselves being stretched.
|
|
15
|
+
- `small-caps` is drawn as capitals with the lower-case letters at `SMALL_CAP` of the size, unless the span's face is a
|
|
16
|
+
small-caps cut (named in `small_caps_faces`), which draws the text as it is; `caps` upper-cases the text.
|
|
17
|
+
- A span with no face, or a face missing from `fonts`, gets the standard PDF face for its style (Times), so a layout
|
|
18
|
+
draws before any font is matched.
|
|
19
|
+
- Figures are drawn first, each crop stretched to its box.
|
|
20
|
+
ReportLab and pdfium have no type stubs, so they are reached through `Any` here; the types of this module's own
|
|
21
|
+
functions are complete."""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import hashlib
|
|
26
|
+
import importlib
|
|
27
|
+
import io
|
|
28
|
+
import os
|
|
29
|
+
from collections.abc import Collection, Mapping, Sequence
|
|
30
|
+
from dataclasses import dataclass
|
|
31
|
+
from typing import TYPE_CHECKING, Any
|
|
32
|
+
|
|
33
|
+
from strata_python.pages.model import Block, Line, Page, PageError, Span
|
|
34
|
+
|
|
35
|
+
if TYPE_CHECKING:
|
|
36
|
+
from PIL import Image
|
|
37
|
+
|
|
38
|
+
SIZE_OF_BOX = (
|
|
39
|
+
0.9 # a Tesseract line box runs from the tallest capital or ascender to the lowest descender: about 0.9-1.1 em
|
|
40
|
+
)
|
|
41
|
+
DESCENT_EM = (
|
|
42
|
+
0.22 # with no baseline given, the baseline sits this far above the box's bottom (a book face's descenders)
|
|
43
|
+
)
|
|
44
|
+
SMALL_CAP = 0.78 # synthesised small capitals: the lower-case letters' size as a share of the capitals'
|
|
45
|
+
FIT_LIMIT_EM = 0.1 # the most a line's glyph spacing is changed to fit its box, in ems a glyph
|
|
46
|
+
STANDARD = {
|
|
47
|
+
"roman": "Times-Roman",
|
|
48
|
+
"italic": "Times-Italic",
|
|
49
|
+
"bold": "Times-Bold",
|
|
50
|
+
"bold-italic": "Times-BoldItalic",
|
|
51
|
+
"small-caps": "Times-Roman",
|
|
52
|
+
"caps": "Times-Roman",
|
|
53
|
+
"blackletter": "Times-Roman",
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _rl(module: str) -> Any:
|
|
58
|
+
try:
|
|
59
|
+
return importlib.import_module(module)
|
|
60
|
+
except ImportError as e: # pragma: no cover (the extra is installed wherever this module's tests run)
|
|
61
|
+
raise ImportError("strata_python.pages.render needs the pdf extra: strata-python[pdf]") from e
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class _Fonts:
|
|
65
|
+
"""The fonts a render may use: each face id's TTF registered with ReportLab once a process, under a name made from
|
|
66
|
+
its path (ReportLab's registry is global, so two apps' faces with the same id must not collide)."""
|
|
67
|
+
|
|
68
|
+
def __init__(self, fonts: Mapping[str, str], small_caps: Collection[str]) -> None:
|
|
69
|
+
self.paths = dict(fonts)
|
|
70
|
+
self.small_caps = set(small_caps)
|
|
71
|
+
self.pdfmetrics: Any = _rl("reportlab.pdfbase.pdfmetrics")
|
|
72
|
+
self.ttfonts: Any = _rl("reportlab.pdfbase.ttfonts")
|
|
73
|
+
|
|
74
|
+
def name(self, span: Span, line: Line) -> str:
|
|
75
|
+
face = span.face or line.face
|
|
76
|
+
path = self.paths.get(face) if face else None
|
|
77
|
+
if not path:
|
|
78
|
+
return STANDARD[span.style]
|
|
79
|
+
if not os.path.isfile(path):
|
|
80
|
+
raise PageError(f"font {face!r}: no such file {path!r}")
|
|
81
|
+
name = "sp-" + hashlib.sha1(os.path.abspath(path).encode()).hexdigest()[:12] # noqa: S324 (a name, not security)
|
|
82
|
+
if name not in self.pdfmetrics.getRegisteredFontNames():
|
|
83
|
+
self.pdfmetrics.registerFont(self.ttfonts.TTFont(name, path))
|
|
84
|
+
return name
|
|
85
|
+
|
|
86
|
+
def is_small_caps_cut(self, span: Span, line: Line) -> bool:
|
|
87
|
+
face = span.face or line.face
|
|
88
|
+
return face is not None and face in self.small_caps and face in self.paths
|
|
89
|
+
|
|
90
|
+
def width(self, text: str, font: str, size: float) -> float:
|
|
91
|
+
return float(self.pdfmetrics.stringWidth(text, font, size))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@dataclass
|
|
95
|
+
class _Run:
|
|
96
|
+
"""Text drawn with one font, size, scale, tracking and weight; `x` and `baseline` (scan pixels) when its span was
|
|
97
|
+
placed by a reader, else it follows the run before it."""
|
|
98
|
+
|
|
99
|
+
text: str
|
|
100
|
+
font: str
|
|
101
|
+
size: float
|
|
102
|
+
hscale: float
|
|
103
|
+
track: float # points a glyph
|
|
104
|
+
weight: float # stroke width in points (0: fill only)
|
|
105
|
+
x: float | None = None
|
|
106
|
+
baseline: float | None = None
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _runs(line: Line, fonts: _Fonts, default_size: float) -> list[_Run]:
|
|
110
|
+
out: list[_Run] = []
|
|
111
|
+
for span in line.spans:
|
|
112
|
+
size = span.size_pt or line.size_pt or default_size
|
|
113
|
+
font = fonts.name(span, line)
|
|
114
|
+
track, weight = span.tracking_em * size, max(span.stroke_em, 0.0) * size
|
|
115
|
+
text = span.text.upper() if span.style == "caps" else span.text
|
|
116
|
+
if span.style != "small-caps" or fonts.is_small_caps_cut(span, line):
|
|
117
|
+
out.append(_Run(text, font, size, span.hscale, track, weight, span.x, span.baseline_y))
|
|
118
|
+
continue
|
|
119
|
+
# capitals as they are, lower case as smaller capitals; split where the case changes so each piece is one run
|
|
120
|
+
# (only the first piece is placed where the span was measured; the rest follow it)
|
|
121
|
+
pieces: list[tuple[str, bool]] = []
|
|
122
|
+
for ch in text:
|
|
123
|
+
if pieces and pieces[-1][1] == ch.islower():
|
|
124
|
+
pieces[-1] = (pieces[-1][0] + ch, pieces[-1][1])
|
|
125
|
+
else:
|
|
126
|
+
pieces.append((ch, ch.islower()))
|
|
127
|
+
for i, (piece, small) in enumerate(pieces):
|
|
128
|
+
first = i == 0
|
|
129
|
+
out.append(
|
|
130
|
+
_Run(
|
|
131
|
+
piece.upper(),
|
|
132
|
+
font,
|
|
133
|
+
size * SMALL_CAP if small else size,
|
|
134
|
+
span.hscale,
|
|
135
|
+
track,
|
|
136
|
+
weight,
|
|
137
|
+
span.x if first else None,
|
|
138
|
+
span.baseline_y,
|
|
139
|
+
)
|
|
140
|
+
)
|
|
141
|
+
return out
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _run_width(fonts: _Fonts, run: _Run, extra: float = 0.0) -> float:
|
|
145
|
+
return fonts.width(run.text, run.font, run.size) * run.hscale + (run.track + extra) * len(run.text)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _draw_line(c: Any, line: Line, block: Block, fonts: _Fonts, k: float, page_h_pt: float, fit: bool) -> None:
|
|
149
|
+
x_px, y_px, w_px, h_px = line.box
|
|
150
|
+
runs = [r for r in _runs(line, fonts, max(h_px * k * SIZE_OF_BOX, 1.0)) if r.text]
|
|
151
|
+
glyphs = sum(len(r.text) for r in runs)
|
|
152
|
+
if not glyphs:
|
|
153
|
+
return
|
|
154
|
+
placed = any(r.x is not None for r in runs)
|
|
155
|
+
natural = sum(_run_width(fonts, r) for r in runs)
|
|
156
|
+
box_w = w_px * k
|
|
157
|
+
extra = 0.0
|
|
158
|
+
if fit and not placed and box_w > 0 and glyphs > 1:
|
|
159
|
+
mean_size = sum(r.size * len(r.text) for r in runs) / glyphs
|
|
160
|
+
limit = FIT_LIMIT_EM * mean_size
|
|
161
|
+
extra = max(-limit, min(limit, (box_w - natural) / glyphs))
|
|
162
|
+
width = natural + extra * glyphs
|
|
163
|
+
x = x_px * k
|
|
164
|
+
if not placed and block.align == "centre":
|
|
165
|
+
x += (box_w - width) / 2
|
|
166
|
+
elif not placed and block.align == "right":
|
|
167
|
+
x += box_w - width
|
|
168
|
+
line_base = line.baseline_y if line.baseline_y is not None else y_px + h_px - DESCENT_EM * runs[0].size / k
|
|
169
|
+
for r in runs: # one text object a run: ReportLab's cursor does not count tracking or scale, so x is ours
|
|
170
|
+
if r.x is not None:
|
|
171
|
+
x = r.x * k
|
|
172
|
+
t = c.beginText(x, page_h_pt - (r.baseline if r.baseline is not None else line_base) * k)
|
|
173
|
+
t.setFont(r.font, r.size)
|
|
174
|
+
t.setHorizScale(r.hscale * 100)
|
|
175
|
+
# PDF scales character spacing by the horizontal scale too (Tz applies to Tc): divide it out, so tracking and
|
|
176
|
+
# fitting are the advance on the page that _run_width counts
|
|
177
|
+
t.setCharSpace((r.track + extra) / r.hscale)
|
|
178
|
+
if r.weight > 0: # fill and stroke the glyphs: heavier print than the face's own weight
|
|
179
|
+
t.setTextRenderMode(2)
|
|
180
|
+
t.textOut(r.text)
|
|
181
|
+
if r.weight > 0:
|
|
182
|
+
# the render mode and line width are graphics state that outlive the text object (and ReportLab assumes a
|
|
183
|
+
# fresh one is fill-only, so it never sets 0 again): save and restore round the run, or every later word
|
|
184
|
+
# on the page would be stroked too
|
|
185
|
+
c.saveState()
|
|
186
|
+
c.setLineWidth(r.weight)
|
|
187
|
+
c.drawText(t)
|
|
188
|
+
c.restoreState()
|
|
189
|
+
else:
|
|
190
|
+
c.drawText(t)
|
|
191
|
+
x += _run_width(fonts, r, extra)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _draw_page(c: Any, page: Page, fonts: _Fonts, fit: bool) -> None:
|
|
195
|
+
k = 72.0 / page.dpi # scan pixels to points
|
|
196
|
+
w_pt, h_pt = page.width * k, page.height * k
|
|
197
|
+
c.setPageSize((w_pt, h_pt))
|
|
198
|
+
for f in page.figures:
|
|
199
|
+
if f.image is None:
|
|
200
|
+
continue
|
|
201
|
+
if not os.path.isfile(f.image):
|
|
202
|
+
raise PageError(f"figure at {list(f.box)}: no such picture {f.image!r}")
|
|
203
|
+
x, y, w, h = f.box
|
|
204
|
+
c.drawImage(f.image, x * k, h_pt - (y + h) * k, w * k, h * k)
|
|
205
|
+
for block in page.reading_order():
|
|
206
|
+
for line in block.lines:
|
|
207
|
+
_draw_line(c, line, block, fonts, k, h_pt, fit)
|
|
208
|
+
c.showPage()
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def render(
|
|
212
|
+
pages: Page | Sequence[Page],
|
|
213
|
+
fonts: Mapping[str, str] | None = None,
|
|
214
|
+
*,
|
|
215
|
+
small_caps_faces: Collection[str] = (),
|
|
216
|
+
fit: bool = True,
|
|
217
|
+
title: str | None = None,
|
|
218
|
+
) -> bytes:
|
|
219
|
+
"""The PDF of one page or several (one PDF page each, sized from the scan's pixels and dpi). `fonts` maps face ids
|
|
220
|
+
to TTF or OTF files with TrueType outlines; the faces used are embedded (subset). The output is the same bytes for
|
|
221
|
+
the same input (no creation date or random id), so a cached rebuild compares by hash."""
|
|
222
|
+
canvas: Any = _rl("reportlab.pdfgen.canvas")
|
|
223
|
+
buf = io.BytesIO()
|
|
224
|
+
c = canvas.Canvas(buf, invariant=1, pageCompression=1)
|
|
225
|
+
if title:
|
|
226
|
+
c.setTitle(title)
|
|
227
|
+
f = _Fonts(fonts or {}, small_caps_faces)
|
|
228
|
+
for page in [pages] if isinstance(pages, Page) else pages:
|
|
229
|
+
_draw_page(c, page, f, fit)
|
|
230
|
+
c.save()
|
|
231
|
+
return buf.getvalue()
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _document(pdf: bytes) -> Any:
|
|
235
|
+
return _rl("pypdfium2").PdfDocument(pdf)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def page_count(pdf: bytes) -> int:
|
|
239
|
+
doc = _document(pdf)
|
|
240
|
+
try:
|
|
241
|
+
return len(doc)
|
|
242
|
+
finally:
|
|
243
|
+
doc.close()
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def rasterise(pdf: bytes, page: int = 0, dpi: float = 300.0) -> Image.Image:
|
|
247
|
+
"""One page of a PDF as a greyscale picture at `dpi` (the scan's dpi gives the scan's size in pixels), white paper."""
|
|
248
|
+
doc = _document(pdf)
|
|
249
|
+
try:
|
|
250
|
+
if not 0 <= page < len(doc):
|
|
251
|
+
raise PageError(f"no page {page} in a PDF of {len(doc)}")
|
|
252
|
+
p = doc[page]
|
|
253
|
+
img = p.render(scale=dpi / 72.0).to_pil().convert("L")
|
|
254
|
+
p.close()
|
|
255
|
+
return img
|
|
256
|
+
finally:
|
|
257
|
+
doc.close()
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def read_text(pdf: bytes, page: int | None = None) -> str:
|
|
261
|
+
"""The text a reader gets from the PDF (one page, or every page with a form feed between), in drawing order."""
|
|
262
|
+
doc = _document(pdf)
|
|
263
|
+
try:
|
|
264
|
+
out: list[str] = []
|
|
265
|
+
for i in [page] if page is not None else range(len(doc)):
|
|
266
|
+
p = doc[i]
|
|
267
|
+
tp = p.get_textpage()
|
|
268
|
+
out.append(str(tp.get_text_range()).replace("\r\n", "\n").replace("\r", "\n"))
|
|
269
|
+
tp.close()
|
|
270
|
+
p.close()
|
|
271
|
+
return "\f".join(out)
|
|
272
|
+
finally:
|
|
273
|
+
doc.close()
|
strata_python/public_check.py
CHANGED
|
@@ -5,6 +5,14 @@ release workflow scans the built sdist and wheel (and CI scans the tree) before
|
|
|
5
5
|
catch what is personal in any repo: email addresses, private IPv4 addresses and home-folder paths. Names that are
|
|
6
6
|
personal to one owner (a person, a host name, a port map) cannot be listed here without publishing them, so they come
|
|
7
7
|
from the `STRATA_PUBLIC_DENY` environment variable (one case-insensitive regex per line), which CI fills from a secret.
|
|
8
|
+
|
|
9
|
+
False positives left after that are silenced in the repo, where a reviewer sees them:
|
|
10
|
+
|
|
11
|
+
- `[tool.strata-public-check] exclude = ["web/package-lock.json"]` in pyproject.toml (or `--exclude`): glob patterns
|
|
12
|
+
matched against each file's path in the folder or archive, or any trailing part of it (so an sdist's
|
|
13
|
+
`pkg-1.0/web/package-lock.json` matches too). An excluded file skips the built-in patterns only.
|
|
14
|
+
- `strata-public-check: ignore` anywhere on a line skips the built-in patterns on that line. Never the owner's
|
|
15
|
+
`STRATA_PUBLIC_DENY` patterns: a name the owner listed is never one to publish.
|
|
8
16
|
"""
|
|
9
17
|
|
|
10
18
|
from __future__ import annotations
|
|
@@ -15,12 +23,17 @@ import os
|
|
|
15
23
|
import re
|
|
16
24
|
import sys
|
|
17
25
|
import tarfile
|
|
26
|
+
import tomllib
|
|
18
27
|
import zipfile
|
|
19
28
|
from collections.abc import Iterable, Iterator
|
|
20
29
|
from dataclasses import dataclass
|
|
30
|
+
from fnmatch import fnmatchcase
|
|
21
31
|
from pathlib import Path
|
|
32
|
+
from typing import Any, cast
|
|
22
33
|
|
|
23
34
|
DENY_ENV = "STRATA_PUBLIC_DENY"
|
|
35
|
+
TABLE = "strata-public-check"
|
|
36
|
+
IGNORE = "strata-public-check: ignore"
|
|
24
37
|
|
|
25
38
|
# Placeholders the docs use on purpose (AGENTS.md: examples use /home/ada/..., myapp).
|
|
26
39
|
PLACEHOLDER_USERS = {"ada", "user", "me", "you", "name", "myapp", "runner"}
|
|
@@ -31,7 +44,11 @@ BUILT_IN: dict[str, re.Pattern[str]] = {
|
|
|
31
44
|
"email address": re.compile(
|
|
32
45
|
r"\b(?!noreply@anthropic\.com\b)[A-Za-z0-9._%+-]+@(?!users\.noreply\.github\.com\b)[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}\b"
|
|
33
46
|
),
|
|
34
|
-
|
|
47
|
+
# A whole dotted quad and nothing more: a three-part version (`10.4.2` in package.json, issue #13) or a longer
|
|
48
|
+
# dotted number is not an address. The lookarounds stop a match inside a longer run of digits and dots.
|
|
49
|
+
"private IPv4 address": re.compile(
|
|
50
|
+
r"(?<![\w.])(?:10(?:\.\d{1,3}){3}|192\.168(?:\.\d{1,3}){2}|172\.(?:1[6-9]|2\d|3[01])(?:\.\d{1,3}){2})(?!\.?\d)"
|
|
51
|
+
),
|
|
35
52
|
"home folder path": re.compile(r"(?:/home/|/Users/|[A-Za-z]:\\+Users\\+)(?P<user>[A-Za-z0-9._-]+)"),
|
|
36
53
|
}
|
|
37
54
|
|
|
@@ -62,10 +79,13 @@ def deny_patterns(env: str | None = None) -> list[re.Pattern[str]]:
|
|
|
62
79
|
return [re.compile(line.strip(), re.IGNORECASE) for line in raw.splitlines() if line.strip()]
|
|
63
80
|
|
|
64
81
|
|
|
65
|
-
def scan_text(
|
|
82
|
+
def scan_text(
|
|
83
|
+
where: str, text: str, extra: Iterable[re.Pattern[str]] = (), *, built_in: bool = True
|
|
84
|
+
) -> Iterator[Finding]:
|
|
85
|
+
"""Findings in one file's text. `built_in=False` (an excluded file) checks only the owner's patterns."""
|
|
66
86
|
extra = list(extra)
|
|
67
87
|
for number, line in enumerate(text.splitlines(), 1):
|
|
68
|
-
for kind, pattern in BUILT_IN.items():
|
|
88
|
+
for kind, pattern in BUILT_IN.items() if built_in and IGNORE not in line else ():
|
|
69
89
|
for match in pattern.finditer(line):
|
|
70
90
|
if kind == "home folder path" and match.group("user").lower() in PLACEHOLDER_USERS:
|
|
71
91
|
continue
|
|
@@ -76,6 +96,20 @@ def scan_text(where: str, text: str, extra: Iterable[re.Pattern[str]] = ()) -> I
|
|
|
76
96
|
yield Finding(where, number, f"matches {DENY_ENV} pattern", "(hidden)")
|
|
77
97
|
|
|
78
98
|
|
|
99
|
+
def excluded(name: str, patterns: Iterable[str]) -> bool:
|
|
100
|
+
"""Whether a path (posix, relative to its folder or archive) matches an exclude pattern, whole or at its end."""
|
|
101
|
+
return any(fnmatchcase(name, p) or fnmatchcase(name, "*/" + p) for p in patterns)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def config_excludes(root: Path | None = None) -> list[str]:
|
|
105
|
+
"""`exclude` from `[tool.strata-public-check]` in root's (default: the current folder's) pyproject.toml."""
|
|
106
|
+
f = (root or Path()) / "pyproject.toml"
|
|
107
|
+
if not f.is_file():
|
|
108
|
+
return []
|
|
109
|
+
tool = cast("dict[str, Any]", tomllib.loads(f.read_text(encoding="utf-8")).get("tool", {}))
|
|
110
|
+
return [str(p) for p in cast("dict[str, Any]", tool.get(TABLE, {})).get("exclude", [])]
|
|
111
|
+
|
|
112
|
+
|
|
79
113
|
def _is_text(name: str) -> bool:
|
|
80
114
|
path = Path(name)
|
|
81
115
|
hidden = any(part.startswith(".") and part != ".github" for part in path.parts[:-1])
|
|
@@ -103,14 +137,19 @@ def _members(path: Path) -> Iterator[tuple[str, bytes]]:
|
|
|
103
137
|
yield path.as_posix(), path.read_bytes()
|
|
104
138
|
|
|
105
139
|
|
|
106
|
-
def scan(paths: Iterable[Path], extra: Iterable[re.Pattern[str]] = ()) -> list[Finding]:
|
|
107
|
-
"""Every finding in the given folders, files, sdists (.tar.gz) and wheels (.whl)."""
|
|
108
|
-
extra = list(extra)
|
|
140
|
+
def scan(paths: Iterable[Path], extra: Iterable[re.Pattern[str]] = (), exclude: Iterable[str] = ()) -> list[Finding]:
|
|
141
|
+
"""Every finding in the given folders, files, sdists (.tar.gz) and wheels (.whl), less the excluded files."""
|
|
142
|
+
extra, exclude = list(extra), list(exclude)
|
|
109
143
|
findings: list[Finding] = []
|
|
110
144
|
for path in paths:
|
|
111
145
|
for where, data in _members(path):
|
|
146
|
+
skip = excluded(where, exclude)
|
|
147
|
+
if skip and not extra:
|
|
148
|
+
continue
|
|
112
149
|
text = io.TextIOWrapper(io.BytesIO(data), encoding="utf-8", errors="replace").read()
|
|
113
|
-
|
|
150
|
+
# an excluded file is still checked against the owner's patterns: an exclude is for false positives of the
|
|
151
|
+
# 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))
|
|
114
153
|
return findings
|
|
115
154
|
|
|
116
155
|
|
|
@@ -119,8 +158,15 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
119
158
|
prog="strata-public-check", description="Refuse to publish personal or machine-specific details."
|
|
120
159
|
)
|
|
121
160
|
parser.add_argument("paths", nargs="*", type=Path, default=[Path()], help="folders, files, sdists or wheels")
|
|
161
|
+
parser.add_argument(
|
|
162
|
+
"--exclude",
|
|
163
|
+
action="append",
|
|
164
|
+
default=[],
|
|
165
|
+
metavar="GLOB",
|
|
166
|
+
help=f"skip matching files, as well as [tool.{TABLE}] exclude in ./pyproject.toml",
|
|
167
|
+
)
|
|
122
168
|
args = parser.parse_args(argv)
|
|
123
|
-
findings = scan(args.paths, deny_patterns())
|
|
169
|
+
findings = scan(args.paths, deny_patterns(), [*config_excludes(), *args.exclude])
|
|
124
170
|
for finding in findings:
|
|
125
171
|
print(finding, file=sys.stderr)
|
|
126
172
|
if findings:
|