waymark-cli 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.
Files changed (92) hide show
  1. waymark/__init__.py +3 -0
  2. waymark/__main__.py +8 -0
  3. waymark/adapters/__init__.py +102 -0
  4. waymark/adapters/claude_code.py +238 -0
  5. waymark/assets/__init__.py +43 -0
  6. waymark/assets/agents/wm-implementer.md +45 -0
  7. waymark/assets/agents/wm-reviewer.md +43 -0
  8. waymark/assets/skills/wm-apply/SKILL.md +58 -0
  9. waymark/assets/skills/wm-archive/SKILL.md +32 -0
  10. waymark/assets/skills/wm-explore/SKILL.md +34 -0
  11. waymark/assets/skills/wm-kickoff/SKILL.md +34 -0
  12. waymark/assets/skills/wm-onboard/SKILL.md +27 -0
  13. waymark/assets/skills/wm-pr/SKILL.md +24 -0
  14. waymark/assets/skills/wm-propose/SKILL.md +32 -0
  15. waymark/assets/skills/wm-update/SKILL.md +31 -0
  16. waymark/cli.py +537 -0
  17. waymark/hooks/__init__.py +6 -0
  18. waymark/hooks/commands.py +190 -0
  19. waymark/hooks/decide.py +314 -0
  20. waymark/hooks/events.py +79 -0
  21. waymark/py.typed +0 -0
  22. waymark/record/__init__.py +5 -0
  23. waymark/record/atlas.py +156 -0
  24. waymark/record/changes.py +202 -0
  25. waymark/record/charter.py +75 -0
  26. waymark/record/commits.py +78 -0
  27. waymark/record/config.py +215 -0
  28. waymark/record/deltas.py +318 -0
  29. waymark/record/design.py +80 -0
  30. waymark/record/edits.py +95 -0
  31. waymark/record/evidence.py +58 -0
  32. waymark/record/explorations.py +66 -0
  33. waymark/record/files.py +75 -0
  34. waymark/record/fingerprint.py +73 -0
  35. waymark/record/git.py +167 -0
  36. waymark/record/githooks.py +106 -0
  37. waymark/record/links.py +104 -0
  38. waymark/record/milestones.py +84 -0
  39. waymark/record/moves.py +60 -0
  40. waymark/record/names.py +39 -0
  41. waymark/record/outline.py +144 -0
  42. waymark/record/pointer.py +56 -0
  43. waymark/record/problems.py +20 -0
  44. waymark/record/project.py +118 -0
  45. waymark/record/proposal.py +171 -0
  46. waymark/record/record.py +340 -0
  47. waymark/record/registry.py +158 -0
  48. waymark/record/specs.py +227 -0
  49. waymark/record/state.py +472 -0
  50. waymark/record/store.py +88 -0
  51. waymark/record/tasks.py +415 -0
  52. waymark/record/templates/charter.md +45 -0
  53. waymark/record/templates/ci-workflow.yml +29 -0
  54. waymark/record/templates/config-atlas.toml +8 -0
  55. waymark/record/templates/config.toml +19 -0
  56. waymark/record/templates/delta.md +29 -0
  57. waymark/record/templates/design.md +20 -0
  58. waymark/record/templates/exploration.md +22 -0
  59. waymark/record/templates/goal.md +13 -0
  60. waymark/record/templates/hook-commit-msg +8 -0
  61. waymark/record/templates/hook-pre-commit +8 -0
  62. waymark/record/templates/proposal.md +18 -0
  63. waymark/record/templates/roadmap.md +4 -0
  64. waymark/record/templates/tasks.md +10 -0
  65. waymark/record/templates.py +30 -0
  66. waymark/record/terms.py +51 -0
  67. waymark/record/text.py +197 -0
  68. waymark/services/__init__.py +1 -0
  69. waymark/services/atlas.py +162 -0
  70. waymark/services/check.py +129 -0
  71. waymark/services/ci.py +44 -0
  72. waymark/services/common.py +154 -0
  73. waymark/services/context.py +296 -0
  74. waymark/services/doctor.py +367 -0
  75. waymark/services/githooks.py +132 -0
  76. waymark/services/instructions.py +304 -0
  77. waymark/services/integration.py +170 -0
  78. waymark/services/lifecycle.py +454 -0
  79. waymark/services/migrations.py +90 -0
  80. waymark/services/pr.py +177 -0
  81. waymark/services/references.py +27 -0
  82. waymark/services/setup.py +127 -0
  83. waymark/views/__init__.py +5 -0
  84. waymark/views/payloads.py +568 -0
  85. waymark/views/render.py +506 -0
  86. waymark/views/schemas.py +413 -0
  87. waymark/views/style.py +102 -0
  88. waymark_cli-0.1.0.dist-info/METADATA +313 -0
  89. waymark_cli-0.1.0.dist-info/RECORD +92 -0
  90. waymark_cli-0.1.0.dist-info/WHEEL +4 -0
  91. waymark_cli-0.1.0.dist-info/entry_points.txt +2 -0
  92. waymark_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,171 @@
1
+ """Proposals: why a change is wanted and what it changes, plus its owner and acceptance."""
2
+
3
+ import datetime
4
+ import re
5
+ from collections.abc import Mapping
6
+ from dataclasses import dataclass
7
+
8
+ from waymark.record.outline import collect_sections, content, parse_facts, require_title
9
+ from waymark.record.problems import Problem
10
+ from waymark.record.text import Document
11
+
12
+ OWNER = "Owner"
13
+ ACCEPTED = "Accepted"
14
+ PATH = "Path"
15
+ SYNCED = "Synced"
16
+ SHORT = "short"
17
+ FULL = "full"
18
+
19
+ WHY = "Why"
20
+ WHAT_CHANGES = "What changes"
21
+ NON_GOALS = "Non-goals"
22
+ IMPACT = "Impact"
23
+ OUTCOME = "Outcome"
24
+ REQUIRED_SECTIONS = (WHY, WHAT_CHANGES, NON_GOALS, IMPACT)
25
+
26
+ NO_SPEC_CHANGES = "No spec changes"
27
+
28
+ _ACCEPTANCE = re.compile(r"^(\d{4}-\d{2}-\d{2}) by (\S.*?) \(fingerprint: ([0-9a-f]{16})\)$")
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class Acceptance:
33
+ """The acceptance line: when, by whom, and the fingerprint of what was accepted."""
34
+
35
+ date: datetime.date
36
+ who: str
37
+ fingerprint: str
38
+ index: int
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class Proposal:
43
+ """A change's proposal."""
44
+
45
+ doc: Document
46
+ title: str
47
+ owner: str | None
48
+ short_path: bool
49
+ acceptance: Acceptance | None
50
+ synced: datetime.date | None
51
+ sections: Mapping[str, str]
52
+ no_spec_changes: bool
53
+ outcome: str | None
54
+ problems: tuple[Problem, ...]
55
+
56
+ def accepted_text(self) -> str:
57
+ """The text acceptance covers: everything but the acceptance line and the outcome."""
58
+ skipped: set[int] = set()
59
+ facts = parse_facts(self.doc, {ACCEPTED, SYNCED}, [], prose=True)
60
+ skipped.update(fact.index for fact in facts.values())
61
+ for section in self.doc.sections(2):
62
+ if section.title.casefold() == OUTCOME.casefold():
63
+ skipped.update(range(section.start, section.end))
64
+ lines = self.doc.lines
65
+ kept = [line.text for index, line in enumerate(lines) if index not in skipped]
66
+ while kept and not kept[-1].strip():
67
+ kept.pop()
68
+ return "\n".join(kept)
69
+
70
+
71
+ def format_synced(date: datetime.date) -> str:
72
+ """The synced line as wm writes it."""
73
+ return f"{SYNCED}: {date.isoformat()}"
74
+
75
+
76
+ def format_acceptance(date: datetime.date, who: str, fingerprint: str) -> str:
77
+ """The acceptance line as wm writes it."""
78
+ return f"{ACCEPTED}: {date.isoformat()} by {who} (fingerprint: {fingerprint})"
79
+
80
+
81
+ def _parse_acceptance(
82
+ doc: Document, value: str, index: int, problems: list[Problem]
83
+ ) -> Acceptance | None:
84
+ match = _ACCEPTANCE.match(value)
85
+ date: datetime.date | None = None
86
+ if match:
87
+ try:
88
+ date = datetime.date.fromisoformat(match.group(1))
89
+ except ValueError:
90
+ date = None
91
+ if match is None or date is None:
92
+ problems.append(
93
+ Problem(
94
+ doc.path,
95
+ index + 1,
96
+ "malformed-evidence",
97
+ f'The "{ACCEPTED}:" line doesn\'t follow the format. It is written by wm; '
98
+ "remove the line and accept the change again.",
99
+ )
100
+ )
101
+ return None
102
+ return Acceptance(date, match.group(2).strip(), match.group(3), index)
103
+
104
+
105
+ def parse_proposal(doc: Document) -> Proposal:
106
+ """Read a proposal."""
107
+ problems: list[Problem] = []
108
+ title = require_title(doc, problems)
109
+ facts = parse_facts(doc, {OWNER, ACCEPTED, PATH, SYNCED}, problems, prose=True)
110
+
111
+ owner = facts[OWNER].value if OWNER in facts else ""
112
+ if not owner:
113
+ problems.append(
114
+ Problem(
115
+ doc.path,
116
+ 1,
117
+ "missing-owner",
118
+ f'Every change has one owner. Add an "{OWNER}: <name>" line under the title.',
119
+ )
120
+ )
121
+
122
+ short_path = False
123
+ if PATH in facts:
124
+ value = facts[PATH].value
125
+ short_path = value == SHORT
126
+ if value not in (SHORT, FULL):
127
+ problems.append(
128
+ Problem(
129
+ doc.path,
130
+ facts[PATH].index + 1,
131
+ "invalid-path",
132
+ f'"{PATH}:" is "{SHORT}" for the short path or "{FULL}". '
133
+ "Fix the value, or remove the line for the full path.",
134
+ )
135
+ )
136
+
137
+ acceptance: Acceptance | None = None
138
+ if ACCEPTED in facts:
139
+ fact = facts[ACCEPTED]
140
+ acceptance = _parse_acceptance(doc, fact.value, fact.index, problems)
141
+
142
+ synced: datetime.date | None = None
143
+ if SYNCED in facts:
144
+ try:
145
+ synced = datetime.date.fromisoformat(facts[SYNCED].value)
146
+ except ValueError:
147
+ problems.append(
148
+ Problem(
149
+ doc.path,
150
+ facts[SYNCED].index + 1,
151
+ "malformed-evidence",
152
+ f'The "{SYNCED}:" line holds a date, YYYY-MM-DD. It is written by wm; '
153
+ "remove the line and sync the change again.",
154
+ )
155
+ )
156
+
157
+ found = collect_sections(doc, REQUIRED_SECTIONS, problems, optional=(OUTCOME,))
158
+ sections = {name: content(doc, found, name, problems) for name in REQUIRED_SECTIONS}
159
+ outcome = doc.body(found[OUTCOME]) if OUTCOME in found else None
160
+ return Proposal(
161
+ doc=doc,
162
+ title=title,
163
+ owner=owner or None,
164
+ short_path=short_path,
165
+ acceptance=acceptance,
166
+ synced=synced,
167
+ sections=sections,
168
+ no_spec_changes=NO_SPEC_CHANGES.casefold() in sections[IMPACT].casefold(),
169
+ outcome=outcome or None,
170
+ problems=tuple(problems),
171
+ )
@@ -0,0 +1,340 @@
1
+ """The record as a whole: every artifact, read fresh from the files.
2
+
3
+ Active artifacts are parsed when the record is loaded. Archived changes are
4
+ only listed; each is parsed when something asks for it.
5
+ """
6
+
7
+ import datetime
8
+ from collections.abc import Iterator, Mapping
9
+ from dataclasses import dataclass
10
+
11
+ from waymark.record.changes import PROPOSAL_FILE, SPECS_DIR, Change, load_change
12
+ from waymark.record.charter import CHARTER_FILE, Charter, parse_charter
13
+ from waymark.record.config import CONFIG_FILE, Config, parse_config
14
+ from waymark.record.explorations import Exploration, parse_exploration
15
+ from waymark.record.files import RecordFiles
16
+ from waymark.record.links import LinkChecker
17
+ from waymark.record.milestones import (
18
+ GOAL_FILE,
19
+ ROADMAP_FILE,
20
+ Goal,
21
+ Milestone,
22
+ Roadmap,
23
+ parse_goal,
24
+ parse_roadmap,
25
+ )
26
+ from waymark.record.names import NAME_RULE, is_valid_name, parse_archive_name
27
+ from waymark.record.problems import WHOLE_FILE, Problem
28
+ from waymark.record.project import Project
29
+ from waymark.record.proposal import parse_proposal
30
+ from waymark.record.specs import Spec, parse_spec
31
+ from waymark.record.terms import Layout, ReviewLevel
32
+ from waymark.record.text import Document
33
+
34
+ SPECS = "specs"
35
+ CHANGES = "changes"
36
+ MILESTONES = "milestones"
37
+ EXPLORATIONS = "explorations"
38
+ ARCHIVE = "archive"
39
+
40
+
41
+ @dataclass(frozen=True, order=True)
42
+ class ArchiveEntry:
43
+ """An archived folder: the date it was archived, its name and where it is."""
44
+
45
+ date: datetime.date
46
+ name: str
47
+ path: str
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class HistoryEntry:
52
+ """An archived change that touched a spec, with its outcome."""
53
+
54
+ date: datetime.date
55
+ change: str
56
+ outcome: str | None
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class Record:
61
+ """Everything in the record, as the files now stand."""
62
+
63
+ project: Project
64
+ config: Config | None
65
+ charter: Charter | None
66
+ specs: Mapping[str, Spec]
67
+ changes: Mapping[str, Change]
68
+ archived_changes: tuple[ArchiveEntry, ...]
69
+ milestones: Mapping[str, Milestone]
70
+ archived_milestones: tuple[ArchiveEntry, ...]
71
+ explorations: Mapping[str, Exploration]
72
+ problems: tuple[Problem, ...]
73
+
74
+ @property
75
+ def files(self) -> RecordFiles:
76
+ return RecordFiles(self.project.record_root)
77
+
78
+ @property
79
+ def default_review(self) -> ReviewLevel:
80
+ return self.config.default_review if self.config else ReviewLevel.SELF
81
+
82
+ @property
83
+ def layout(self) -> Layout:
84
+ return self.config.layout if self.config else Layout.REPO
85
+
86
+ def documents(self) -> Iterator[Document]:
87
+ """Every parsed markdown file of the active record."""
88
+ if self.charter:
89
+ yield self.charter.doc
90
+ for spec in self.specs.values():
91
+ yield spec.doc
92
+ for change in self.changes.values():
93
+ if change.proposal:
94
+ yield change.proposal.doc
95
+ for delta in change.deltas.values():
96
+ yield delta.doc
97
+ if change.design:
98
+ yield change.design.doc
99
+ if change.tasks:
100
+ yield change.tasks.doc
101
+ for milestone in self.milestones.values():
102
+ if milestone.goal:
103
+ yield milestone.goal.doc
104
+ if milestone.roadmap:
105
+ yield milestone.roadmap.doc
106
+ for exploration in self.explorations.values():
107
+ yield exploration.doc
108
+
109
+
110
+ def _bad_name(path: str, kind: str) -> Problem:
111
+ return Problem(
112
+ path,
113
+ WHOLE_FILE,
114
+ "invalid-name",
115
+ f"A {kind} is named in {NAME_RULE}. Rename it.",
116
+ )
117
+
118
+
119
+ def _load_config(files: RecordFiles, problems: list[Problem]) -> Config | None:
120
+ text = files.read(CONFIG_FILE, problems)
121
+ if text is None:
122
+ return None
123
+ config, found = parse_config(text)
124
+ problems.extend(found)
125
+ return config
126
+
127
+
128
+ def _load_charter(files: RecordFiles, problems: list[Problem]) -> Charter | None:
129
+ if not files.is_file(CHARTER_FILE):
130
+ problems.append(
131
+ Problem(
132
+ CHARTER_FILE,
133
+ WHOLE_FILE,
134
+ "missing-file",
135
+ "The record has no charter. Create it from the built-in template.",
136
+ )
137
+ )
138
+ return None
139
+ doc = files.document(CHARTER_FILE, problems)
140
+ if doc is None:
141
+ return None
142
+ charter = parse_charter(doc)
143
+ problems.extend(charter.problems)
144
+ return charter
145
+
146
+
147
+ def _load_markdown_folder(
148
+ files: RecordFiles, folder: str, kind: str, problems: list[Problem]
149
+ ) -> dict[str, Document]:
150
+ documents: dict[str, Document] = {}
151
+ for entry in files.entries(folder):
152
+ relative = f"{folder}/{entry.name}"
153
+ name = entry.name.removesuffix(".md")
154
+ if entry.is_dir or not entry.name.endswith(".md"):
155
+ problems.append(
156
+ Problem(
157
+ relative,
158
+ WHOLE_FILE,
159
+ "unexpected-file",
160
+ f'"{folder}/" holds one <name>.md file per {kind}. Move this elsewhere '
161
+ "or remove it.",
162
+ )
163
+ )
164
+ elif not is_valid_name(name):
165
+ problems.append(_bad_name(relative, kind))
166
+ else:
167
+ doc = files.document(relative, problems)
168
+ if doc is not None:
169
+ documents[name] = doc
170
+ return documents
171
+
172
+
173
+ def _split_folder(
174
+ files: RecordFiles, folder: str, kind: str, problems: list[Problem]
175
+ ) -> tuple[list[str], list[ArchiveEntry]]:
176
+ """The active and archived folders under ``changes/`` or ``milestones/``."""
177
+ active: list[str] = []
178
+ archived: list[ArchiveEntry] = []
179
+ for entry in files.entries(folder):
180
+ relative = f"{folder}/{entry.name}"
181
+ if not entry.is_dir:
182
+ problems.append(
183
+ Problem(
184
+ relative,
185
+ WHOLE_FILE,
186
+ "unexpected-file",
187
+ f'"{folder}/" holds one folder per {kind}. Move this file into one, '
188
+ "or remove it.",
189
+ )
190
+ )
191
+ elif entry.name == ARCHIVE:
192
+ continue
193
+ elif is_valid_name(entry.name):
194
+ active.append(entry.name)
195
+ else:
196
+ problems.append(_bad_name(relative, kind))
197
+ for entry in files.entries(f"{folder}/{ARCHIVE}"):
198
+ relative = f"{folder}/{ARCHIVE}/{entry.name}"
199
+ parsed = parse_archive_name(entry.name) if entry.is_dir else None
200
+ if parsed is None:
201
+ problems.append(
202
+ Problem(
203
+ relative,
204
+ WHOLE_FILE,
205
+ "invalid-name",
206
+ f"An archived {kind} is a folder named YYYY-MM-DD-<name>. The archive is "
207
+ "written by wm; rename this to match, or remove it.",
208
+ )
209
+ )
210
+ else:
211
+ archived.append(ArchiveEntry(parsed.date, parsed.name, relative))
212
+ return active, sorted(archived)
213
+
214
+
215
+ def _load_milestone(files: RecordFiles, name: str, path: str, problems: list[Problem]) -> Milestone:
216
+ found: list[Problem] = []
217
+ goal: Goal | None = None
218
+ roadmap: Roadmap | None = None
219
+ for entry in files.entries(path):
220
+ relative = f"{path}/{entry.name}"
221
+ if entry.is_dir or entry.name not in (GOAL_FILE, ROADMAP_FILE):
222
+ found.append(
223
+ Problem(
224
+ relative,
225
+ WHOLE_FILE,
226
+ "unexpected-file",
227
+ f"A milestone holds {GOAL_FILE} and {ROADMAP_FILE}. Move this elsewhere "
228
+ "or remove it.",
229
+ )
230
+ )
231
+ continue
232
+ doc = files.document(relative, found)
233
+ if doc is None:
234
+ continue
235
+ if entry.name == GOAL_FILE:
236
+ goal = parse_goal(doc)
237
+ found.extend(goal.problems)
238
+ else:
239
+ roadmap = parse_roadmap(doc)
240
+ found.extend(roadmap.problems)
241
+ for file_name, artifact in ((GOAL_FILE, goal), (ROADMAP_FILE, roadmap)):
242
+ if artifact is None and not files.is_file(f"{path}/{file_name}"):
243
+ found.append(
244
+ Problem(
245
+ f"{path}/{file_name}",
246
+ WHOLE_FILE,
247
+ "missing-file",
248
+ f"The milestone has no {file_name}. Create it from the built-in template.",
249
+ )
250
+ )
251
+ problems.extend(found)
252
+ return Milestone(name, path, goal, roadmap, tuple(sorted(found)))
253
+
254
+
255
+ def _check_spec_repos(spec: Spec, config: Config | None, problems: list[Problem]) -> None:
256
+ if config is None:
257
+ return
258
+ for repo in spec.repos:
259
+ if repo not in config.repo_names:
260
+ known = ", ".join(sorted(config.repo_names)) or "none"
261
+ problems.append(
262
+ Problem(
263
+ spec.doc.path,
264
+ WHOLE_FILE,
265
+ "unknown-repo",
266
+ f'The spec names the repo "{repo}", which the settings don\'t list '
267
+ f"(repos: {known}).",
268
+ )
269
+ )
270
+
271
+
272
+ def load_record(project: Project) -> Record:
273
+ """Read the whole active record. Nothing is cached; every call reads the files."""
274
+ files = RecordFiles(project.record_root)
275
+ problems: list[Problem] = []
276
+ config = _load_config(files, problems)
277
+ charter = _load_charter(files, problems)
278
+
279
+ specs: dict[str, Spec] = {}
280
+ for name, doc in _load_markdown_folder(files, SPECS, "spec", problems).items():
281
+ specs[name] = parse_spec(name, doc)
282
+ problems.extend(specs[name].problems)
283
+ _check_spec_repos(specs[name], config, problems)
284
+
285
+ change_names, archived_changes = _split_folder(files, CHANGES, "change", problems)
286
+ changes: dict[str, Change] = {}
287
+ for name in change_names:
288
+ changes[name] = load_change(files, f"{CHANGES}/{name}", name, config)
289
+ problems.extend(changes[name].problems)
290
+
291
+ milestone_names, archived_milestones = _split_folder(files, MILESTONES, "milestone", problems)
292
+ milestones = {
293
+ name: _load_milestone(files, name, f"{MILESTONES}/{name}", problems)
294
+ for name in milestone_names
295
+ }
296
+
297
+ explorations: dict[str, Exploration] = {}
298
+ for name, doc in _load_markdown_folder(files, EXPLORATIONS, "exploration", problems).items():
299
+ explorations[name] = parse_exploration(name, doc)
300
+ problems.extend(explorations[name].problems)
301
+
302
+ return Record(
303
+ project=project,
304
+ config=config,
305
+ charter=charter,
306
+ specs=specs,
307
+ changes=changes,
308
+ archived_changes=tuple(archived_changes),
309
+ milestones=milestones,
310
+ archived_milestones=tuple(archived_milestones),
311
+ explorations=explorations,
312
+ problems=tuple(sorted(problems)),
313
+ )
314
+
315
+
316
+ def load_archived_change(record: Record, entry: ArchiveEntry) -> Change:
317
+ """Read one archived change."""
318
+ return load_change(record.files, entry.path, entry.name, record.config, entry.date)
319
+
320
+
321
+ def spec_history(record: Record, domain: str) -> tuple[HistoryEntry, ...]:
322
+ """The archived changes whose deltas touched a spec, oldest first, with their outcomes."""
323
+ files = record.files
324
+ history: list[HistoryEntry] = []
325
+ for entry in record.archived_changes:
326
+ if not files.is_file(f"{entry.path}/{SPECS_DIR}/{domain}.md"):
327
+ continue
328
+ doc = files.document(f"{entry.path}/{PROPOSAL_FILE}", [])
329
+ outcome = parse_proposal(doc).outcome if doc else None
330
+ history.append(HistoryEntry(entry.date, entry.name, outcome))
331
+ return tuple(history)
332
+
333
+
334
+ def link_problems(record: Record) -> tuple[Problem, ...]:
335
+ """Every broken or non-portable link in the active record."""
336
+ checker = LinkChecker(record.project.record_root)
337
+ found: list[Problem] = []
338
+ for doc in record.documents():
339
+ found.extend(checker.problems(doc))
340
+ return tuple(sorted(found))
@@ -0,0 +1,158 @@
1
+ """The per-machine registry: where each atlas and its code repos sit on this machine.
2
+
3
+ It lives in the user's settings folder, outside every repository, and is
4
+ written whole by wm. ``WAYMARK_REGISTRY`` names another file to use instead.
5
+ """
6
+
7
+ import json
8
+ import os
9
+ import sys
10
+ import tomllib
11
+ from collections.abc import Mapping
12
+ from dataclasses import dataclass, field, replace
13
+ from pathlib import Path, PurePosixPath
14
+
15
+ from waymark.record.files import RecordFiles
16
+ from waymark.record.store import Transaction
17
+
18
+ REGISTRY_ENV = "WAYMARK_REGISTRY"
19
+ REGISTRY_FILE = "registry.toml"
20
+ _FOLDER = "waymark"
21
+
22
+ _HEADER = (
23
+ "# The atlases and code repos on this machine, and where each one is.\n"
24
+ '# Written by wm ("wm atlas register"). "wm atlas doctor" checks it.\n'
25
+ )
26
+
27
+
28
+ def registry_path(
29
+ environ: Mapping[str, str] | None = None,
30
+ platform: str | None = None,
31
+ home: Path | None = None,
32
+ ) -> Path:
33
+ """Where this machine's registry is: the user's settings folder, or ``WAYMARK_REGISTRY``."""
34
+ env = os.environ if environ is None else environ
35
+ override = env.get(REGISTRY_ENV, "").strip()
36
+ if override:
37
+ return Path(override).expanduser()
38
+ where = sys.platform if platform is None else platform
39
+ base = Path.home() if home is None else home
40
+ if where.startswith("win"):
41
+ appdata = env.get("APPDATA", "").strip()
42
+ folder = Path(appdata) if appdata else base / "AppData" / "Roaming"
43
+ elif where == "darwin":
44
+ folder = base / "Library" / "Application Support"
45
+ else:
46
+ xdg = env.get("XDG_CONFIG_HOME", "").strip()
47
+ folder = Path(xdg) if xdg and PurePosixPath(xdg).is_absolute() else base / ".config"
48
+ return folder / _FOLDER / REGISTRY_FILE
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class AtlasEntry:
53
+ """A registered atlas: its folder, and the folders of its code repos."""
54
+
55
+ name: str
56
+ path: Path | None
57
+ repos: Mapping[str, Path] = field(default_factory=dict)
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class Registry:
62
+ """The registry as read from its file. ``problems`` says what could not be read."""
63
+
64
+ path: Path
65
+ atlases: Mapping[str, AtlasEntry] = field(default_factory=dict)
66
+ problems: tuple[str, ...] = ()
67
+
68
+ def atlas(self, name: str) -> AtlasEntry | None:
69
+ return self.atlases.get(name)
70
+
71
+ def repo(self, atlas: str, repo: str) -> Path | None:
72
+ entry = self.atlases.get(atlas)
73
+ return entry.repos.get(repo) if entry else None
74
+
75
+ def with_atlas(self, name: str, path: Path) -> "Registry":
76
+ """The registry with an atlas registered at a folder, keeping its repos."""
77
+ current = self.atlases.get(name)
78
+ repos = current.repos if current else {}
79
+ return replace(self, atlases={**self.atlases, name: AtlasEntry(name, path, repos)})
80
+
81
+ def with_repo(self, atlas: str, repo: str, path: Path) -> "Registry":
82
+ """The registry with one of an atlas's code repos registered at a folder."""
83
+ current = self.atlases.get(atlas) or AtlasEntry(atlas, None)
84
+ entry = AtlasEntry(atlas, current.path, {**current.repos, repo: path})
85
+ return replace(self, atlases={**self.atlases, atlas: entry})
86
+
87
+
88
+ def _string(value: str) -> str:
89
+ """A TOML basic string. JSON's escapes are all valid in TOML."""
90
+ return json.dumps(value, ensure_ascii=False)
91
+
92
+
93
+ def render_registry(registry: Registry) -> str:
94
+ """The registry's file text."""
95
+ parts = [_HEADER]
96
+ for name in sorted(registry.atlases):
97
+ entry = registry.atlases[name]
98
+ parts.append(f"\n[atlases.{_string(name)}]\n")
99
+ if entry.path is not None:
100
+ parts.append(f"path = {_string(str(entry.path))}\n")
101
+ for repo in sorted(entry.repos):
102
+ parts.append(f"\n[atlases.{_string(name)}.repos.{_string(repo)}]\n")
103
+ parts.append(f"path = {_string(str(entry.repos[repo]))}\n")
104
+ return "".join(parts)
105
+
106
+
107
+ def _folder(table: object) -> Path | None:
108
+ value = table.get("path") if isinstance(table, dict) else None
109
+ return Path(value) if isinstance(value, str) and value.strip() else None
110
+
111
+
112
+ def parse_registry(path: Path, text: str) -> Registry:
113
+ """Read the registry's text. Entries that can't be read are reported and left out."""
114
+ try:
115
+ data = tomllib.loads(text)
116
+ except tomllib.TOMLDecodeError as error:
117
+ return Registry(path, problems=(f"The registry is not valid TOML: {error}.",))
118
+ problems: list[str] = []
119
+ atlases: dict[str, AtlasEntry] = {}
120
+ tables = data.get("atlases", {})
121
+ if not isinstance(tables, dict) or set(data) - {"atlases"}:
122
+ return Registry(path, problems=('The registry holds only "[atlases.<name>]" tables.',))
123
+ for name, table in tables.items():
124
+ if not isinstance(table, dict):
125
+ problems.append(f'The entry for the atlas "{name}" is not a table.')
126
+ continue
127
+ repos: dict[str, Path] = {}
128
+ repo_tables = table.get("repos", {})
129
+ for repo, repo_table in repo_tables.items() if isinstance(repo_tables, dict) else ():
130
+ folder = _folder(repo_table)
131
+ if folder is None:
132
+ problems.append(f'The code repo "{repo}" of the atlas "{name}" has no path.')
133
+ else:
134
+ repos[repo] = folder
135
+ atlases[name] = AtlasEntry(name, _folder(table), repos)
136
+ return Registry(path, atlases, tuple(problems))
137
+
138
+
139
+ def load_registry(path: Path | None = None) -> Registry:
140
+ """Read this machine's registry. A registry that doesn't exist yet is empty."""
141
+ where = registry_path() if path is None else path
142
+ try:
143
+ text = where.read_bytes().decode("utf-8")
144
+ except FileNotFoundError:
145
+ return Registry(where)
146
+ except UnicodeDecodeError:
147
+ return Registry(where, problems=("The registry is not valid UTF-8.",))
148
+ except OSError as error:
149
+ reason = error.strerror or type(error).__name__
150
+ return Registry(where, problems=(f"The registry can't be read ({reason}).",))
151
+ return parse_registry(where, text)
152
+
153
+
154
+ def stage_registry(registry: Registry) -> Transaction:
155
+ """A transaction that writes the registry's file; the caller commits it."""
156
+ transaction = Transaction(RecordFiles(registry.path.parent))
157
+ transaction.write(registry.path.name, render_registry(registry))
158
+ return transaction