prosefix 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.
- prosefix/__init__.py +3 -0
- prosefix/cli.py +428 -0
- prosefix/engine.py +192 -0
- prosefix/jsonout.py +41 -0
- prosefix/settings.py +188 -0
- prosefix/tools.py +26 -0
- prosefix-0.1.0.dist-info/METADATA +132 -0
- prosefix-0.1.0.dist-info/RECORD +11 -0
- prosefix-0.1.0.dist-info/WHEEL +4 -0
- prosefix-0.1.0.dist-info/entry_points.txt +2 -0
- prosefix-0.1.0.dist-info/licenses/LICENSE +21 -0
prosefix/__init__.py
ADDED
prosefix/cli.py
ADDED
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
"""prosefix command line."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import difflib
|
|
7
|
+
import errno
|
|
8
|
+
import functools
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
import sys
|
|
13
|
+
import tempfile
|
|
14
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from adjudicate import ConfigError, Skipped, check_endpoint, resolve_endpoint, run_setup
|
|
19
|
+
from stylefix import styleguides
|
|
20
|
+
|
|
21
|
+
from . import __version__, engine, jsonout, tools
|
|
22
|
+
from .settings import PASSES, TIERS, Settings, SettingsError, find_project, resolve
|
|
23
|
+
|
|
24
|
+
SKIP_DIRS = {".git", ".obsidian", "node_modules"}
|
|
25
|
+
EXTS = {".md", ".markdown"}
|
|
26
|
+
|
|
27
|
+
DESCRIPTION = """\
|
|
28
|
+
Clean, consistent prose in Markdown: stylefix's spelling and style guide, then
|
|
29
|
+
proofix's typos, punctuation and commas, in one pass. Files and directories are
|
|
30
|
+
rewritten in place; - reads stdin and writes stdout. Front matter, code, links,
|
|
31
|
+
HTML and Obsidian syntax are never changed."""
|
|
32
|
+
|
|
33
|
+
EPILOG = """\
|
|
34
|
+
examples:
|
|
35
|
+
prosefix --setup choose and test a model endpoint
|
|
36
|
+
prosefix note.md rewrite one note in place
|
|
37
|
+
prosefix vault/ --diff show what would change in a vault
|
|
38
|
+
prosefix content/ --check --llm cached CI: fail if anything would change
|
|
39
|
+
prosefix - < in.md > out.md filter
|
|
40
|
+
|
|
41
|
+
settings: prosefix.toml, .prosefix.toml or [tool.prosefix] in pyproject.toml,
|
|
42
|
+
found upwards from each file; front matter `prosefix: off` or
|
|
43
|
+
`prosefix: {target: uk}`, or `lang: en-GB`. Flags beat front matter, which
|
|
44
|
+
beats the project file.
|
|
45
|
+
|
|
46
|
+
Full documentation: https://github.com/AndrewBroz/prosefix (man page:
|
|
47
|
+
man/prosefix.1 in the source, installed by the Homebrew formula)."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
51
|
+
p = argparse.ArgumentParser(prog="prosefix", description=DESCRIPTION, epilog=EPILOG,
|
|
52
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
53
|
+
p.add_argument("paths", nargs="*", metavar="PATH", help="files, directories, or - for stdin")
|
|
54
|
+
p.add_argument("-o", "--output", type=Path, metavar="FILE", help="write one file's result here")
|
|
55
|
+
p.add_argument("--stdin-filename", type=Path, metavar="PATH",
|
|
56
|
+
help="with -, the path used for settings lookup, exclude and --json")
|
|
57
|
+
m = p.add_mutually_exclusive_group()
|
|
58
|
+
m.add_argument("--diff", action="store_true", help="print a unified diff; write nothing")
|
|
59
|
+
m.add_argument("--check", action="store_true",
|
|
60
|
+
help="write nothing; exit 1 if any file would change")
|
|
61
|
+
m.add_argument("--json", action="store_true", help="print proposals as JSON (schema 1); write nothing")
|
|
62
|
+
p.add_argument("--strict", action="store_true", help="with --check, review items also fail")
|
|
63
|
+
p.add_argument("--target", choices=["us", "uk"], help="English variety")
|
|
64
|
+
p.add_argument("--style", metavar="GUIDE", choices=styleguides.choices(),
|
|
65
|
+
help="style guide, as stylefix --style: " + ", ".join(styleguides.choices()))
|
|
66
|
+
p.add_argument("--only", choices=PASSES, help="run one pass only")
|
|
67
|
+
p.add_argument("--skip", metavar="TIER,...", help="tiers to skip: " + ", ".join(TIERS))
|
|
68
|
+
p.add_argument("--llm", choices=["auto", "ollama", "none", "cached"], default="auto",
|
|
69
|
+
help="auto: configured endpoint or local Ollama; cached: decisions in the "
|
|
70
|
+
"cache only, never a model; none: rules only (default: %(default)s)")
|
|
71
|
+
p.add_argument("--url", metavar="URL", help="OpenAI-compatible base URL; overrides every configured url")
|
|
72
|
+
p.add_argument("--model", metavar="NAME", help="model name at the endpoint")
|
|
73
|
+
p.add_argument("--timeout", type=float, metavar="SEC", help="seconds per model request")
|
|
74
|
+
p.add_argument("--no-cache", action="store_true", help="neither read nor write the decision cache")
|
|
75
|
+
p.add_argument("--require", metavar="TOOL,...",
|
|
76
|
+
help="fail (exit 2) if any of vale, languagetool, typos, model is missing")
|
|
77
|
+
p.add_argument("--changes", action="store_true", help="print every change to stderr")
|
|
78
|
+
p.add_argument("--report", type=Path, metavar="FILE", help="write a Markdown report of all files")
|
|
79
|
+
p.add_argument("-q", "--quiet", action="store_true", help="only errors on stderr")
|
|
80
|
+
p.add_argument("-j", "--jobs", type=int, default=4, metavar="N", help="files in parallel (default: %(default)s)")
|
|
81
|
+
c = p.add_argument_group("configuration", "set up or check the model endpoint, then exit")
|
|
82
|
+
c.add_argument("--setup", action="store_true", help="choose, test and save a model endpoint")
|
|
83
|
+
c.add_argument("--check-endpoint", action="store_true",
|
|
84
|
+
help="show the endpoint prosefix would use and test it")
|
|
85
|
+
c.add_argument("--doctor", action="store_true",
|
|
86
|
+
help="show which tools, endpoint and settings this machine and directory have")
|
|
87
|
+
p.add_argument("--version", action="version", version=f"prosefix {__version__}")
|
|
88
|
+
return p
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def excluded(rel: str, patterns) -> bool:
|
|
92
|
+
"""rel: posix path relative to the project root. `**` crosses directories; `*` and `?` do not."""
|
|
93
|
+
for pat in patterns:
|
|
94
|
+
rx = _glob_regex(pat)
|
|
95
|
+
if rx.match(rel):
|
|
96
|
+
return True
|
|
97
|
+
return False
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
@functools.lru_cache(maxsize=None)
|
|
101
|
+
def _glob_regex(pat: str) -> re.Pattern:
|
|
102
|
+
out, i = "", 0
|
|
103
|
+
while i < len(pat):
|
|
104
|
+
if pat.startswith("**/", i):
|
|
105
|
+
out += "(?:.*/)?"
|
|
106
|
+
i += 3
|
|
107
|
+
elif pat.startswith("**", i):
|
|
108
|
+
out += ".*"
|
|
109
|
+
i += 2
|
|
110
|
+
elif pat[i] == "*":
|
|
111
|
+
out += "[^/]*"
|
|
112
|
+
i += 1
|
|
113
|
+
elif pat[i] == "?":
|
|
114
|
+
out += "[^/]"
|
|
115
|
+
i += 1
|
|
116
|
+
else:
|
|
117
|
+
out += re.escape(pat[i])
|
|
118
|
+
i += 1
|
|
119
|
+
return re.compile(out + r"\Z")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@dataclass
|
|
123
|
+
class Job:
|
|
124
|
+
label: str
|
|
125
|
+
path: Path | None # None: stdin
|
|
126
|
+
lookup: Path
|
|
127
|
+
text: str | None = None
|
|
128
|
+
error: str | None = None
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _walk(directory: Path):
|
|
132
|
+
for p in sorted(directory.rglob("*")):
|
|
133
|
+
rel = p.relative_to(directory)
|
|
134
|
+
if not p.is_file() or p.suffix not in EXTS:
|
|
135
|
+
continue
|
|
136
|
+
if any(part in SKIP_DIRS or part.startswith(".") for part in rel.parts):
|
|
137
|
+
continue
|
|
138
|
+
yield p
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _is_excluded(p: Path) -> bool:
|
|
142
|
+
try:
|
|
143
|
+
project = find_project(p)
|
|
144
|
+
except SettingsError:
|
|
145
|
+
return False # the job reports it
|
|
146
|
+
if project.root is None:
|
|
147
|
+
return False
|
|
148
|
+
try:
|
|
149
|
+
settings_exclude = project.values.get("exclude", ())
|
|
150
|
+
rel = p.resolve().relative_to(project.root.resolve()).as_posix()
|
|
151
|
+
except ValueError:
|
|
152
|
+
return False
|
|
153
|
+
return excluded(rel, tuple(settings_exclude))
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
class ChangedDuringRun(Exception):
|
|
157
|
+
"""The file on disk is no longer the text that was processed."""
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _read_umask() -> int:
|
|
161
|
+
old = os.umask(0)
|
|
162
|
+
os.umask(old)
|
|
163
|
+
return old
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
_UMASK = 0o022 # read once, at startup, in main()
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _write_atomic(path: Path, text: str, expect: str | None = None) -> None:
|
|
170
|
+
"""Write via a temporary file beside the target, keeping its mode (a new file gets
|
|
171
|
+
0666 less the umask); a crash cannot truncate it. With `expect`, the target is
|
|
172
|
+
re-read just before the rename and left alone if it no longer holds that text."""
|
|
173
|
+
if path.is_symlink():
|
|
174
|
+
path = path.resolve()
|
|
175
|
+
if path.exists() and not os.access(path, os.W_OK): # a rename would bypass a read-only file
|
|
176
|
+
raise PermissionError(errno.EACCES, "Permission denied", str(path))
|
|
177
|
+
mode = path.stat().st_mode & 0o7777 if path.exists() else 0o666 & ~_UMASK
|
|
178
|
+
fd, tmp = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
|
|
179
|
+
try:
|
|
180
|
+
with os.fdopen(fd, "w", encoding="utf-8", newline="") as fh:
|
|
181
|
+
fh.write(text)
|
|
182
|
+
os.chmod(tmp, mode)
|
|
183
|
+
if expect is not None:
|
|
184
|
+
try:
|
|
185
|
+
with open(path, encoding="utf-8", newline="") as fh:
|
|
186
|
+
now = fh.read()
|
|
187
|
+
except (OSError, UnicodeDecodeError):
|
|
188
|
+
now = None
|
|
189
|
+
if now != expect:
|
|
190
|
+
raise ChangedDuringRun(str(path))
|
|
191
|
+
os.replace(tmp, path)
|
|
192
|
+
except BaseException:
|
|
193
|
+
try:
|
|
194
|
+
os.unlink(tmp)
|
|
195
|
+
except OSError:
|
|
196
|
+
pass
|
|
197
|
+
raise
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _err(msg: str) -> None:
|
|
201
|
+
print(f"prosefix: {msg}", file=sys.stderr)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _doctor(args) -> int:
|
|
205
|
+
t = tools.detect()
|
|
206
|
+
for name, found in (("vale", t.vale), ("languagetool", t.languagetool), ("typos", t.typos)):
|
|
207
|
+
print(f"{name:<13}" + (f"found {found}" if found else f"missing {tools.install_hint(name)}"))
|
|
208
|
+
preset = "none" if args.llm in ("none", "cached") else args.llm
|
|
209
|
+
check_endpoint("prosefix", out=sys.stdout, preset=preset, url=args.url, model=args.model,
|
|
210
|
+
timeout=args.timeout)
|
|
211
|
+
try:
|
|
212
|
+
src = find_project(Path.cwd()).source
|
|
213
|
+
except SettingsError as e:
|
|
214
|
+
print(f"settings: {e}")
|
|
215
|
+
else:
|
|
216
|
+
print(f"settings: {src or 'none (defaults)'}")
|
|
217
|
+
return 0
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _change_line(label: str, line: int, c) -> str:
|
|
221
|
+
extra = f", {c.reason}" if c.reason else ""
|
|
222
|
+
return (f"{label}:{line}: {c.before!r} -> {c.after!r} "
|
|
223
|
+
f"[{c.pass_} {c.check}, {c.decided_by}{extra}]")
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _lines(r):
|
|
227
|
+
for c in r.changes:
|
|
228
|
+
yield _change_line(r.path, r.original.count("\n", 0, c.start) + 1, c)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _unified_diff(a: str, b: str, label: str):
|
|
232
|
+
"""difflib's unified diff, with the marker patch(1) needs after a last line
|
|
233
|
+
that has no newline."""
|
|
234
|
+
for line in difflib.unified_diff(a.splitlines(True), b.splitlines(True), label, label):
|
|
235
|
+
if line.endswith("\n"):
|
|
236
|
+
yield line
|
|
237
|
+
else:
|
|
238
|
+
yield line + "\n\\n"
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def main(argv=None) -> int:
|
|
242
|
+
global _UMASK
|
|
243
|
+
_UMASK = _read_umask()
|
|
244
|
+
parser = build_parser()
|
|
245
|
+
args = parser.parse_args(argv)
|
|
246
|
+
if args.setup:
|
|
247
|
+
return run_setup("prosefix")
|
|
248
|
+
if args.check_endpoint:
|
|
249
|
+
preset = "none" if args.llm in ("none", "cached") else args.llm
|
|
250
|
+
return check_endpoint("prosefix", preset=preset, url=args.url, model=args.model,
|
|
251
|
+
timeout=args.timeout)
|
|
252
|
+
if args.doctor:
|
|
253
|
+
return _doctor(args)
|
|
254
|
+
if not args.paths:
|
|
255
|
+
parser.error("give files, directories, or - for stdin")
|
|
256
|
+
if args.output and "-" in args.paths:
|
|
257
|
+
parser.error("-o cannot be used with -")
|
|
258
|
+
if args.output and (len(args.paths) > 1 or Path(args.paths[0]).is_dir()):
|
|
259
|
+
parser.error("-o takes exactly one input file")
|
|
260
|
+
if args.strict and not args.check:
|
|
261
|
+
parser.error("--strict needs --check")
|
|
262
|
+
skip_list = [s for s in (args.skip or "").split(",") if s]
|
|
263
|
+
unknown = [s for s in skip_list if s not in TIERS]
|
|
264
|
+
if unknown:
|
|
265
|
+
parser.error(f"unknown tier(s) in --skip: {', '.join(unknown)} (known: {', '.join(TIERS)})")
|
|
266
|
+
flags = {"target": args.target, "style": args.style,
|
|
267
|
+
"only": (args.only,) if args.only else None, "skip": skip_list or None}
|
|
268
|
+
|
|
269
|
+
failed = False
|
|
270
|
+
if args.llm in ("none", "cached"):
|
|
271
|
+
ep = None
|
|
272
|
+
else:
|
|
273
|
+
try:
|
|
274
|
+
ep = resolve_endpoint("prosefix", args.llm, url=args.url, model=args.model,
|
|
275
|
+
timeout=args.timeout)
|
|
276
|
+
except ConfigError as e:
|
|
277
|
+
_err(str(e))
|
|
278
|
+
return 2
|
|
279
|
+
mode = "off" if (args.no_cache or args.llm == "none") else "replay" if args.llm == "cached" else "use"
|
|
280
|
+
replay = args.llm == "cached"
|
|
281
|
+
|
|
282
|
+
if args.require:
|
|
283
|
+
t = tools.detect()
|
|
284
|
+
have = {"vale": t.vale, "languagetool": t.languagetool, "typos": t.typos,
|
|
285
|
+
"model": ep}
|
|
286
|
+
for name in [n.strip() for n in args.require.split(",") if n.strip()]:
|
|
287
|
+
if name not in have:
|
|
288
|
+
parser.error(f"--require: unknown tool {name!r} (known: {', '.join(have)})")
|
|
289
|
+
if not have[name]:
|
|
290
|
+
_err(f"required {name} is missing ({tools.install_hint(name)})")
|
|
291
|
+
failed = True
|
|
292
|
+
if failed:
|
|
293
|
+
return 2
|
|
294
|
+
|
|
295
|
+
jobs: list[Job] = []
|
|
296
|
+
for raw in args.paths:
|
|
297
|
+
if raw == "-":
|
|
298
|
+
label = str(args.stdin_filename) if args.stdin_filename else "-"
|
|
299
|
+
jobs.append(Job(label, None, args.stdin_filename or Path.cwd() / "stdin.md",
|
|
300
|
+
text=sys.stdin.read()))
|
|
301
|
+
continue
|
|
302
|
+
p = Path(raw)
|
|
303
|
+
if p.is_dir():
|
|
304
|
+
for f in _walk(p):
|
|
305
|
+
if not _is_excluded(f):
|
|
306
|
+
jobs.append(Job(str(f), f, f))
|
|
307
|
+
elif p.is_file():
|
|
308
|
+
jobs.append(Job(raw, p, p))
|
|
309
|
+
else:
|
|
310
|
+
_err(f"no such file: {raw}")
|
|
311
|
+
failed = True
|
|
312
|
+
|
|
313
|
+
def run(job: Job) -> engine.FileResult:
|
|
314
|
+
text, settings = job.text, Settings()
|
|
315
|
+
if job.path is None and args.stdin_filename and _is_excluded(job.lookup):
|
|
316
|
+
src = find_project(job.lookup).source
|
|
317
|
+
return engine.FileResult(job.label, "skipped", f"excluded by {src}", settings, text, text)
|
|
318
|
+
try:
|
|
319
|
+
if text is None:
|
|
320
|
+
try:
|
|
321
|
+
with open(job.path, encoding="utf-8", newline="") as fh:
|
|
322
|
+
text = fh.read()
|
|
323
|
+
except UnicodeDecodeError as e:
|
|
324
|
+
return engine.FileResult(job.label, "error", f"not UTF-8 text: {e.reason}",
|
|
325
|
+
settings, "", "")
|
|
326
|
+
except OSError as e:
|
|
327
|
+
return engine.FileResult(job.label, "error", f"cannot read: {e.strerror}",
|
|
328
|
+
settings, "", "")
|
|
329
|
+
project = find_project(job.lookup)
|
|
330
|
+
settings = resolve(job.lookup, text, flags, project)
|
|
331
|
+
except SettingsError as e:
|
|
332
|
+
return engine.FileResult(job.label, "error", str(e), settings, text or "", text or "")
|
|
333
|
+
try:
|
|
334
|
+
return engine.process(job.label, text, settings, ep, engine.caches_for(settings, mode), replay)
|
|
335
|
+
except Exception as e: # one bad file must not sink the run
|
|
336
|
+
msg = f"{type(e).__name__}: {e}"
|
|
337
|
+
return engine.FileResult(job.label, "error", msg, settings, text, text)
|
|
338
|
+
|
|
339
|
+
try:
|
|
340
|
+
with ThreadPoolExecutor(max_workers=max(1, args.jobs)) as pool:
|
|
341
|
+
results = list(pool.map(run, jobs))
|
|
342
|
+
finally: # decisions already paid for survive Ctrl-C or a crash
|
|
343
|
+
if mode != "off":
|
|
344
|
+
for msg in engine.flush_all():
|
|
345
|
+
_err(msg)
|
|
346
|
+
for r in results:
|
|
347
|
+
if r.status == "error":
|
|
348
|
+
failed = True
|
|
349
|
+
if not args.json:
|
|
350
|
+
_err(f"{r.path}: {r.reason}")
|
|
351
|
+
|
|
352
|
+
skipped: dict[str, Skipped] = {}
|
|
353
|
+
for r in results:
|
|
354
|
+
for s in r.skipped:
|
|
355
|
+
skipped.setdefault(s.what, s)
|
|
356
|
+
if ep is None and args.llm != "none":
|
|
357
|
+
why, fix = (("only cached decisions are used", "run without --llm cached")
|
|
358
|
+
if args.llm == "cached" else ("no model endpoint", "prosefix --setup"))
|
|
359
|
+
s = Skipped("model decisions and comma placement", why, fix)
|
|
360
|
+
skipped.setdefault(s.what, s)
|
|
361
|
+
skipped_list = list(skipped.values())
|
|
362
|
+
if not (args.quiet or args.json):
|
|
363
|
+
for s in skipped_list:
|
|
364
|
+
_err(f"skipped {s.what} ({s.why}: {s.fix})")
|
|
365
|
+
|
|
366
|
+
changed = [r for r in results if r.status == "changed"]
|
|
367
|
+
reviewed = [r for r in results if r.review]
|
|
368
|
+
if args.changes:
|
|
369
|
+
for r in results:
|
|
370
|
+
for line in _lines(r):
|
|
371
|
+
print(line, file=sys.stderr)
|
|
372
|
+
if args.report:
|
|
373
|
+
try:
|
|
374
|
+
with open(args.report, "w", encoding="utf-8") as fh:
|
|
375
|
+
for r in results:
|
|
376
|
+
fh.write(f"## {r.path}\n\n")
|
|
377
|
+
if r.status in ("error", "skipped"):
|
|
378
|
+
fh.write(f"{r.status}: {r.reason}\n\n")
|
|
379
|
+
for line in _lines(r):
|
|
380
|
+
fh.write(f"- {line}\n")
|
|
381
|
+
for i in r.review:
|
|
382
|
+
fh.write(f"- review, line {i.line}: [{i.pass_} {i.check}] {i.message}\n")
|
|
383
|
+
fh.write("\n")
|
|
384
|
+
except OSError as e:
|
|
385
|
+
_err(f"{args.report}: cannot write report: {e.strerror or e}")
|
|
386
|
+
failed = True
|
|
387
|
+
|
|
388
|
+
n_changes = sum(len(r.changes) for r in changed)
|
|
389
|
+
if args.json:
|
|
390
|
+
json.dump(jsonout.document(results, ep, skipped_list), sys.stdout, ensure_ascii=False, indent=1)
|
|
391
|
+
sys.stdout.write("\n")
|
|
392
|
+
elif args.diff:
|
|
393
|
+
for r in changed:
|
|
394
|
+
sys.stdout.writelines(_unified_diff(r.original, r.output, r.path))
|
|
395
|
+
elif args.check:
|
|
396
|
+
flagged = [r for r in results if r.status == "changed" or (args.strict and r.review)]
|
|
397
|
+
for r in flagged:
|
|
398
|
+
why = "would change" if r.status == "changed" else "has review items:"
|
|
399
|
+
print(f"{why} {r.path}")
|
|
400
|
+
if not args.quiet:
|
|
401
|
+
print(f"would change {len(flagged)} file(s)" if flagged else "nothing to change")
|
|
402
|
+
if flagged:
|
|
403
|
+
return 2 if failed else 1
|
|
404
|
+
else:
|
|
405
|
+
for job, r in zip(jobs, results):
|
|
406
|
+
if job.path is None: # stdin filter: always emit text, even on error
|
|
407
|
+
sys.stdout.write(r.output if r.status != "error" else job.text)
|
|
408
|
+
continue
|
|
409
|
+
if r.status == "error" or not (args.output or r.status == "changed"):
|
|
410
|
+
continue
|
|
411
|
+
target = Path(args.output) if args.output else job.path
|
|
412
|
+
try:
|
|
413
|
+
_write_atomic(target, r.output, expect=None if args.output else r.original)
|
|
414
|
+
except ChangedDuringRun:
|
|
415
|
+
_err(f"{target}: changed during the run; left alone")
|
|
416
|
+
failed = True
|
|
417
|
+
except OSError as e:
|
|
418
|
+
_err(f"{target}: cannot write: {e.strerror or e}")
|
|
419
|
+
failed = True
|
|
420
|
+
if not args.quiet:
|
|
421
|
+
out = sys.stderr if any(j.path is None for j in jobs) else sys.stdout
|
|
422
|
+
for r in results:
|
|
423
|
+
if r.status in ("changed",) or (r.review and r.status != "error"):
|
|
424
|
+
print(f"prosefix: {r.path}: {len(r.changes)} change(s), {len(r.review)} for review",
|
|
425
|
+
file=out)
|
|
426
|
+
print(f"prosefix: {len(changed)} file(s) changed, {n_changes} change(s), "
|
|
427
|
+
f"{sum(len(r.review) for r in results)} for review", file=out)
|
|
428
|
+
return 2 if failed else 0
|
prosefix/engine.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""One file through stylefix then proofix, with changes against the original."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import copy
|
|
6
|
+
import os
|
|
7
|
+
import threading
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from adjudicate import Annotation, Cache, Change, ReviewItem, Skipped, compose, derive_changes
|
|
12
|
+
from proofix import api as proof
|
|
13
|
+
from proofix.commas import CommaCache
|
|
14
|
+
from stylefix import api as style
|
|
15
|
+
from stylefix.cli import BUILTIN_ACCEPT
|
|
16
|
+
|
|
17
|
+
from .settings import FRONT, PROOF_TIERS, STYLE_TIERS, Settings
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class _Flushable:
|
|
21
|
+
"""Written once, at the end of the run, and only if a decision was added:
|
|
22
|
+
preview modes and read-only projects never write an unchanged cache."""
|
|
23
|
+
|
|
24
|
+
def _mark_clean(self):
|
|
25
|
+
self._saved = copy.deepcopy(self.data)
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def dirty(self) -> bool:
|
|
29
|
+
return self.data != self._saved
|
|
30
|
+
|
|
31
|
+
def save(self): # the libraries call this after every batch; we write once, at the end
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
def flush(self):
|
|
35
|
+
if self.dirty:
|
|
36
|
+
self._base.save(self)
|
|
37
|
+
self._mark_clean()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class SharedCache(_Flushable, Cache):
|
|
41
|
+
_base = Cache
|
|
42
|
+
|
|
43
|
+
def __init__(self, path):
|
|
44
|
+
Cache.__init__(self, path)
|
|
45
|
+
self._mark_clean()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class SharedCommaCache(_Flushable, CommaCache):
|
|
49
|
+
_base = CommaCache
|
|
50
|
+
|
|
51
|
+
def __init__(self, path):
|
|
52
|
+
CommaCache.__init__(self, path)
|
|
53
|
+
self._mark_clean()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass
|
|
57
|
+
class Caches:
|
|
58
|
+
cache: Cache
|
|
59
|
+
commas: CommaCache
|
|
60
|
+
|
|
61
|
+
def flush(self) -> list[str]:
|
|
62
|
+
"""Errors, one per file that could not be saved; saving never stops the run."""
|
|
63
|
+
errors = []
|
|
64
|
+
for c in (self.cache, self.commas):
|
|
65
|
+
if hasattr(c, "flush"):
|
|
66
|
+
try:
|
|
67
|
+
c.flush()
|
|
68
|
+
except OSError as e:
|
|
69
|
+
errors.append(f"cannot save decisions to {c.path}: {e.strerror or e}")
|
|
70
|
+
return errors
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
_LOCK = threading.Lock()
|
|
74
|
+
_OPEN: dict[Path, Caches] = {}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def caches_for(settings: Settings, mode: str) -> Caches:
|
|
78
|
+
"""mode: use (read and write), replay (read; written only if new answers arrive), off (none)."""
|
|
79
|
+
if mode == "off" or settings.cache is None:
|
|
80
|
+
return Caches(Cache(None), CommaCache(None))
|
|
81
|
+
with _LOCK:
|
|
82
|
+
if settings.cache not in _OPEN:
|
|
83
|
+
_OPEN[settings.cache] = Caches(SharedCache(settings.cache),
|
|
84
|
+
SharedCommaCache(settings.cache.with_name("commas.json")))
|
|
85
|
+
return _OPEN[settings.cache]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def flush_all() -> list[str]:
|
|
89
|
+
errors: list[str] = []
|
|
90
|
+
with _LOCK:
|
|
91
|
+
for c in _OPEN.values():
|
|
92
|
+
errors += c.flush()
|
|
93
|
+
_OPEN.clear()
|
|
94
|
+
return errors
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def user_accept() -> tuple[list[str], set[str]]:
|
|
98
|
+
words: list[str] = []
|
|
99
|
+
cfg = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")
|
|
100
|
+
for p in (BUILTIN_ACCEPT, cfg / "stylefix" / "accept.txt", cfg / "proofix" / "accept.txt"):
|
|
101
|
+
if p.exists():
|
|
102
|
+
words += [l.strip() for l in p.read_text(encoding="utf-8").splitlines()
|
|
103
|
+
if l.strip() and not l.strip().startswith("#")]
|
|
104
|
+
return words, {w.lower() for w in words}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@dataclass
|
|
108
|
+
class FileResult:
|
|
109
|
+
path: str
|
|
110
|
+
status: str # changed | unchanged | skipped | error
|
|
111
|
+
reason: str | None
|
|
112
|
+
settings: Settings
|
|
113
|
+
original: str
|
|
114
|
+
output: str
|
|
115
|
+
changes: list[Change] = field(default_factory=list)
|
|
116
|
+
review: list[ReviewItem] = field(default_factory=list)
|
|
117
|
+
skipped: list[Skipped] = field(default_factory=list)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def process(label: str, text: str, settings: Settings, endpoint, caches: Caches,
|
|
121
|
+
replay: bool, parallel: int = 4) -> FileResult:
|
|
122
|
+
if settings.off:
|
|
123
|
+
return FileResult(label, "skipped", "prosefix: off", settings, text, text)
|
|
124
|
+
m = FRONT.match(text)
|
|
125
|
+
head = m.group(0) if m else ""
|
|
126
|
+
body = text[len(head):]
|
|
127
|
+
style_accept, proof_accept = user_accept()
|
|
128
|
+
style_accept += list(settings.accept)
|
|
129
|
+
proof_accept |= {w.lower() for w in settings.accept}
|
|
130
|
+
review: list[ReviewItem] = []
|
|
131
|
+
skipped: list[Skipped] = []
|
|
132
|
+
style_opts = style.Options(target=settings.target, style=settings.style,
|
|
133
|
+
accept=style_accept, parallel=parallel,
|
|
134
|
+
skip=settings.skip & frozenset(STYLE_TIERS),
|
|
135
|
+
require_vale=False, replay_cache=replay)
|
|
136
|
+
middle, first = body, []
|
|
137
|
+
if "style" in settings.only:
|
|
138
|
+
r = style.fix(body, style_opts, endpoint, caches.cache)
|
|
139
|
+
middle, first = r.text, r.changes
|
|
140
|
+
review, skipped = review + r.review, skipped + r.skipped
|
|
141
|
+
final, second = middle, []
|
|
142
|
+
if "proof" in settings.only:
|
|
143
|
+
r2 = proof.fix(middle, proof.Options(target=settings.target, accept=frozenset(proof_accept),
|
|
144
|
+
style=settings.style or "none", parallel=parallel,
|
|
145
|
+
skip=settings.skip & frozenset(PROOF_TIERS),
|
|
146
|
+
replay_cache=replay),
|
|
147
|
+
endpoint, caches.cache, caches.commas)
|
|
148
|
+
final, second = r2.text, r2.changes
|
|
149
|
+
review += r2.review
|
|
150
|
+
skipped += r2.skipped
|
|
151
|
+
if final != middle and "style" in settings.only:
|
|
152
|
+
# proofix's output is styled again (hygiene can decode "—" into a dash
|
|
153
|
+
# stylefix has not seen), so a second run changes nothing. "proofix + restyle"
|
|
154
|
+
# is the second pass, labelled from both passes' changes.
|
|
155
|
+
r3 = style.fix(final, style_opts, endpoint, caches.cache)
|
|
156
|
+
if r3.text != final:
|
|
157
|
+
seen = {(i.kind, i.message, i.check) for i in review}
|
|
158
|
+
review += [i for i in r3.review if (i.kind, i.message, i.check) not in seen]
|
|
159
|
+
skipped += [k for k in r3.skipped if k not in skipped]
|
|
160
|
+
second = _second_pass(middle, r3.text, [("proofix", c) for c in r2.changes]
|
|
161
|
+
+ [("stylefix", c) for c in r3.changes])
|
|
162
|
+
final = r3.text
|
|
163
|
+
for n, c in enumerate(first, 1):
|
|
164
|
+
c.id = f"s{n}"
|
|
165
|
+
for n, c in enumerate(second, 1):
|
|
166
|
+
c.id = f"p{n}"
|
|
167
|
+
changes = compose(body, middle, first, second)
|
|
168
|
+
shift = len(head)
|
|
169
|
+
for c in changes:
|
|
170
|
+
c.start += shift
|
|
171
|
+
c.end += shift
|
|
172
|
+
head_lines = head.count("\n")
|
|
173
|
+
review = [ReviewItem(i.line + head_lines, i.kind, i.message, i.check, i.pass_) for i in review]
|
|
174
|
+
if settings.note: # prosefix's own note is about the front matter: line 1
|
|
175
|
+
review.insert(0, ReviewItem(1, "note", settings.note, "settings", "prosefix"))
|
|
176
|
+
output = head + final
|
|
177
|
+
return FileResult(label, "changed" if output != text else "unchanged", None, settings,
|
|
178
|
+
text, output, changes, review, skipped)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
_TAG = "\x00"
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _second_pass(middle: str, final: str, tagged) -> list[Change]:
|
|
185
|
+
"""Changes middle -> final, each labelled from the proofix or restyle change
|
|
186
|
+
it matches and given that pass; a hunk nothing matches is proofix's."""
|
|
187
|
+
ann = [Annotation(c.before, c.after, f"{origin}{_TAG}{c.check}", c.reason, c.decided_by,
|
|
188
|
+
c.confidence) for origin, c in tagged]
|
|
189
|
+
out = derive_changes(middle, final, ann, f"proofix{_TAG}proofix")
|
|
190
|
+
for c in out:
|
|
191
|
+
c.pass_, _, c.check = c.check.partition(_TAG) if _TAG in c.check else ("proofix", "", c.check)
|
|
192
|
+
return out
|
prosefix/jsonout.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""The versioned JSON document (schema 1)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from . import __version__
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def utf16_offsets(text: str) -> list[int]:
|
|
9
|
+
"""m[i] = UTF-16 code units before code point i (len(text)+1 entries)."""
|
|
10
|
+
out = [0]
|
|
11
|
+
for ch in text:
|
|
12
|
+
out.append(out[-1] + (2 if ord(ch) > 0xFFFF else 1))
|
|
13
|
+
return out
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def file_entry(r) -> dict:
|
|
17
|
+
s = r.settings
|
|
18
|
+
entry = {"path": r.path, "status": r.status, "reason": r.reason,
|
|
19
|
+
"settings": {"target": s.target, "style": s.style, "only": list(s.only),
|
|
20
|
+
"skip": sorted(s.skip)}}
|
|
21
|
+
if r.status == "error":
|
|
22
|
+
return entry
|
|
23
|
+
m = utf16_offsets(r.original)
|
|
24
|
+
entry["changes"] = [{"id": c.id, "pass": c.pass_, "check": c.check,
|
|
25
|
+
"start": m[c.start], "end": m[c.end],
|
|
26
|
+
"line": r.original.count("\n", 0, c.start) + 1,
|
|
27
|
+
"before": c.before, "after": c.after, "reason": c.reason,
|
|
28
|
+
"decided_by": c.decided_by, "confidence": round(c.confidence, 3),
|
|
29
|
+
"depends_on": list(c.depends_on)} for c in r.changes]
|
|
30
|
+
entry["review"] = [{"pass": i.pass_, "line": i.line, "kind": i.kind, "check": i.check,
|
|
31
|
+
"message": i.message} for i in r.review]
|
|
32
|
+
entry["output"] = r.output
|
|
33
|
+
return entry
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def document(results, endpoint, skipped) -> dict:
|
|
37
|
+
ep = None if endpoint is None else {"url": endpoint.url, "model": endpoint.model,
|
|
38
|
+
"source": endpoint.sources.get("url", "")}
|
|
39
|
+
return {"schema": 1, "prosefix": __version__, "endpoint": ep,
|
|
40
|
+
"skipped": [{"what": s.what, "why": s.why, "fix": s.fix} for s in skipped],
|
|
41
|
+
"files": [file_entry(r) for r in results]}
|
prosefix/settings.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""Settings for one file: built-in defaults < project file < front matter < flags."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import functools
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import tomllib
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
import yaml
|
|
13
|
+
|
|
14
|
+
PASSES = ("style", "proof")
|
|
15
|
+
STYLE_TIERS = ("variety", "guide", "ambiguous", "numbers", "serial-comma", "abbreviations", "punctuation")
|
|
16
|
+
PROOF_TIERS = ("hygiene", "mechanical", "typos", "adjudicated", "compounds", "commas")
|
|
17
|
+
TIERS = STYLE_TIERS + PROOF_TIERS
|
|
18
|
+
SETTINGS_FILES = ("prosefix.toml", ".prosefix.toml")
|
|
19
|
+
FRONT = re.compile(r"\A\ufeff?---\r?\n(.*?)\r?\n---\r?\n", re.S)
|
|
20
|
+
|
|
21
|
+
_LISTS = {"only": PASSES, "skip": TIERS, "exclude": None, "accept": None}
|
|
22
|
+
_PROJECT_KEYS = ("target", "style", "only", "skip", "exclude", "accept", "accept_file", "cache")
|
|
23
|
+
_NOTE_KEYS = ("target", "style", "only", "skip")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class SettingsError(ValueError):
|
|
27
|
+
pass
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class Project:
|
|
32
|
+
root: Path | None
|
|
33
|
+
source: Path | None
|
|
34
|
+
values: dict
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True)
|
|
38
|
+
class Settings:
|
|
39
|
+
target: str = "us"
|
|
40
|
+
style: str | None = None
|
|
41
|
+
only: tuple[str, ...] = PASSES
|
|
42
|
+
skip: frozenset[str] = frozenset()
|
|
43
|
+
exclude: tuple[str, ...] = ()
|
|
44
|
+
accept: tuple[str, ...] = ()
|
|
45
|
+
cache: Path | None = None
|
|
46
|
+
project: Path | None = None
|
|
47
|
+
off: bool = False
|
|
48
|
+
note: str | None = None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _validate(table, where: str, allowed: tuple[str, ...]) -> dict:
|
|
52
|
+
if not isinstance(table, dict):
|
|
53
|
+
raise SettingsError(f"{where}: settings must be a table")
|
|
54
|
+
for k, v in table.items():
|
|
55
|
+
if k not in allowed:
|
|
56
|
+
raise SettingsError(f"{where}: unknown key '{k}' (known: {', '.join(allowed)})")
|
|
57
|
+
if k == "target" and v not in ("us", "uk"):
|
|
58
|
+
raise SettingsError(f"{where}: target must be \"us\" or \"uk\", not {v!r}")
|
|
59
|
+
if k in ("style", "accept_file", "cache") and not isinstance(v, str):
|
|
60
|
+
raise SettingsError(f"{where}: {k} must be a string, not {v!r}")
|
|
61
|
+
if k == "style" and v not in _guides():
|
|
62
|
+
raise SettingsError(f"{where}: style has unknown value {v!r} (known: {', '.join(_guides())})")
|
|
63
|
+
if k in _LISTS:
|
|
64
|
+
if not isinstance(v, list) or not all(isinstance(x, str) for x in v):
|
|
65
|
+
raise SettingsError(f"{where}: {k} must be a list of strings, not {v!r}")
|
|
66
|
+
choices = _LISTS[k]
|
|
67
|
+
bad = [x for x in v if choices is not None and x not in choices]
|
|
68
|
+
if bad:
|
|
69
|
+
raise SettingsError(f"{where}: {k} has unknown value '{bad[0]}' "
|
|
70
|
+
f"(known: {', '.join(choices)})")
|
|
71
|
+
return dict(table)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _guides() -> list[str]:
|
|
75
|
+
from stylefix import styleguides
|
|
76
|
+
return styleguides.choices()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _load_toml(path: Path) -> dict:
|
|
80
|
+
try:
|
|
81
|
+
return tomllib.loads(path.read_text(encoding="utf-8"))
|
|
82
|
+
except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError) as e:
|
|
83
|
+
raise SettingsError(f"{path}: cannot read settings: {e}") from e
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@functools.lru_cache(maxsize=None)
|
|
87
|
+
def _project_for_dir(d: Path) -> Project:
|
|
88
|
+
for p in [d, *d.parents]:
|
|
89
|
+
for name in SETTINGS_FILES:
|
|
90
|
+
f = p / name
|
|
91
|
+
if f.is_file():
|
|
92
|
+
return Project(p, f, _validate(_load_toml(f), str(f), _PROJECT_KEYS))
|
|
93
|
+
py = p / "pyproject.toml"
|
|
94
|
+
if py.is_file():
|
|
95
|
+
table = _load_toml(py).get("tool", {}).get("prosefix")
|
|
96
|
+
if table is not None:
|
|
97
|
+
return Project(p, py, _validate(table, f"{py} [tool.prosefix]", _PROJECT_KEYS))
|
|
98
|
+
return Project(None, None, {})
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def find_project(path: Path) -> Project:
|
|
102
|
+
d = path if path.is_dir() else path.parent
|
|
103
|
+
return _project_for_dir(d.resolve())
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
find_project.cache_clear = _project_for_dir.cache_clear # for tests
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def front_matter(text: str) -> tuple[dict | None, str | None]:
|
|
110
|
+
m = FRONT.match(text)
|
|
111
|
+
if not m:
|
|
112
|
+
return None, None
|
|
113
|
+
try:
|
|
114
|
+
data = yaml.safe_load(m.group(1))
|
|
115
|
+
except yaml.YAMLError as e:
|
|
116
|
+
return None, f"front matter does not parse ({type(e).__name__}); project settings used"
|
|
117
|
+
if data is None:
|
|
118
|
+
return {}, None
|
|
119
|
+
if not isinstance(data, dict):
|
|
120
|
+
return None, "front matter is not a mapping; project settings used"
|
|
121
|
+
return data, None
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _inside(project: Project, key: str, value: str) -> Path:
|
|
125
|
+
"""value resolved against the project root; it must stay inside it, symlinks included."""
|
|
126
|
+
root = project.root
|
|
127
|
+
bad = SettingsError(f"{project.source}: {key} must be a path inside {root}, not {value!r}")
|
|
128
|
+
if Path(value).is_absolute():
|
|
129
|
+
raise bad
|
|
130
|
+
path = root / value
|
|
131
|
+
if not path.resolve().is_relative_to(root.resolve()):
|
|
132
|
+
raise bad
|
|
133
|
+
return path
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _read_accept_file(project: Project, name: str) -> list[str]:
|
|
137
|
+
path = _inside(project, "accept_file", name)
|
|
138
|
+
try:
|
|
139
|
+
lines = path.read_text(encoding="utf-8").splitlines()
|
|
140
|
+
except (OSError, UnicodeDecodeError) as e:
|
|
141
|
+
raise SettingsError(f"{path}: cannot read accept_file: {e}") from e
|
|
142
|
+
return [l.strip() for l in lines if l.strip() and not l.strip().startswith("#")]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def resolve(path: Path | None, text: str, flags: dict, project: Project) -> Settings:
|
|
146
|
+
v: dict = {"target": "us"}
|
|
147
|
+
v.update(project.values)
|
|
148
|
+
fm, note = front_matter(text)
|
|
149
|
+
off = False
|
|
150
|
+
if fm is not None:
|
|
151
|
+
p = fm.get("prosefix")
|
|
152
|
+
where = f"{path or '-'}: front matter 'prosefix'"
|
|
153
|
+
if p is False or p == "off":
|
|
154
|
+
off = True
|
|
155
|
+
elif isinstance(p, dict):
|
|
156
|
+
v.update(_validate(p, where, _NOTE_KEYS))
|
|
157
|
+
elif p is not None:
|
|
158
|
+
raise SettingsError(f"{where} must be off or a mapping, not {p!r}")
|
|
159
|
+
if not (isinstance(p, dict) and "target" in p):
|
|
160
|
+
lang = str(fm.get("lang", "")).strip().lower()
|
|
161
|
+
if lang in ("en-gb", "en-uk"):
|
|
162
|
+
v["target"] = "uk"
|
|
163
|
+
elif lang == "en-us":
|
|
164
|
+
v["target"] = "us"
|
|
165
|
+
v.update({k: val for k, val in flags.items() if val is not None})
|
|
166
|
+
accept = list(v.get("accept", []))
|
|
167
|
+
if project.root and "accept_file" in v:
|
|
168
|
+
accept += _read_accept_file(project, v["accept_file"])
|
|
169
|
+
if "cache" in v and project.root:
|
|
170
|
+
cache = _inside(project, "cache", v["cache"])
|
|
171
|
+
allowed = project.root
|
|
172
|
+
elif "cache" in v: # only from a flag or note: relative to the working directory
|
|
173
|
+
cache = Path.cwd() / v["cache"]
|
|
174
|
+
allowed = Path.cwd()
|
|
175
|
+
elif project.root:
|
|
176
|
+
cache, allowed = project.root / ".prosefix" / "cache.json", project.root
|
|
177
|
+
else:
|
|
178
|
+
allowed = Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache")
|
|
179
|
+
cache = allowed / "prosefix" / "cache.json"
|
|
180
|
+
for f in (cache, cache.with_name("commas.json")): # every file prosefix will write
|
|
181
|
+
if not f.resolve().is_relative_to(allowed.resolve()):
|
|
182
|
+
raise SettingsError(f"{project.source or 'settings'}: cache file {f} must be a path inside "
|
|
183
|
+
f"{allowed}, not a link to {f.resolve()}")
|
|
184
|
+
return Settings(target=v["target"], style=v.get("style"),
|
|
185
|
+
only=tuple(v.get("only", PASSES)), skip=frozenset(v.get("skip", ())),
|
|
186
|
+
exclude=tuple(v.get("exclude", ())), accept=tuple(accept),
|
|
187
|
+
cache=cache,
|
|
188
|
+
project=project.source, off=off, note=note)
|
prosefix/tools.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""External programs prosefix can use, and how to get them."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import shutil
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
HINTS = {"vale": "brew install vale", "languagetool": "brew install languagetool",
|
|
9
|
+
"typos": "brew install typos-cli", "model": "prosefix --setup"}
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class Tools:
|
|
14
|
+
vale: str | None
|
|
15
|
+
languagetool: str | None
|
|
16
|
+
typos: str | None
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def detect() -> Tools:
|
|
20
|
+
return Tools(shutil.which("vale"),
|
|
21
|
+
shutil.which("languagetool") or shutil.which("languagetool-commandline"),
|
|
22
|
+
shutil.which("typos"))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def install_hint(name: str) -> str:
|
|
26
|
+
return HINTS[name]
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: prosefix
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Clean, consistent prose in Markdown: stylefix's spelling and style guide plus proofix's typos, punctuation and commas, in one command.
|
|
5
|
+
Project-URL: Homepage, https://github.com/AndrewBroz/prosefix
|
|
6
|
+
Project-URL: Issues, https://github.com/AndrewBroz/prosefix/issues
|
|
7
|
+
Author: Andrew Brož
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Intended Audience :: End Users/Desktop
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Topic :: Text Processing :: Markup :: Markdown
|
|
16
|
+
Requires-Python: >=3.11
|
|
17
|
+
Requires-Dist: adjudicate<0.4,>=0.3.1
|
|
18
|
+
Requires-Dist: proofix<0.7,>=0.6
|
|
19
|
+
Requires-Dist: pyyaml>=6
|
|
20
|
+
Requires-Dist: stylefix<0.9,>=0.8
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# prosefix
|
|
24
|
+
|
|
25
|
+
Clean, consistent prose in Markdown: stylefix's spelling and style guide plus proofix's typos, punctuation and commas, in one command.
|
|
26
|
+
|
|
27
|
+
prosefix runs two passes over each file with one model endpoint, one decision cache and one change list. The style pass (stylefix) settles one English variety and one style guide; the proof pass (proofix) fixes typos, punctuation, compounds and commas. Front matter, code, links, HTML and Obsidian syntax are never changed. Files are rewritten in place.
|
|
28
|
+
|
|
29
|
+
```text
|
|
30
|
+
Before: The colour of the "new" programme was fine, and we honour it -- really.
|
|
31
|
+
After: The color of the “new” program was fine, and we honor it—really.
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
(US target, rules only. With a model, words that depend on meaning, such as licence and license, are decided too.)
|
|
35
|
+
|
|
36
|
+
## Install
|
|
37
|
+
|
|
38
|
+
```sh
|
|
39
|
+
brew install andrewbroz/tap/prosefix # also installs Vale, LanguageTool and typos
|
|
40
|
+
uv tool install prosefix # or: pipx install prosefix
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Without Homebrew, install the tools you want. prosefix runs every tier whose requirements are met and says once, on stderr, what it skipped:
|
|
44
|
+
|
|
45
|
+
| missing | skipped | still runs |
|
|
46
|
+
|---|---|---|
|
|
47
|
+
| [Vale](https://vale.sh) (`brew install vale`) | `variety`, `guide`, `ambiguous`, `numbers` | `serial-comma`, `abbreviations`, `punctuation`, and all of the proof pass |
|
|
48
|
+
| [LanguageTool](https://languagetool.org) (`brew install languagetool`) | `mechanical`, `adjudicated` | `hygiene`, `compounds`, `commas` |
|
|
49
|
+
| [typos](https://github.com/crate-ci/typos) (`brew install typos-cli`) | `typos` | everything else |
|
|
50
|
+
| a model | decisions that need judgement, `commas` | rule-based tiers; undecided items are reported |
|
|
51
|
+
|
|
52
|
+
## First run
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
prosefix --setup # choose and test a model endpoint
|
|
56
|
+
prosefix --doctor # tools found or missing, the endpoint, the settings file for this directory
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
The endpoint comes from flags, `PROSEFIX_LLM_*` / `ADJUDICATE_LLM_*` environment variables, `~/.config/prosefix/config.toml` and `~/.config/adjudicate/config.toml`, never from a project file. Without a model, `--llm none` (or no configured endpoint) still applies all rule-based tiers.
|
|
60
|
+
|
|
61
|
+
## Use
|
|
62
|
+
|
|
63
|
+
```sh
|
|
64
|
+
prosefix note.md # rewrite one note in place
|
|
65
|
+
prosefix vault/ --diff # show what would change in a vault
|
|
66
|
+
prosefix content/ --check --llm cached # CI: fail if anything would change
|
|
67
|
+
prosefix - < in.md > out.md # filter
|
|
68
|
+
prosefix note.md --target uk --skip commas
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Directory walks take `*.md` and `*.markdown`, skipping `.git`, `.obsidian`, `node_modules`, other dot-directories and your `exclude` globs. Exit status: 0 success; 1 from `--check` (or `--strict`) when something would change; 2 for usage, configuration, input or write errors, a file that changed on disk during the run (it is left alone), or a failed `--require`. Any per-file error is reported on stderr and gives 2, but the other files are still processed.
|
|
72
|
+
|
|
73
|
+
Writes are atomic, keep the file's mode, and follow symlinks to their target; read-only files are reported and left alone.
|
|
74
|
+
|
|
75
|
+
## Obsidian
|
|
76
|
+
|
|
77
|
+
Run prosefix in place on a vault. Wikilinks and their aliases, embeds, `#tags`, `%%comments%%`, `^block-ids`, the `> [!note]` marker of a callout, maths, and Markdown code, links and HTML are never edited; quotes beside them are curled sensibly. Prose that only looks like syntax ("issue #42", "C#", "costs $5 and $10") is edited as prose.
|
|
78
|
+
|
|
79
|
+
Until the prosefix plugin exists, use the Shell Commands community plugin with:
|
|
80
|
+
|
|
81
|
+
```text
|
|
82
|
+
prosefix {{file_path:absolute}}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Publishing
|
|
86
|
+
|
|
87
|
+
```yaml
|
|
88
|
+
- run: pipx install prosefix
|
|
89
|
+
- run: prosefix content/ --check --llm cached
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Commit `.prosefix/` so CI replays your decisions: `--llm cached` applies decisions already in the cache and never contacts a model. With no settings file, decisions are cached under `$XDG_CACHE_HOME/prosefix/` (default `~/.cache/prosefix/`) instead.
|
|
93
|
+
|
|
94
|
+
## Settings
|
|
95
|
+
|
|
96
|
+
prosefix looks upward from each file for `prosefix.toml`, `.prosefix.toml`, or `[tool.prosefix]` in `pyproject.toml`:
|
|
97
|
+
|
|
98
|
+
```toml
|
|
99
|
+
target = "uk" # "us" or "uk"
|
|
100
|
+
style = "oxford" # style guide
|
|
101
|
+
only = ["style", "proof"] # passes to run
|
|
102
|
+
skip = ["commas"] # tiers to skip
|
|
103
|
+
exclude = ["drafts/**", "templates/**"]
|
|
104
|
+
accept = ["Obsidian", "Zettelkasten"]
|
|
105
|
+
accept_file = ".prosefix/accept.txt"
|
|
106
|
+
cache = ".prosefix/cache.json" # comma decisions go to commas.json beside it
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
`exclude` globs are relative to the settings file; `**` crosses directories, `*` and `?` do not, and a bare directory name does not exclude its contents (write `templates/**`). `cache` and `accept_file` must stay inside the project directory.
|
|
110
|
+
|
|
111
|
+
A note can override the project in its front matter:
|
|
112
|
+
|
|
113
|
+
```yaml
|
|
114
|
+
---
|
|
115
|
+
lang: en-GB # sets the target when prosefix.target is absent
|
|
116
|
+
prosefix:
|
|
117
|
+
target: uk
|
|
118
|
+
skip: [commas]
|
|
119
|
+
---
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
or opt out with `prosefix: off`. Only `target`, `style`, `only` and `skip` are allowed there. Flags beat front matter, which beats the project file.
|
|
123
|
+
|
|
124
|
+
The tiers are `variety`, `guide`, `ambiguous`, `numbers`, `serial-comma`, `abbreviations`, `punctuation` (style) and `hygiene`, `mechanical`, `typos`, `adjudicated`, `compounds`, `commas` (proof).
|
|
125
|
+
|
|
126
|
+
## JSON
|
|
127
|
+
|
|
128
|
+
`prosefix --json` prints one document, `"schema": 1`, for editors and plugins: the endpoint, the capabilities skipped, and for each file its status, settings, a list of changes (`id`, `pass`, `check`, `start`, `end`, `line`, `before`, `after`, `reason`, `decided_by`, `confidence`, `depends_on`), review items and the full output. Offsets are UTF-16 code units into the whole original file; `line` is 1-based. A change that lists `depends_on` supersedes the changes it names. The details are in the man page (`man prosefix`, or `man/prosefix.1` in the source).
|
|
129
|
+
|
|
130
|
+
## License
|
|
131
|
+
|
|
132
|
+
MIT
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
prosefix/__init__.py,sha256=q1V1aEt0sxN4Azjtdz2QwNcWMItKyEnlKMBFDjrPN0c,76
|
|
2
|
+
prosefix/cli.py,sha256=b_kmhvKDQBE9PlNwAaN7UVuEEvGUgUCyDqvfx1Hbgxo,18250
|
|
3
|
+
prosefix/engine.py,sha256=U76YeBrDScIur9MzCFiaiUVpv9MeduFdfwK2TYT7RqM,7381
|
|
4
|
+
prosefix/jsonout.py,sha256=bdnIpyXp14tzGe0qR8MY8tOWoV5FGDSJrRydw6UzV1A,1774
|
|
5
|
+
prosefix/settings.py,sha256=IJq1e8NtGaZ1FyuDshnfPW35te6KADfCVj1lmjESKAQ,7330
|
|
6
|
+
prosefix/tools.py,sha256=iCtOfx5u4SubV4BO9uioYANvgRDYCFrVKWo-uUnXWng,672
|
|
7
|
+
prosefix-0.1.0.dist-info/METADATA,sha256=Un_lK3QQLJz2HTIpB8JsuEvoHeN3gMp5FIuMOskoZOQ,6689
|
|
8
|
+
prosefix-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
9
|
+
prosefix-0.1.0.dist-info/entry_points.txt,sha256=9DeKN1tpNe1jEze6WrMs8P2RqUUfCLwfUIU2RrX0Hfo,47
|
|
10
|
+
prosefix-0.1.0.dist-info/licenses/LICENSE,sha256=zej0aWUm6klR2w0pyC9vcw7qEubfLHpXomZtcR6g1oE,1069
|
|
11
|
+
prosefix-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Andrew Brož
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|