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,104 @@
1
+ """Links between record files: resolving them and checking that they lead somewhere."""
2
+
3
+ import posixpath
4
+ import re
5
+ from pathlib import Path
6
+ from urllib.parse import unquote
7
+
8
+ from waymark.record.problems import Problem
9
+ from waymark.record.text import Document
10
+
11
+ _SCHEME = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]+:")
12
+ _DRIVE = re.compile(r"^[A-Za-z]:[\\/]")
13
+
14
+
15
+ def is_absolute(target: str) -> bool:
16
+ """Whether a link names an absolute file path, which breaks on another machine."""
17
+ return (target.startswith("/") and not target.startswith("//")) or bool(_DRIVE.match(target))
18
+
19
+
20
+ def local_path(target: str) -> str | None:
21
+ """The relative file path a link points at.
22
+
23
+ None for links wm doesn't follow: web addresses, absolute paths and anchors
24
+ within the same file.
25
+ """
26
+ if is_absolute(target) or _SCHEME.match(target) or target.startswith("//"):
27
+ return None
28
+ path = target.split("#", 1)[0].split("?", 1)[0]
29
+ return unquote(path) or None
30
+
31
+
32
+ def resolve(doc_path: str, target: str) -> str | None:
33
+ """Where a link in a document leads, relative to the record's root.
34
+
35
+ The result starts with ``../`` when the link leaves the record.
36
+ """
37
+ path = local_path(target)
38
+ if path is None:
39
+ return None
40
+ return posixpath.normpath(posixpath.join(posixpath.dirname(doc_path), path))
41
+
42
+
43
+ class LinkChecker:
44
+ """Checks that links lead to existing files, matching names exactly.
45
+
46
+ Names are compared case-sensitively on every platform, so a link that works
47
+ on one machine works on all of them. Folder listings are remembered for the
48
+ life of the checker, which is one command.
49
+ """
50
+
51
+ def __init__(self, record_root: Path) -> None:
52
+ self._root = record_root
53
+ self._listings: dict[Path, frozenset[str]] = {}
54
+
55
+ def _names(self, folder: Path) -> frozenset[str]:
56
+ if folder not in self._listings:
57
+ try:
58
+ names = frozenset(child.name for child in folder.iterdir())
59
+ except OSError:
60
+ names = frozenset()
61
+ self._listings[folder] = names
62
+ return self._listings[folder]
63
+
64
+ def exists(self, relative: str) -> bool:
65
+ """Whether a path relative to the record's root exists, with exact names."""
66
+ current = self._root
67
+ for part in relative.split("/"):
68
+ if part in ("", "."):
69
+ continue
70
+ if part == "..":
71
+ current = current.parent
72
+ continue
73
+ if part not in self._names(current):
74
+ return False
75
+ current = current / part
76
+ return True
77
+
78
+ def problems(self, doc: Document) -> list[Problem]:
79
+ """The links in a document that are broken or not portable."""
80
+ found: list[Problem] = []
81
+ for link in doc.links():
82
+ target = link.target
83
+ if is_absolute(target):
84
+ message = (
85
+ f'"{target}" is an absolute path, which only works on one machine. '
86
+ "Write it relative to this file."
87
+ )
88
+ found.append(Problem(doc.path, link.index + 1, "absolute-link", message))
89
+ continue
90
+ path = local_path(target)
91
+ if path is None:
92
+ continue
93
+ if "\\" in path:
94
+ message = f'"{target}" uses backslashes. Write the link with forward slashes.'
95
+ found.append(Problem(doc.path, link.index + 1, "broken-link", message))
96
+ continue
97
+ resolved = resolve(doc.path, target)
98
+ if resolved is None or not self.exists(resolved):
99
+ message = (
100
+ f'"{target}" doesn\'t lead to a file or folder. Fix the path (names are '
101
+ "matched exactly, including case), or remove the link."
102
+ )
103
+ found.append(Problem(doc.path, link.index + 1, "broken-link", message))
104
+ return found
@@ -0,0 +1,84 @@
1
+ """Milestones: a goal several changes work toward, and the roadmap that lists them."""
2
+
3
+ import re
4
+ from collections.abc import Mapping
5
+ from dataclasses import dataclass
6
+
7
+ from waymark.record.outline import collect_sections, content, require_title
8
+ from waymark.record.problems import Problem
9
+ from waymark.record.text import Document
10
+
11
+ GOAL_FILE = "goal.md"
12
+ ROADMAP_FILE = "roadmap.md"
13
+
14
+ GOAL = "Goal"
15
+ DONE_WHEN = "Done when"
16
+ NON_GOALS = "Non-goals"
17
+ REQUIRED_SECTIONS = (GOAL, DONE_WHEN, NON_GOALS)
18
+
19
+ _ENTRY = re.compile(r"^\s*[-*]\s+(?:\[([ xX])\]\s+)?(\S.*)$")
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class Goal:
24
+ """A milestone's aim."""
25
+
26
+ doc: Document
27
+ title: str
28
+ sections: Mapping[str, str]
29
+ problems: tuple[Problem, ...]
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class RoadmapEntry:
34
+ """One roadmap line: a link to a change, or a plain line for one not proposed yet."""
35
+
36
+ text: str
37
+ target: str | None
38
+ checked: bool
39
+ index: int
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class Roadmap:
44
+ """The changes a milestone expects."""
45
+
46
+ doc: Document
47
+ entries: tuple[RoadmapEntry, ...]
48
+ problems: tuple[Problem, ...]
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class Milestone:
53
+ """A milestone folder: its goal and its roadmap."""
54
+
55
+ name: str
56
+ path: str
57
+ goal: Goal | None
58
+ roadmap: Roadmap | None
59
+ problems: tuple[Problem, ...]
60
+
61
+
62
+ def parse_goal(doc: Document) -> Goal:
63
+ """Read a milestone's goal."""
64
+ problems: list[Problem] = []
65
+ title = require_title(doc, problems)
66
+ found = collect_sections(doc, REQUIRED_SECTIONS, problems)
67
+ sections = {name: content(doc, found, name, problems) for name in REQUIRED_SECTIONS}
68
+ return Goal(doc, title, sections, tuple(problems))
69
+
70
+
71
+ def parse_roadmap(doc: Document) -> Roadmap:
72
+ """Read a roadmap: every list line is an entry, linked or not."""
73
+ problems: list[Problem] = []
74
+ require_title(doc, problems)
75
+ targets: dict[int, str] = {}
76
+ for link in doc.links():
77
+ targets.setdefault(link.index, link.target)
78
+ entries: list[RoadmapEntry] = []
79
+ for index, line in enumerate(doc.lines):
80
+ match = None if line.in_fence else _ENTRY.match(line.text)
81
+ if match:
82
+ checked = match.group(1) is not None and match.group(1) != " "
83
+ entries.append(RoadmapEntry(match.group(2).strip(), targets.get(index), checked, index))
84
+ return Roadmap(doc, tuple(entries), tuple(problems))
@@ -0,0 +1,60 @@
1
+ """Moving a folder inside the record, and rewriting the links the move would break."""
2
+
3
+ import posixpath
4
+ import re
5
+ from urllib.parse import quote
6
+
7
+ from waymark.record.edits import replace_spans
8
+ from waymark.record.links import local_path, resolve
9
+ from waymark.record.text import Document
10
+
11
+ _UNCHECKED = re.compile(r"^(\s*[-*]\s+)\[ \]")
12
+
13
+
14
+ def _inside(path: str, folder: str) -> bool:
15
+ return path == folder or path.startswith(f"{folder}/")
16
+
17
+
18
+ def _retarget(original: str, new_path: str) -> str:
19
+ """A link's new target: the new path, with the original's anchor and style kept."""
20
+ path = local_path(original) or ""
21
+ suffix = original[len(original.split("#", 1)[0].split("?", 1)[0]) :]
22
+ if path.endswith("/") and not new_path.endswith("/"):
23
+ new_path += "/"
24
+ if "%" in original:
25
+ new_path = quote(new_path)
26
+ return new_path + suffix
27
+
28
+
29
+ def rewrite_links(doc: Document, source: str, target: str) -> str:
30
+ """A document's text after the folder ``source`` has moved to ``target``.
31
+
32
+ Links that point into the moved folder follow it. If the document itself is
33
+ in the moved folder, its links to everything outside are re-aimed from its
34
+ new place. Links wm doesn't follow (web addresses, anchors) are left alone.
35
+ """
36
+ moving = _inside(doc.path, source)
37
+ new_doc_path = target + doc.path[len(source) :] if moving else doc.path
38
+ replacements: dict[tuple[int, int, int], str] = {}
39
+ for link in doc.links():
40
+ resolved = resolve(doc.path, link.target)
41
+ if resolved is None:
42
+ continue
43
+ points_inside = _inside(resolved, source)
44
+ if points_inside == moving:
45
+ continue
46
+ destination = target + resolved[len(source) :] if points_inside else resolved
47
+ relative = posixpath.relpath(destination, posixpath.dirname(new_doc_path) or ".")
48
+ replacements[(link.index, link.start, link.end)] = _retarget(link.target, relative)
49
+ return replace_spans(doc, replacements) if replacements else doc.text
50
+
51
+
52
+ def tick_roadmap_lines(doc: Document, folder: str) -> str:
53
+ """A roadmap's text with the lines that link into a folder ticked."""
54
+ replacements: dict[tuple[int, int, int], str] = {}
55
+ for link in doc.links():
56
+ resolved = resolve(doc.path, link.target)
57
+ match = _UNCHECKED.match(doc.lines[link.index].text)
58
+ if resolved is not None and _inside(resolved, folder) and match:
59
+ replacements[(link.index, match.end(1), match.end())] = "[x]"
60
+ return replace_spans(doc, replacements) if replacements else doc.text
@@ -0,0 +1,39 @@
1
+ """Names of changes, specs, milestones and explorations, and of archived folders."""
2
+
3
+ import datetime
4
+ import re
5
+ from dataclasses import dataclass
6
+
7
+ _NAME = re.compile(r"[a-z]+(?:-[a-z]+)*")
8
+ _ARCHIVE_NAME = re.compile(r"(\d{4}-\d{2}-\d{2})-(.+)")
9
+
10
+ NAME_RULE = "lowercase words joined by hyphens, with no digits"
11
+
12
+
13
+ def is_valid_name(name: str) -> bool:
14
+ """Whether a name is kebab-case with no digits."""
15
+ return _NAME.fullmatch(name) is not None
16
+
17
+
18
+ @dataclass(frozen=True, order=True)
19
+ class ArchiveName:
20
+ """An archived folder's name: the date it was archived, then the original name."""
21
+
22
+ date: datetime.date
23
+ name: str
24
+
25
+ @property
26
+ def folder(self) -> str:
27
+ return f"{self.date.isoformat()}-{self.name}"
28
+
29
+
30
+ def parse_archive_name(folder: str) -> ArchiveName | None:
31
+ """Read ``YYYY-MM-DD-<name>``; None when the folder name doesn't follow it."""
32
+ match = _ARCHIVE_NAME.fullmatch(folder)
33
+ if match is None or not is_valid_name(match.group(2)):
34
+ return None
35
+ try:
36
+ date = datetime.date.fromisoformat(match.group(1))
37
+ except ValueError:
38
+ return None
39
+ return ArchiveName(date, match.group(2))
@@ -0,0 +1,144 @@
1
+ """Shared reading of an artifact's outline: its title, fact lines and named sections."""
2
+
3
+ import re
4
+ from collections.abc import Collection, Sequence
5
+ from dataclasses import dataclass
6
+
7
+ from waymark.record.problems import Problem
8
+ from waymark.record.text import Document, Section
9
+
10
+ _FACT = re.compile(r"^([A-Z][A-Za-z-]*):(?:[ \t]+(.*))?$")
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Fact:
15
+ """A plain ``Key: value`` line under an artifact's title."""
16
+
17
+ value: str
18
+ index: int
19
+
20
+
21
+ def require_title(doc: Document, problems: list[Problem]) -> str:
22
+ """The document's title; reports a problem when there is none."""
23
+ title = doc.title
24
+ if title is None or not title.title:
25
+ problems.append(
26
+ Problem(doc.path, 1, "missing-title", 'Start the file with a "# <title>" heading.')
27
+ )
28
+ return ""
29
+ return title.title
30
+
31
+
32
+ def parse_facts(
33
+ doc: Document, keys: Collection[str], problems: list[Problem], *, prose: bool
34
+ ) -> dict[str, Fact]:
35
+ """Read the fact lines between the title and the first section.
36
+
37
+ With ``prose`` false, any other text there is a problem.
38
+ """
39
+ facts: dict[str, Fact] = {}
40
+ start, end = doc.preamble
41
+ in_comment = False
42
+ for index in range(start, end):
43
+ line = doc.lines[index]
44
+ if in_comment or line.text.lstrip().startswith("<!--"):
45
+ in_comment = "-->" not in line.text
46
+ continue
47
+ if line.is_blank:
48
+ continue
49
+ match = _FACT.match(line.text)
50
+ if match and match.group(1) in keys:
51
+ key = match.group(1)
52
+ if key in facts:
53
+ problems.append(
54
+ Problem(
55
+ doc.path,
56
+ index + 1,
57
+ "duplicate-fact",
58
+ f'"{key}:" appears twice. Keep one line.',
59
+ )
60
+ )
61
+ else:
62
+ facts[key] = Fact((match.group(2) or "").strip(), index)
63
+ elif not prose:
64
+ allowed = ", ".join(f'"{key}:"' for key in sorted(keys)) or "nothing"
65
+ problems.append(
66
+ Problem(
67
+ doc.path,
68
+ index + 1,
69
+ "unexpected-text",
70
+ f"Only {allowed} may appear between the title and the first section. "
71
+ "Move this text into a section.",
72
+ )
73
+ )
74
+ return facts
75
+
76
+
77
+ def collect_sections(
78
+ doc: Document,
79
+ required: Sequence[str],
80
+ problems: list[Problem],
81
+ *,
82
+ optional: Sequence[str] = (),
83
+ strict: bool = False,
84
+ ) -> dict[str, Section]:
85
+ """Find the level-2 sections by name, ignoring case.
86
+
87
+ Reports missing and duplicate sections and, when ``strict``, unknown ones.
88
+ """
89
+ wanted = {name.casefold(): name for name in (*required, *optional)}
90
+ found: dict[str, Section] = {}
91
+ for section in doc.sections(2):
92
+ name = wanted.get(section.title.casefold())
93
+ if name is None:
94
+ if strict:
95
+ expected = ", ".join(f'"{known}"' for known in wanted.values())
96
+ problems.append(
97
+ Problem(
98
+ doc.path,
99
+ section.start + 1,
100
+ "unknown-section",
101
+ f'"{section.title}" is not a section of this file. '
102
+ f"Use {expected}, or remove it.",
103
+ )
104
+ )
105
+ elif name in found:
106
+ problems.append(
107
+ Problem(
108
+ doc.path,
109
+ section.start + 1,
110
+ "duplicate-section",
111
+ f'"## {name}" appears twice. Merge the two sections.',
112
+ )
113
+ )
114
+ else:
115
+ found[name] = section
116
+ problems.extend(
117
+ Problem(doc.path, 1, "missing-section", f'Add a "## {name}" section.')
118
+ for name in required
119
+ if name not in found
120
+ )
121
+ return found
122
+
123
+
124
+ def content(doc: Document, sections: dict[str, Section], name: str, problems: list[Problem]) -> str:
125
+ """A named section's text; an empty section is reported as a problem."""
126
+ section = sections.get(name)
127
+ if section is None:
128
+ return ""
129
+ text = doc.body(section)
130
+ if not text:
131
+ problems.append(
132
+ Problem(
133
+ doc.path,
134
+ section.start + 1,
135
+ "empty-section",
136
+ f'"## {name}" is empty. Write its content.',
137
+ )
138
+ )
139
+ return text
140
+
141
+
142
+ def split_names(value: str) -> tuple[str, ...]:
143
+ """Split a comma-separated list of names."""
144
+ return tuple(part.strip() for part in value.split(",") if part.strip())
@@ -0,0 +1,56 @@
1
+ """The pointer file a code repo may carry: which atlas holds its record, and where.
2
+
3
+ It sits at ``.waymark/atlas.toml`` in the code repo's top folder and holds the
4
+ atlas's name, an optional relative-path hint and the pinned wm version. A code
5
+ repo needs no Waymark files; the pointer is written only when asked for.
6
+ """
7
+
8
+ import json
9
+ import tomllib
10
+ from dataclasses import dataclass
11
+
12
+ POINTER_DIR = ".waymark"
13
+ POINTER_FILE = f"{POINTER_DIR}/atlas.toml"
14
+ _KEYS = frozenset({"atlas", "path", "wm_version"})
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Pointer:
19
+ """What a code repo's pointer file says."""
20
+
21
+ atlas: str
22
+ path_hint: str | None
23
+ wm_version: str | None
24
+
25
+
26
+ def parse_pointer(text: str) -> tuple[Pointer | None, str | None]:
27
+ """Read a pointer file. Returns the pointer, or why it can't be read."""
28
+ try:
29
+ data = tomllib.loads(text)
30
+ except tomllib.TOMLDecodeError as error:
31
+ return None, f"{POINTER_FILE} is not valid TOML: {error}."
32
+ unknown = sorted(set(data) - _KEYS)
33
+ if unknown:
34
+ return None, f'{POINTER_FILE} holds "{unknown[0]}", which is not one of its settings.'
35
+ values = {key: data.get(key) for key in _KEYS}
36
+ if not all(value is None or isinstance(value, str) for value in values.values()):
37
+ return None, f"{POINTER_FILE} holds a setting that is not a string."
38
+ atlas = (values["atlas"] or "").strip()
39
+ if not atlas:
40
+ return None, f'{POINTER_FILE} names no atlas. Set "atlas" to the atlas\'s name.'
41
+ hint = (values["path"] or "").strip() or None
42
+ version = (values["wm_version"] or "").strip() or None
43
+ return Pointer(atlas, hint, version), None
44
+
45
+
46
+ def render_pointer(pointer: Pointer) -> str:
47
+ """The pointer file's text."""
48
+ lines = [
49
+ "# This repository's record lives in a Waymark atlas. Written by wm atlas point.",
50
+ f"atlas = {json.dumps(pointer.atlas)}",
51
+ ]
52
+ if pointer.path_hint:
53
+ lines.append(f"path = {json.dumps(pointer.path_hint)}")
54
+ if pointer.wm_version:
55
+ lines.append(f"wm_version = {json.dumps(pointer.wm_version)}")
56
+ return "\n".join(lines) + "\n"
@@ -0,0 +1,20 @@
1
+ """Problems found while reading the record."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+ WHOLE_FILE = 0
6
+ """The line number of a problem that concerns a whole file or folder."""
7
+
8
+
9
+ @dataclass(frozen=True, order=True)
10
+ class Problem:
11
+ """One thing wrong in the record: where it is, what it is, and how to fix it.
12
+
13
+ ``path`` is relative to the record's root and uses forward slashes, so the
14
+ same files give the same problems on every platform. ``line`` is 1-based.
15
+ """
16
+
17
+ path: str
18
+ line: int
19
+ code: str
20
+ message: str
@@ -0,0 +1,118 @@
1
+ """Finding the project: the folder that holds the record.
2
+
3
+ From inside the repository or atlas that holds the record, it is found by
4
+ looking upward for the record's settings. From inside a code repo that an
5
+ atlas covers, it is found through the code repo's pointer file, or through
6
+ this machine's registry.
7
+ """
8
+
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+
12
+ from waymark.record.atlas import Found, contains, locate_atlas
13
+ from waymark.record.config import CONFIG_FILE, RECORD_DIR
14
+ from waymark.record.pointer import POINTER_FILE, parse_pointer
15
+ from waymark.record.registry import Registry, load_registry
16
+
17
+ __all__ = ["RECORD_DIR", "Project", "ProjectNotFoundError", "find_project"]
18
+
19
+
20
+ class ProjectNotFoundError(Exception):
21
+ """No record was found at or above the starting folder, nor through a code repo."""
22
+
23
+ def __init__(self, start: Path, reason: str | None = None) -> None:
24
+ advice = (
25
+ f'A project has a "{RECORD_DIR}/{CONFIG_FILE}" file at its top. '
26
+ "Change to the project's folder, or initialize one."
27
+ )
28
+ super().__init__(reason or f'No Waymark project found at or above "{start}". {advice}')
29
+ self.start = start
30
+ self.plain = reason or f"No Waymark project found here or above. {advice}"
31
+ """The same message without the starting folder, for output that holds no paths."""
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class Project:
36
+ """A project: the repository, or the atlas, whose top folder holds the record.
37
+
38
+ When it was found from inside one of an atlas's code repos, ``code_repo``
39
+ is that repo's top folder. ``notes`` are things worth telling the person
40
+ running the command, such as a hint that could be registered.
41
+ """
42
+
43
+ root: Path
44
+ code_repo: Path | None = None
45
+ notes: tuple[str, ...] = ()
46
+
47
+ @property
48
+ def record_root(self) -> Path:
49
+ return self.root / RECORD_DIR
50
+
51
+
52
+ def _upward(start: Path, relative: str) -> Path | None:
53
+ for folder in (start, *start.parents):
54
+ if (folder / relative).is_file():
55
+ return folder
56
+ return None
57
+
58
+
59
+ def _through_pointer(start: Path, folder: Path, registry: Registry) -> Project:
60
+ try:
61
+ text = (folder / POINTER_FILE).read_bytes().decode("utf-8")
62
+ except (OSError, UnicodeDecodeError) as error:
63
+ detail = getattr(error, "strerror", None) or "not valid UTF-8"
64
+ reason = f"This code repo's {POINTER_FILE} can't be read ({detail})."
65
+ raise ProjectNotFoundError(start, reason) from error
66
+ pointer, problem = parse_pointer(text)
67
+ if pointer is None:
68
+ raise ProjectNotFoundError(start, f"This code repo's pointer: {problem}")
69
+ location = locate_atlas(pointer.atlas, registry, folder, pointer.path_hint)
70
+ if location.folder is None:
71
+ raise ProjectNotFoundError(
72
+ start, f'This code repo points to the atlas "{pointer.atlas}". {location.detail}'
73
+ )
74
+ notes = (f"{location.detail} ({location.folder})",) if location.found is Found.HINT else ()
75
+ return Project(location.folder, folder, notes)
76
+
77
+
78
+ def _through_registry(start: Path, registry: Registry) -> Project | None:
79
+ matches = sorted(
80
+ (entry.name, repo_folder)
81
+ for entry in registry.atlases.values()
82
+ for repo_folder in entry.repos.values()
83
+ if contains(repo_folder, start)
84
+ )
85
+ atlases = sorted({name for name, _ in matches})
86
+ if len(atlases) > 1:
87
+ raise ProjectNotFoundError(
88
+ start,
89
+ f"This folder is a code repo of several atlases ({', '.join(atlases)}). Run wm "
90
+ 'from the atlas you mean, or give this repo a pointer with "wm atlas point <atlas>".',
91
+ )
92
+ if not matches:
93
+ return None
94
+ name, repo_folder = matches[0]
95
+ location = locate_atlas(name, registry)
96
+ if location.folder is None:
97
+ raise ProjectNotFoundError(start, location.detail)
98
+ return Project(location.folder, repo_folder)
99
+
100
+
101
+ def find_project(start: Path, registry: Registry | None = None) -> Project:
102
+ """Find the project that contains a folder, or the atlas a code repo belongs to.
103
+
104
+ The record sits in the same place in a repository and in an atlas, so both
105
+ are found the same way; the settings say which one it is.
106
+ """
107
+ origin = start.resolve()
108
+ found = _upward(origin, f"{RECORD_DIR}/{CONFIG_FILE}")
109
+ if found is not None:
110
+ return Project(found)
111
+ known = load_registry() if registry is None else registry
112
+ pointed = _upward(origin, POINTER_FILE)
113
+ if pointed is not None:
114
+ return _through_pointer(start, pointed, known)
115
+ project = _through_registry(origin, known)
116
+ if project is None:
117
+ raise ProjectNotFoundError(start)
118
+ return project