onelook 0.1.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.
onelook/__init__.py ADDED
@@ -0,0 +1,67 @@
1
+ """onelook: seal a blind test set, record the one run made against it, and
2
+ check later whether a published number still corresponds to that code and
3
+ that data.
4
+
5
+ The library mirrors the command line::
6
+
7
+ from onelook import Ledger, seal, record_run, status
8
+
9
+ ledger = Ledger.load("onelook.json", create=True)
10
+ seal(ledger, "blind", ["blind.csv"], note="written by a colleague")
11
+ ledger.set_engine(["src"])
12
+ ledger.save()
13
+ record_run(ledger, "blind", ["python", "evaluate.py"], metrics_file="metrics.json")
14
+ status(ledger).ok
15
+
16
+ Scoring helpers are in :mod:`onelook.metrics`.
17
+ """
18
+
19
+ __version__ = "0.1.2"
20
+
21
+ from ._errors import OnelookError
22
+ from .hashing import DEFAULT_IGNORE, Fingerprint, combine, expand, fingerprint, hash_file
23
+ from .ledger import (
24
+ Ledger,
25
+ RunResult,
26
+ SealResult,
27
+ SetCheck,
28
+ SetStatus,
29
+ Status,
30
+ check_ledger,
31
+ check_set,
32
+ fingerprint_config,
33
+ record_run,
34
+ seal,
35
+ set_status,
36
+ status,
37
+ )
38
+ from .reporting import render_markdown, report
39
+ from .verification import Verification, verify
40
+
41
+ __all__ = [
42
+ "DEFAULT_IGNORE",
43
+ "Fingerprint",
44
+ "Ledger",
45
+ "OnelookError",
46
+ "RunResult",
47
+ "SealResult",
48
+ "SetCheck",
49
+ "SetStatus",
50
+ "Status",
51
+ "Verification",
52
+ "check_ledger",
53
+ "check_set",
54
+ "combine",
55
+ "expand",
56
+ "fingerprint",
57
+ "fingerprint_config",
58
+ "hash_file",
59
+ "record_run",
60
+ "render_markdown",
61
+ "report",
62
+ "seal",
63
+ "set_status",
64
+ "status",
65
+ "verify",
66
+ "__version__",
67
+ ]
onelook/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
onelook/_errors.py ADDED
@@ -0,0 +1,8 @@
1
+ """The one exception type onelook raises for problems the user can act on."""
2
+
3
+
4
+ class OnelookError(Exception):
5
+ """A problem with the ledger, the files, or the request.
6
+
7
+ The command line prints the message and exits with status 2.
8
+ """
onelook/cli.py ADDED
@@ -0,0 +1,361 @@
1
+ """Command line for onelook.
2
+
3
+ Exit status: 0 when the command succeeded and everything it checked holds,
4
+ 1 when a check does not hold (``status``, ``verify``), 2 for usage errors
5
+ and problems onelook reports itself. ``onelook run`` exits with the status
6
+ of the command it ran.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import sys
15
+
16
+ from . import __version__
17
+ from ._errors import OnelookError
18
+ from .hashing import DEFAULT_IGNORE, fingerprint
19
+ from .ledger import LEDGER_NAME, BLIND, Ledger, fingerprint_config, record_run, seal, status
20
+ from .reporting import render_markdown, report, write_blocks
21
+ from .verification import verify
22
+
23
+
24
+ def _plural(count: int, word: str) -> str:
25
+ return f"{count} {word}" + ("" if count == 1 else "s")
26
+
27
+
28
+ def build_parser() -> argparse.ArgumentParser:
29
+ common = argparse.ArgumentParser(add_help=False)
30
+ common.add_argument(
31
+ "--ledger",
32
+ default=LEDGER_NAME,
33
+ metavar="FILE",
34
+ help="ledger file (default: onelook.json in the current directory); "
35
+ "recorded paths are relative to its directory",
36
+ )
37
+ parser = argparse.ArgumentParser(
38
+ prog="onelook",
39
+ description="Seal a blind test set, record the one run made against it, "
40
+ "and check later whether a published number still corresponds to that "
41
+ "code and that data.",
42
+ )
43
+ parser.add_argument("--version", action="version", version=f"onelook {__version__}")
44
+ sub = parser.add_subparsers(dest="command_name", metavar="COMMAND", required=True)
45
+
46
+ p = sub.add_parser("seal", parents=[common], help="record the hashes of a blind set")
47
+ p.add_argument("name", metavar="NAME")
48
+ p.add_argument("files", metavar="FILES", nargs="+", help="files, directories or globs")
49
+ p.add_argument("--note", help="free text, for example who wrote the set")
50
+ p.add_argument(
51
+ "--new-version",
52
+ action="store_true",
53
+ help="seal changed files under an existing name; earlier versions are kept",
54
+ )
55
+ p.add_argument(
56
+ "--exact",
57
+ action="store_true",
58
+ help="hash the bytes as they are (default: CRLF is hashed as LF)",
59
+ )
60
+ p.set_defaults(func=_seal)
61
+
62
+ p = sub.add_parser(
63
+ "fingerprint", parents=[common], help="hash the engine; --save records which paths it is"
64
+ )
65
+ p.add_argument(
66
+ "paths",
67
+ metavar="PATHS",
68
+ nargs="*",
69
+ help="files, directories or globs (default: the engine saved in the ledger)",
70
+ )
71
+ p.add_argument(
72
+ "--ignore",
73
+ action="append",
74
+ default=[],
75
+ metavar="PATTERN",
76
+ help="ignore pattern, repeatable; added to " + ", ".join(DEFAULT_IGNORE),
77
+ )
78
+ p.add_argument("--exact", action="store_true", help="hash the bytes as they are")
79
+ p.add_argument("--save", action="store_true", help="save PATHS as the engine in the ledger")
80
+ p.add_argument("--list", action="store_true", help="also print each file and its hash")
81
+ p.set_defaults(func=_fingerprint)
82
+
83
+ p = sub.add_parser(
84
+ "run",
85
+ parents=[common],
86
+ help="run an evaluation command against a sealed set and record it",
87
+ usage="onelook run [-h] [--ledger FILE] [--metrics FILE] [--shell] "
88
+ "[--tail N] NAME -- COMMAND...",
89
+ )
90
+ p.add_argument("name", metavar="NAME")
91
+ p.add_argument("--metrics", metavar="FILE", help="JSON object the command writes")
92
+ p.add_argument(
93
+ "--shell",
94
+ action="store_true",
95
+ help="join COMMAND with spaces and give it to the system shell "
96
+ "(on Windows, required for .bat and .cmd files)",
97
+ )
98
+ p.add_argument(
99
+ "--tail",
100
+ type=int,
101
+ default=20,
102
+ metavar="N",
103
+ help="lines of output to keep in the ledger (default 20; 0 for none)",
104
+ )
105
+ p.set_defaults(func=_run)
106
+
107
+ p = sub.add_parser("status", parents=[common], help="does everything still hold?")
108
+ p.add_argument(
109
+ "--strict",
110
+ action="store_true",
111
+ help="also fail when a set has repeat runs or a blind run that failed",
112
+ )
113
+ p.set_defaults(func=_status)
114
+
115
+ p = sub.add_parser("report", parents=[common], help="paragraph and table for a README")
116
+ p.add_argument("names", metavar="NAME", nargs="*", help="sets to report (default: all)")
117
+ p.add_argument("--format", choices=("md", "json"), default="md")
118
+ p.add_argument(
119
+ "--write",
120
+ metavar="FILE",
121
+ help="insert or replace the report blocks in this Markdown file",
122
+ )
123
+ p.set_defaults(func=_report)
124
+
125
+ p = sub.add_parser(
126
+ "verify", parents=[common], help="recompute everything and test the README's claim"
127
+ )
128
+ p.add_argument(
129
+ "--readme", metavar="FILE", help="default: README.md beside the ledger, if present"
130
+ )
131
+ p.set_defaults(func=_verify)
132
+ return parser
133
+
134
+
135
+ # --------------------------------------------------------------------------
136
+
137
+
138
+ def _seal(args, _command) -> int:
139
+ ledger = Ledger.load(args.ledger, create=True)
140
+ result = seal(
141
+ ledger,
142
+ args.name,
143
+ [os.path.abspath(f) for f in args.files],
144
+ note=args.note,
145
+ new_version=args.new_version,
146
+ newlines="exact" if args.exact else "lf",
147
+ )
148
+ record = result.record
149
+ size = _plural(len(record["files"]), "file")
150
+ if record["items"] is not None:
151
+ size += f", {_plural(record['items'], 'item')}"
152
+ if result.created:
153
+ print(f"sealed {args.name!r} version {record['version']}: {size}")
154
+ else:
155
+ print(
156
+ f"{args.name!r} is already sealed with exactly these files "
157
+ f"(version {record['version']}: {size}); nothing recorded"
158
+ )
159
+ print(f"set hash {record['set_hash']} (newlines: {record['newlines']})")
160
+ for entry in record["files"]:
161
+ print(f" {entry['sha256']} {entry['path']}")
162
+ return 0
163
+
164
+
165
+ def _fingerprint(args, _command) -> int:
166
+ if args.paths:
167
+ ledger = Ledger.load(args.ledger, create=True)
168
+ include = [ledger.pattern_for(os.path.abspath(p)) for p in args.paths]
169
+ ignore = list(DEFAULT_IGNORE) + [p for p in args.ignore if p not in DEFAULT_IGNORE]
170
+ newlines = "exact" if args.exact else "lf"
171
+ result = fingerprint(ledger.root, include, ignore, newlines, exclude=(ledger.name,))
172
+ if args.save:
173
+ ledger.set_engine(include, ignore, newlines)
174
+ ledger.save()
175
+ else:
176
+ if args.ignore or args.exact or args.save:
177
+ raise OnelookError("--ignore, --exact and --save need PATHS")
178
+ ledger = Ledger.load(args.ledger)
179
+ result = fingerprint_config(ledger)
180
+ include, ignore = ledger.engine["include"], ledger.engine.get("ignore", [])
181
+ print(result.hash)
182
+ print(
183
+ f"{_plural(len(result.files), 'file')}; include: {', '.join(include)}; "
184
+ f"ignore: {', '.join(ignore) or '(nothing)'}; newlines: {result.newlines}"
185
+ )
186
+ if args.list:
187
+ for path, digest in result.files:
188
+ print(f" {digest} {path}")
189
+ if args.save:
190
+ print(f"saved as the engine in {ledger.name}")
191
+ return 0
192
+
193
+
194
+ def _echo(chunk: bytes) -> None:
195
+ buffer = getattr(sys.stdout, "buffer", None)
196
+ if buffer is not None:
197
+ buffer.write(chunk)
198
+ else:
199
+ sys.stdout.write(chunk.decode("utf-8", "replace"))
200
+ sys.stdout.flush()
201
+
202
+
203
+ def _run(args, command) -> int:
204
+ if not command:
205
+ raise OnelookError("give the evaluation command after '--', as in: onelook run NAME -- python evaluate.py")
206
+ ledger = Ledger.load(args.ledger)
207
+ recorded_before = len(ledger.runs)
208
+ try:
209
+ result = record_run(
210
+ ledger,
211
+ args.name,
212
+ command,
213
+ shell=args.shell,
214
+ metrics_file=args.metrics,
215
+ tail_lines=args.tail,
216
+ echo=_echo,
217
+ )
218
+ except KeyboardInterrupt:
219
+ sys.stdout.flush()
220
+ if len(ledger.runs) > recorded_before:
221
+ record = ledger.runs[-1]
222
+ print(
223
+ f"\nonelook: interrupted; recorded run {record['run']} of set "
224
+ f"{args.name!r} (version {record['set_version']}) as "
225
+ f"{'the blind run' if record['label'] == BLIND else 'a repeat'}, "
226
+ "status interrupted",
227
+ file=sys.stderr,
228
+ )
229
+ else:
230
+ print("\nonelook: interrupted; nothing recorded", file=sys.stderr)
231
+ return 130
232
+ record = result.record
233
+ if result.output and not result.output.endswith(b"\n"):
234
+ print()
235
+ where = f"run {record['run']} of set {args.name!r} (version {record['set_version']})"
236
+ if record["label"] == BLIND:
237
+ print(f"onelook: recorded {where} as the blind run")
238
+ else:
239
+ print(
240
+ f"onelook: recorded {where} as a repeat; it is not blind, "
241
+ "and the blind run stays on record"
242
+ )
243
+ if record["engine_changed_since_blind"]:
244
+ print("onelook: the engine has changed since the blind run")
245
+ if record.get("engine_config_changed_since_blind"):
246
+ print(
247
+ "onelook: the engine configuration differs from the blind run's; "
248
+ "compared with the blind run's configuration, the engine files are "
249
+ + ("different" if record["engine_changed_since_blind"] else "the same")
250
+ )
251
+ print(f"onelook: engine {record['engine_fingerprint']}, exit code {record['exit_code']}")
252
+ failed = False
253
+ if "metrics_error" in record:
254
+ print(f"onelook: no metrics recorded: {record['metrics_error']}")
255
+ failed = True
256
+ elif record.get("metrics_file_unchanged"):
257
+ print(
258
+ f"onelook: warning: {record['metrics_file']} was not modified by the "
259
+ "command; the recorded metrics may be stale"
260
+ )
261
+ sys.stdout.flush()
262
+ code = record["exit_code"]
263
+ if code != 0:
264
+ return code if 0 < code < 256 else 1
265
+ return 1 if failed else 0
266
+
267
+
268
+ def _status(args, _command) -> int:
269
+ ledger = Ledger.load(args.ledger)
270
+ current = status(ledger)
271
+ if not current.sets:
272
+ print("no sealed sets")
273
+ return 0
274
+ failing = 0
275
+ for item in current.sets:
276
+ parts = [
277
+ "sealed files intact"
278
+ if item.check.intact
279
+ else f"sealed files CHANGED ({item.check.describe()})"
280
+ ]
281
+ strict_problem = False
282
+ if not item.runs:
283
+ parts.append("no runs")
284
+ else:
285
+ runs = "1 run (blind)" if not item.repeats else (
286
+ f"{len(item.runs)} runs (1 blind, {item.repeats} repeat)"
287
+ )
288
+ parts.append(runs)
289
+ if item.blind_run.get("status") == "interrupted":
290
+ parts.append("blind run was interrupted")
291
+ elif item.blind_run["exit_code"] != 0:
292
+ parts.append(f"blind run exited with code {item.blind_run['exit_code']}")
293
+ if item.engine_matches:
294
+ parts.append("engine matches the blind run")
295
+ elif item.engine_error:
296
+ parts.append(f"engine CANNOT BE FINGERPRINTED ({item.engine_error})")
297
+ else:
298
+ parts.append("engine CHANGED since the blind run")
299
+ if item.engine_config_differs:
300
+ parts.append("engine configuration edited since the blind run")
301
+ strict_problem = bool(item.repeats) or item.blind_run["exit_code"] != 0
302
+ bad = not item.ok or (args.strict and strict_problem)
303
+ failing += bad
304
+ print(f"{'FAIL' if bad else 'ok':<4} {item.name} (v{item.version}): " + "; ".join(parts))
305
+ if failing:
306
+ print(f"{failing} of {_plural(len(current.sets), 'set')} no longer hold{'s' if failing == 1 else ''}")
307
+ return 1
308
+ return 0
309
+
310
+
311
+ def _report(args, _command) -> int:
312
+ ledger = Ledger.load(args.ledger)
313
+ reports = report(ledger, args.names)
314
+ if args.write:
315
+ if args.format != "md":
316
+ raise OnelookError("--write produces Markdown; drop --format json")
317
+ for line in write_blocks(args.write, reports):
318
+ print(f"{args.write}: {line}")
319
+ return 0
320
+ if args.format == "json":
321
+ print(json.dumps({"onelook": 1, "sets": reports}, indent=2, ensure_ascii=False))
322
+ else:
323
+ sys.stdout.write(render_markdown(reports))
324
+ return 0
325
+
326
+
327
+ def _verify(args, _command) -> int:
328
+ ledger = Ledger.load(args.ledger)
329
+ result = verify(ledger, args.readme)
330
+ for tag, text in result.lines:
331
+ print(f"{tag:<4} {text}")
332
+ if result.ok:
333
+ print(
334
+ "verified: the README's report is accurate for this checkout"
335
+ if result.blocks
336
+ else "verified: every sealed set is intact and the engine matches each blind run"
337
+ )
338
+ return 0
339
+ print("NOT verified")
340
+ return 1
341
+
342
+
343
+ def main(argv: list[str] | None = None) -> int:
344
+ argv = list(sys.argv[1:] if argv is None else argv)
345
+ command = None
346
+ if "--" in argv:
347
+ split = argv.index("--")
348
+ argv, command = argv[:split], argv[split + 1 :]
349
+ parser = build_parser()
350
+ args = parser.parse_args(argv)
351
+ if command is not None and args.command_name != "run":
352
+ parser.error("'--' is only used by `onelook run`")
353
+ try:
354
+ return args.func(args, command)
355
+ except OnelookError as exc:
356
+ print(f"onelook: error: {exc}", file=sys.stderr)
357
+ return 2
358
+
359
+
360
+ if __name__ == "__main__":
361
+ sys.exit(main())