frameledger 0.9.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.
Files changed (86) hide show
  1. frameledger/__init__.py +27 -0
  2. frameledger/__main__.py +23 -0
  3. frameledger/alternate.py +252 -0
  4. frameledger/atomic.py +68 -0
  5. frameledger/baseline.py +115 -0
  6. frameledger/bisecting.py +429 -0
  7. frameledger/budgeting.py +390 -0
  8. frameledger/cli.py +1155 -0
  9. frameledger/compare.py +1012 -0
  10. frameledger/expect.py +165 -0
  11. frameledger/generated.py +115 -0
  12. frameledger/kit/README.txt +140 -0
  13. frameledger/kit/basic.csv +30 -0
  14. frameledger/kit/basic.json +64 -0
  15. frameledger/kit/dropped.csv +35 -0
  16. frameledger/kit/dropped.json +73 -0
  17. frameledger/kit/events.csv +33 -0
  18. frameledger/kit/events.json +67 -0
  19. frameledger/kit/frame-hole.csv +37 -0
  20. frameledger/kit/frame-hole.json +73 -0
  21. frameledger/kit/frame-numbers-large.csv +30 -0
  22. frameledger/kit/frame-numbers-large.json +64 -0
  23. frameledger/kit/gpu-after-last-dropped.csv +20 -0
  24. frameledger/kit/gpu-after-last-dropped.json +56 -0
  25. frameledger/kit/gpu-after-last.csv +22 -0
  26. frameledger/kit/gpu-after-last.json +56 -0
  27. frameledger/kit/gpu-late-segments.csv +28 -0
  28. frameledger/kit/gpu-late-segments.json +66 -0
  29. frameledger/kit/gpu-late.csv +28 -0
  30. frameledger/kit/gpu-late.json +66 -0
  31. frameledger/kit/gpu-over-wall-not-pipelined.csv +32 -0
  32. frameledger/kit/gpu-over-wall-not-pipelined.json +70 -0
  33. frameledger/kit/header-every-field.csv +23 -0
  34. frameledger/kit/header-every-field.json +75 -0
  35. frameledger/kit/header-required-only.csv +23 -0
  36. frameledger/kit/header-required-only.json +54 -0
  37. frameledger/kit/hitch.csv +122 -0
  38. frameledger/kit/hitch.json +196 -0
  39. frameledger/kit/longest-fields.csv +25 -0
  40. frameledger/kit/longest-fields.json +57 -0
  41. frameledger/kit/negative.csv +26 -0
  42. frameledger/kit/negative.json +58 -0
  43. frameledger/kit/pipelined-gpu-over-wall.csv +32 -0
  44. frameledger/kit/pipelined-gpu-over-wall.json +70 -0
  45. frameledger/kit/quoting.csv +30 -0
  46. frameledger/kit/quoting.json +64 -0
  47. frameledger/kit/round-largest.csv +26 -0
  48. frameledger/kit/round-largest.json +58 -0
  49. frameledger/kit/round-ties.csv +33 -0
  50. frameledger/kit/round-ties.json +65 -0
  51. frameledger/kit/static-no-summary.csv +24 -0
  52. frameledger/kit/static-no-summary.json +56 -0
  53. frameledger/kit/static-summary.csv +24 -0
  54. frameledger/kit/static-summary.json +56 -0
  55. frameledger/kit/unfinished.csv +26 -0
  56. frameledger/kit/unfinished.json +61 -0
  57. frameledger/kit.py +80 -0
  58. frameledger/ledger.py +607 -0
  59. frameledger/picture.py +439 -0
  60. frameledger/presentmon.py +375 -0
  61. frameledger/render.py +593 -0
  62. frameledger/run_report.py +584 -0
  63. frameledger/scenes.py +241 -0
  64. frameledger/schemas/alternate.schema.json +1032 -0
  65. frameledger/schemas/bisect.schema.json +450 -0
  66. frameledger/schemas/budget.schema.json +294 -0
  67. frameledger/schemas/check.schema.json +200 -0
  68. frameledger/schemas/compare.schema.json +1070 -0
  69. frameledger/schemas/floor.schema.json +254 -0
  70. frameledger/schemas/import.schema.json +172 -0
  71. frameledger/schemas/kit.schema.json +133 -0
  72. frameledger/schemas/report.schema.json +360 -0
  73. frameledger/schemas/selftest.schema.json +136 -0
  74. frameledger/schemas/survey.schema.json +322 -0
  75. frameledger/schemas.py +36 -0
  76. frameledger/selftest.py +136 -0
  77. frameledger/stats.py +32 -0
  78. frameledger/strict.py +239 -0
  79. frameledger/survey.py +136 -0
  80. frameledger/trust.py +83 -0
  81. frameledger/variants.py +321 -0
  82. frameledger-0.9.0.dist-info/METADATA +12 -0
  83. frameledger-0.9.0.dist-info/RECORD +86 -0
  84. frameledger-0.9.0.dist-info/WHEEL +4 -0
  85. frameledger-0.9.0.dist-info/entry_points.txt +2 -0
  86. frameledger-0.9.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,27 @@
1
+ """The installed form (FLED-0043): pip puts this folder in site-packages as
2
+ the package `frameledger`, and its `frameledger` command calls main().
3
+
4
+ Importing the package does nothing else. __main__.py puts this folder on
5
+ the import path when frameledger runs, since its modules import each other
6
+ by bare name (docs/design.md § The parts). frameledger is a command, not a
7
+ library: main() runs it in this process, path change included, so a
8
+ host program's own `cli` or `stats` module may meet frameledger's. Offered
9
+ as a library, it would need package imports (`from frameledger import
10
+ ledger`) instead.
11
+
12
+ scripts/build_release.py leaves this file out of the .pyz, and the source
13
+ form never imports it.
14
+ """
15
+
16
+ import os
17
+ import runpy
18
+ from typing import NoReturn
19
+
20
+
21
+ def main() -> NoReturn:
22
+ """Run the analyser as `python3 -I src/frameledger` does; exits with its code.
23
+
24
+ It runs __main__.py, never cli.main itself, so __main__'s path and
25
+ output setup apply. `python -m frameledger` runs __main__.py directly.
26
+ """
27
+ runpy.run_path(os.path.join(os.path.dirname(os.path.abspath(__file__)), "__main__.py"), run_name="__main__")
@@ -0,0 +1,23 @@
1
+ """Run as `python3 -I src/frameledger ...`, `python3 -I frameledger.pyz ...`,
2
+ or, installed by pip, `frameledger ...` or `python3 -m frameledger ...`."""
3
+
4
+ import os
5
+ import sys
6
+
7
+ # The modules import each other by bare name (docs/design.md § The parts).
8
+ # The first two forms already have this folder first on the import path;
9
+ # the installed forms do not have it at all, so it goes first, ahead of any
10
+ # other module of the same name (FLED-0043). A folder already on the path
11
+ # is left where it is.
12
+ _HERE = os.path.dirname(os.path.abspath(__file__))
13
+ if _HERE not in sys.path:
14
+ sys.path.insert(0, _HERE)
15
+
16
+ import cli # noqa: E402 - needs the path above
17
+
18
+ # A Windows console may not encode every character in a path; print a
19
+ # stand-in rather than stop with an encoding error.
20
+ # Standard output may be closed (None) when it runs headless (S20).
21
+ if sys.stdout is not None:
22
+ sys.stdout.reconfigure(errors="backslashreplace")
23
+ sys.exit(cli.main(sys.argv[1:]))
@@ -0,0 +1,252 @@
1
+ """`alternate`: run the old and new builds' commands in turn, each into its
2
+ own run file (docs/specs/FLED-0001-run-file-format.md § 4.15); or a base's
3
+ command and each named variant's (§ 4.16). Each of those is a side.
4
+
5
+ This module only plans and runs the commands. It times nothing and reads
6
+ no run file: cli.py compares the files once every run has finished.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import re
13
+ import signal
14
+ import subprocess
15
+ import sys
16
+ import time
17
+ from typing import NamedTuple
18
+
19
+ import ledger
20
+
21
+ PLACEHOLDER = "{run}"
22
+ # The sides with a flag of their own; a variant's is --variant NAME. A side
23
+ # added here is a name variants.RESERVED must refuse.
24
+ FLAG_SIDES = ("old", "new", "base")
25
+ FEWEST_RUNS, MOST_RUNS = 3, 100
26
+ MOST_WARMUPS = 10
27
+ POSIX = os.name == "posix"
28
+ # A --out made of these needs no quoting in its shell. /bin/sh reads a
29
+ # backslash as an escape (UT Ants), and a leading ~ as home, so only
30
+ # Windows allows them; there ~ is in short names such as NAME~1 (Vestige).
31
+ SAFE_CHARS = "._-/:" if POSIX else "._-/\\:~"
32
+ SAFE_DIR = re.compile(f"[A-Za-z0-9{re.escape(SAFE_CHARS)}]+")
33
+ # Windows' Ctrl-Break arrives as SIGBREAK, which stops a run as Ctrl-C does.
34
+ STOP_SIGNALS = (signal.SIGINT, signal.SIGTERM) + ((signal.SIGBREAK,) if hasattr(signal, "SIGBREAK") else ())
35
+ # Windows has no SIGKILL, and KILL must differ from every stop signal there
36
+ # too (UT Ants), so it is None and _signal_windows_tree kills.
37
+ KILL = getattr(signal, "SIGKILL", None)
38
+ GRACE_S = 10 # how long a stopped command has to end before it is killed
39
+ POLL_S = 0.05 # how often a wait checks for a stop
40
+ SETTLE_S = 2 # how long a finished command's leftover processes have to end
41
+
42
+
43
+ class Run(NamedTuple):
44
+ name: str # old-1, new-warmup-1, ...
45
+ side: str # old or new; or base, or a variant's name
46
+ number: int # 1 for old-1 and old-warmup-1
47
+ timed: bool # False for a warm-up, which is never compared
48
+ path: str # the run's own file, absolute
49
+
50
+
51
+ def plan(out: str, sides: list[str], runs: int, warmup: int) -> list[Run]:
52
+ """Rounds of one run a side. Warm-up rounds first, the sides in the
53
+ order given; then timed rounds, in that order in odd rounds and
54
+ reversed in even ones, so a steady drift cancels over every two
55
+ rounds, for every side. With old and new that is old-1, new-1, new-2,
56
+ old-2, ...."""
57
+ planned = []
58
+ for number in range(1, warmup + 1):
59
+ planned += [_run(out, side, number, False) for side in sides]
60
+ for number in range(1, runs + 1):
61
+ planned += [_run(out, side, number, True) for side in (sides if number % 2 else reversed(sides))]
62
+ return planned
63
+
64
+
65
+ def _run(out: str, side: str, number: int, timed: bool) -> Run:
66
+ name = f"{side}-{number}" if timed else f"{side}-warmup-{number}"
67
+ return Run(name, side, number, timed, os.path.join(out, f"{name}.csv"))
68
+
69
+
70
+ def check_setup(commands: dict[str, str], out: str, planned: list[Run]) -> None:
71
+ """Every setup error, found before any command starts. `commands` maps
72
+ each side to its command."""
73
+ for side, command in commands.items():
74
+ if PLACEHOLDER not in command:
75
+ flag = f"--{side}" if side in FLAG_SIDES else f"--variant {side}"
76
+ raise ledger.LedgerError(f"{flag} must hold {PLACEHOLDER}, where its run file's path goes")
77
+ if not os.path.isdir(out):
78
+ raise ledger.LedgerError(f"--out {out} is not an existing folder")
79
+ if not SAFE_DIR.fullmatch(out):
80
+ raise ledger.LedgerError(f"--out {out} may hold only ASCII letters, digits and the characters "
81
+ f"{' '.join(SAFE_CHARS)}, in every folder of its path, so it needs no "
82
+ "quoting; pick a folder whose path holds only those")
83
+ for run in planned:
84
+ if os.path.lexists(run.path):
85
+ raise ledger.LedgerError(f"{run.path} already exists, and no run file is overwritten; "
86
+ "give a new --out, or remove its run files")
87
+
88
+
89
+ def run_all(commands: dict[str, str], planned: list[Run]) -> dict | None:
90
+ """Run each command in turn. None when every run finished; otherwise
91
+ § 4.15's `stopped`, after ending the failed command's processes and
92
+ deleting its file.
93
+
94
+ While the commands run, Ctrl-C and SIGTERM are only recorded, never
95
+ raised, so a stop cannot land between two steps; each wait checks
96
+ for one (POLL_S)."""
97
+ stops: list[int] = []
98
+ previous = {signum: signal.signal(signum, lambda signum, _frame: stops.append(signum))
99
+ for signum in STOP_SIGNALS}
100
+ try:
101
+ for index, run in enumerate(planned, 1):
102
+ command = commands[run.side].replace(PLACEHOLDER, run.path)
103
+ if stops: # it came between two runs
104
+ exit_code, reason = None, _stopped_reason(stops[0])
105
+ else:
106
+ print(f"alternate: running {run.name} ({index} of {len(planned)})", file=sys.stderr,
107
+ flush=True)
108
+ exit_code, reason = _run_one(command, run.path, stops)
109
+ if reason:
110
+ if os.path.isfile(run.path): # a directory there is not this run's to remove
111
+ os.remove(run.path)
112
+ return {"run": run.name, "command": command, "reason": reason, "exit_code": exit_code,
113
+ "finished": [done.name for done in planned[:index - 1]]}
114
+ return None
115
+ finally:
116
+ for signum, handler in previous.items():
117
+ signal.signal(signum, handler)
118
+
119
+
120
+ def _run_one(command: str, path: str, stops: list[int]) -> tuple[int | None, str | None]:
121
+ """(exit code, why the run failed), the reason None when it did not.
122
+ The engine's output goes to standard error, so --json output is never
123
+ mixed with it. The command gets its own process group, so a stop
124
+ reaches every process it started, a wrapper's engine included; the
125
+ terminal's Ctrl-C then reaches only this process, which passes it
126
+ on."""
127
+ process = subprocess.Popen(command, shell=True, stdout=sys.stderr.fileno(), start_new_session=POSIX,
128
+ creationflags=0 if POSIX else subprocess.CREATE_NEW_PROCESS_GROUP)
129
+ code = _wait(process, stops)
130
+ if code is None:
131
+ return None, _stopped_reason(stops[0]) + _end_group(process, stops[0], stops)
132
+ if code == 0 and POSIX and not _waited(process, lambda: bool(stops), SETTLE_S):
133
+ # Left running, it would overlap the next run (UT Ants). SETTLE_S
134
+ # lets a headless display finish tearing down first (DOOM Ants).
135
+ if stops:
136
+ return None, _stopped_reason(stops[0]) + _end_group(process, stops[0], stops)
137
+ return None, "the command left processes running" + _end_group(process, signal.SIGTERM, stops)
138
+ if code != 0:
139
+ stuck = _end_group(process, signal.SIGTERM, stops) # nothing left may write the file later
140
+ return (None if code < 0 else code), _exit_reason(code) + stuck
141
+ if not os.path.exists(path):
142
+ return None, f"the command wrote no file at {path}"
143
+ return code, None
144
+
145
+
146
+ def _wait(process: subprocess.Popen, stops: list[int]) -> int | None:
147
+ """The command's exit code, or None once a stop is recorded."""
148
+ while (code := process.poll()) is None:
149
+ if stops:
150
+ return None
151
+ time.sleep(POLL_S)
152
+ return code
153
+
154
+
155
+ def _end_group(process: subprocess.Popen, signum: int, stops: list[int]) -> str:
156
+ """Send `signum` to the command's processes, give them GRACE_S seconds
157
+ to end, then kill them, and give that GRACE_S too. A further stop
158
+ kills them at once. Returns "" once none is left, or a clause naming
159
+ the group that would not die, as a process stuck in a GPU driver can
160
+ (UT Ants)."""
161
+ seen = len(stops)
162
+ _signal_group(process, signum)
163
+ if not _waited(process, lambda: len(stops) > seen):
164
+ _signal_group(process, KILL)
165
+ if not _waited(process, lambda: False):
166
+ return f"; process group {process.pid} did not end after being killed"
167
+ return ""
168
+
169
+
170
+ def _waited(process: subprocess.Popen, give_up, seconds: float = GRACE_S) -> bool:
171
+ """True once the command's processes have all ended; False after
172
+ `seconds`, or as soon as give_up() is true."""
173
+ deadline = time.monotonic() + seconds
174
+ while _group_alive(process):
175
+ if give_up() or time.monotonic() >= deadline:
176
+ return False
177
+ time.sleep(POLL_S)
178
+ return True
179
+
180
+
181
+ def _signal_group(process: subprocess.Popen, signum: int | None) -> None:
182
+ if not POSIX:
183
+ _signal_windows_tree(process, signum)
184
+ return
185
+ try:
186
+ os.killpg(process.pid, signum)
187
+ except (ProcessLookupError, PermissionError): # none left, or none this process may signal: see _group_alive
188
+ pass
189
+
190
+
191
+ def _signal_windows_tree(process: subprocess.Popen, signum: int | None) -> None:
192
+ """Windows has no signals to send a group (Vestige's review). A stop
193
+ becomes CTRL_BREAK_EVENT, which reaches every process in the command's
194
+ console process group; a kill becomes taskkill /T /F, which ends
195
+ cmd.exe and every process it started that is still running. Both need
196
+ cmd.exe alive: a process whose parent has exited is in no tree. If
197
+ cmd.exe exits between poll() and taskkill, taskkill finds nothing:
198
+ Popen's open handle keeps the id from being reused (DOOM Ants)."""
199
+ if process.poll() is not None:
200
+ return
201
+ if signum is KILL:
202
+ subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"],
203
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)
204
+ return
205
+ try:
206
+ process.send_signal(signal.CTRL_BREAK_EVENT)
207
+ except OSError:
208
+ pass # no console (a service, a scheduled task): the kill after GRACE_S ends it (UT Ants)
209
+
210
+
211
+ def _group_alive(process: subprocess.Popen) -> bool:
212
+ if process.poll() is None: # poll also reaps the shell once it has ended
213
+ return True
214
+ if not POSIX:
215
+ return False
216
+ try:
217
+ os.killpg(process.pid, 0)
218
+ except ProcessLookupError:
219
+ return False
220
+ except PermissionError:
221
+ # The group still has members, but none this process may signal.
222
+ # On macOS that includes members that have ended and are not yet
223
+ # collected, where Linux accepts the signal; once the system
224
+ # collects them the answer is ProcessLookupError. They are not
225
+ # gone, so the group is alive; each caller's wait has a deadline,
226
+ # so this cannot hang (FLED-0038).
227
+ pass
228
+ return True
229
+
230
+
231
+ def _exit_reason(code: int) -> str:
232
+ if code < 0:
233
+ return f"the command was killed by signal {-code} ({_signal_name(-code)})"
234
+ reason = f"the command exited with code {code}"
235
+ if POSIX and 128 < code < 128 + signal.NSIG: # how /bin/sh reports a killed command
236
+ reason += f", as the shell reports a command killed by signal {code - 128} ({_signal_name(code - 128)})"
237
+ return reason
238
+
239
+
240
+ def _stopped_reason(signum: int) -> str:
241
+ return f"alternate was stopped by {_signal_name(signum)} while it ran"
242
+
243
+
244
+ def _signal_name(signum: int) -> str:
245
+ try:
246
+ return signal.Signals(signum).name
247
+ except ValueError:
248
+ return f"signal {signum}"
249
+
250
+
251
+ def stopped_sentences(stopped: dict) -> list[str]:
252
+ return [f"{stopped['run']} failed: {stopped['reason']}.", f"Its command was: {stopped['command']}"]
frameledger/atomic.py ADDED
@@ -0,0 +1,68 @@
1
+ """Write a file whole or not at all.
2
+
3
+ The text goes to a temporary file beside the target, which is then put
4
+ in the target's place. So a write that fails part way leaves no half
5
+ file, and leaves the target as it was. `import` writes its run file
6
+ this way, never over an existing file (§ 4.18 of
7
+ docs/specs/FLED-0001-run-file-format.md), and `report --html` its page,
8
+ which it overwrites (§ 4.21).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ import tempfile
15
+
16
+ import ledger
17
+
18
+
19
+ class Exists(ledger.LedgerError):
20
+ """`path` holds a file, and the write was not to overwrite one."""
21
+
22
+ def __init__(self, path: str):
23
+ super().__init__("the file exists, and it is not to be overwritten", path)
24
+
25
+
26
+ def write(path: str, text: str, overwrite: bool = False) -> None:
27
+ """Write `text` to `path`, replacing a file there only when
28
+ `overwrite`; without it, a file there raises Exists. Raises
29
+ LedgerError naming `path` when it cannot write."""
30
+ folder = os.path.dirname(os.path.abspath(path))
31
+ try:
32
+ handle, temporary = tempfile.mkstemp(dir=folder, prefix=".frameledger-")
33
+ except OSError as error:
34
+ raise ledger.LedgerError(error.strerror or "cannot be written", path) from error
35
+ try:
36
+ with os.fdopen(handle, "w", encoding="utf-8", newline="\n") as stream:
37
+ stream.write(text)
38
+ os.chmod(temporary, 0o666 & ~_umask()) # mkstemp's 0600, made what open() would give
39
+ if overwrite:
40
+ os.replace(temporary, path)
41
+ else:
42
+ _link(temporary, path)
43
+ except OSError as error:
44
+ raise ledger.LedgerError(error.strerror or "cannot be written", path) from error
45
+ finally:
46
+ if os.path.lexists(temporary):
47
+ os.unlink(temporary)
48
+
49
+
50
+ def _link(temporary: str, path: str) -> None:
51
+ """Put `temporary` at `path`, never over a file there: a link fails
52
+ if `path` appeared meanwhile, where a rename would overwrite it. A
53
+ file system with no hard links falls back to a rename after one more
54
+ look."""
55
+ try:
56
+ os.link(temporary, path)
57
+ except FileExistsError:
58
+ raise Exists(path) from None
59
+ except OSError:
60
+ if os.path.lexists(path):
61
+ raise Exists(path) from None
62
+ os.replace(temporary, path)
63
+
64
+
65
+ def _umask() -> int:
66
+ mask = os.umask(0)
67
+ os.umask(mask)
68
+ return mask
@@ -0,0 +1,115 @@
1
+ """A baseline file (S24): the run files it names, as paths.
2
+
3
+ The rules are docs/specs/FLED-0001-run-file-format.md § 4.17. The engine
4
+ keeps the file and its runs; this module reads the file and nothing
5
+ else, and never opens a run.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import re
13
+ from pathlib import Path
14
+
15
+ import ledger
16
+
17
+ SCHEMA = 1
18
+ KEYWORD = "# frameledger-baseline"
19
+ FEWEST_RUNS = 3 # § 4.10's smallest set; a test holds it equal to compare.py's
20
+ WINDOWS_DRIVE = re.compile(r"[A-Za-z]:")
21
+
22
+
23
+ def read(path: str) -> list[str]:
24
+ """The run files `path` lists, in its order, as absolute paths.
25
+ Raises LedgerError naming the line at fault."""
26
+ path = os.path.abspath(path)
27
+ try:
28
+ data = Path(path).read_bytes()
29
+ except OSError as error:
30
+ raise ledger.LedgerError(error.strerror or "cannot be read", path) from error
31
+ texts = _lines(data, path)
32
+ if not texts:
33
+ raise ledger.LedgerError(f"the file is empty; its first line must be '{KEYWORD} {{\"schema\":{SCHEMA}}}'",
34
+ path)
35
+ _check_header(texts[0], path)
36
+
37
+ listed: dict[object, int] = {} # a run file's _identity -> the line that names it
38
+ runs = []
39
+ for number, text in enumerate(texts[1:], start=2):
40
+ written = text.strip()
41
+ if not written or written.startswith("#"):
42
+ continue # a blank line or a comment
43
+ run = _resolve(written, os.path.dirname(path))
44
+ if run is None:
45
+ raise ledger.LedgerError(f"'{ledger.clip(written, ledger.LONG_QUOTE)}' is neither a relative path "
46
+ "nor an absolute one on this system", path, number)
47
+ if not os.path.isfile(run): # a moved run must not read as a regression (Vestige)
48
+ raise ledger.LedgerError(f"this line names {run}, which is not a file", path, number)
49
+ # One file under two names would count twice and narrow the spread
50
+ # (Vestige, UT Ants).
51
+ same = _identity(run)
52
+ if same in listed:
53
+ raise ledger.LedgerError(f"this line names {run}, which is line {listed[same]}'s", path, number)
54
+ listed[same] = number
55
+ runs.append(run)
56
+ if len(runs) < FEWEST_RUNS:
57
+ raise ledger.LedgerError(f"the file names {len(runs)} runs; a baseline needs at least {FEWEST_RUNS}, "
58
+ "since two give too many false changes", path)
59
+ return runs
60
+
61
+
62
+ def _identity(run: str) -> object:
63
+ """What two names of one file share: a symbolic link, a hard link, or
64
+ on Windows another letter case. The file's own number where the
65
+ system gives one, else its path with links followed."""
66
+ status = os.stat(run)
67
+ return (status.st_dev, status.st_ino) if status.st_ino else os.path.normcase(os.path.realpath(run))
68
+
69
+
70
+ def _lines(data: bytes, path: str) -> list[str]:
71
+ if data.startswith(b"\xef\xbb\xbf"):
72
+ data = data[3:] # some Windows editors add a byte-order mark
73
+ lines = data.split(b"\n")
74
+ if lines[-1] == b"":
75
+ lines.pop() # the final line ending, not an empty line
76
+ texts = []
77
+ for number, raw in enumerate(lines, start=1):
78
+ try:
79
+ texts.append(raw.removesuffix(b"\r").decode("utf-8"))
80
+ except UnicodeDecodeError:
81
+ raise ledger.LedgerError("the line is not UTF-8 text", path, number) from None
82
+ return texts
83
+
84
+
85
+ def _check_header(text: str, path: str) -> None:
86
+ keyword, _, rest = text.partition(" {")
87
+ if keyword != KEYWORD:
88
+ raise ledger.LedgerError(f"the first line must be '{KEYWORD} {{\"schema\":{SCHEMA}}}'", path, 1)
89
+ try:
90
+ header = json.loads("{" + rest)
91
+ except (ValueError, RecursionError): # a huge integer is a plain ValueError; deep nesting recurses (UT Ants)
92
+ raise ledger.LedgerError("the header is not one JSON object", path, 1) from None
93
+ schema = header.get("schema") if isinstance(header, dict) else None
94
+ if type(schema) is not int or schema != SCHEMA: # not True, not 1.0
95
+ raise ledger.LedgerError(f"schema must be {SCHEMA}, not {json.dumps(schema)}", path, 1)
96
+
97
+
98
+ def _resolve(written: str, folder: str) -> str | None:
99
+ """A listed path as an absolute one. A relative path starts at the
100
+ baseline file's folder, and may use either slash on any platform, so
101
+ one file serves Linux and Windows; an absolute path is the
102
+ platform's own. None for a path that is neither here: one that opens
103
+ with a slash or a drive letter and is still not absolute, as
104
+ `\\runs\\a.csv` or `C:\\runs\\a.csv` on Linux, or `/runs/a.csv` and
105
+ `C:a.csv` on Windows. Joining one to the folder would name a file
106
+ the line never wrote (Vestige, UT Ants). So would a later part with
107
+ a drive letter, `runs/C:a.csv`: Windows' join starts again at it
108
+ (DOOM Ants)."""
109
+ drive, rest = os.path.splitdrive(written)
110
+ if os.path.isabs(written) and (drive or os.sep == "/"):
111
+ return os.path.normpath(written)
112
+ parts = written.replace("\\", "/").split("/")
113
+ if rest[:1] in ("/", "\\") or any(WINDOWS_DRIVE.match(part) for part in parts):
114
+ return None
115
+ return os.path.normpath(os.path.join(folder, *parts))