ticket-docket 1.0.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.
- docket/__init__.py +11 -0
- docket/cli/__init__.py +171 -0
- docket/cli/__main__.py +16 -0
- docket/cli/commands.py +428 -0
- docket/cli/grammar.py +376 -0
- docket/cli/output.py +134 -0
- docket/core/__init__.py +5 -0
- docket/core/atomic.py +62 -0
- docket/core/config.py +386 -0
- docket/core/deploy.py +288 -0
- docket/core/errors.py +122 -0
- docket/core/fields.py +166 -0
- docket/core/graph.py +418 -0
- docket/core/ids.py +215 -0
- docket/core/inputs.py +91 -0
- docket/core/lock.py +95 -0
- docket/core/mermaid.py +164 -0
- docket/core/store.py +534 -0
- docket/core/ticket.py +272 -0
- docket/core/validate.py +378 -0
- docket/py.typed +0 -0
- docket/server.py +330 -0
- docket/templates/CLAUDE.md +108 -0
- docket/templates/docket.toml +22 -0
- ticket_docket-1.0.0.dist-info/METADATA +226 -0
- ticket_docket-1.0.0.dist-info/RECORD +29 -0
- ticket_docket-1.0.0.dist-info/WHEEL +4 -0
- ticket_docket-1.0.0.dist-info/entry_points.txt +3 -0
- ticket_docket-1.0.0.dist-info/licenses/LICENSE +693 -0
docket/core/ids.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Docket Ids
|
|
3
|
+
|
|
4
|
+
Key parsing, id formatting, next-number allocation, and filename slug generation.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
# MARK: Imports
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
import unicodedata
|
|
11
|
+
from typing import Iterable, Optional
|
|
12
|
+
|
|
13
|
+
from docket.core.errors import InvalidIdError, InvalidKeyError
|
|
14
|
+
|
|
15
|
+
# MARK: Constants
|
|
16
|
+
|
|
17
|
+
# A key is uppercase alphanumeric and must start with a letter.
|
|
18
|
+
KEY_PATTERN: re.Pattern[str] = re.compile(r"^[A-Z][A-Z0-9]*$")
|
|
19
|
+
|
|
20
|
+
# A ticket id is a key, a hyphen, and a positive integer with no leading zeros.
|
|
21
|
+
ID_PATTERN: re.Pattern[str] = re.compile(r"^([A-Z][A-Z0-9]*)-([1-9][0-9]*)$")
|
|
22
|
+
|
|
23
|
+
# Every run of characters outside this set separates one slug token from the next.
|
|
24
|
+
SLUG_SEPARATOR_PATTERN: re.Pattern[str] = re.compile(r"[^A-Za-z0-9]+")
|
|
25
|
+
|
|
26
|
+
# The slug is capped so a filename stays comfortably inside every filesystem's limit.
|
|
27
|
+
SLUG_MAX_LENGTH: int = 48
|
|
28
|
+
|
|
29
|
+
# Used when a title contains nothing that survives normalization, for example a title of only emoji.
|
|
30
|
+
SLUG_FALLBACK: str = "untitled"
|
|
31
|
+
|
|
32
|
+
# MARK: Functions
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def isValidKey(key: str) -> bool:
|
|
36
|
+
"""
|
|
37
|
+
Report whether a key matches the required form.
|
|
38
|
+
|
|
39
|
+
key: The key to test.
|
|
40
|
+
|
|
41
|
+
Returns `True` when the key is well formed.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
return bool(KEY_PATTERN.match(key))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def requireValidKey(key: str) -> str:
|
|
48
|
+
"""
|
|
49
|
+
Return the key unchanged, raising when it is malformed.
|
|
50
|
+
|
|
51
|
+
key: The key to check.
|
|
52
|
+
|
|
53
|
+
Returns the same key.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
# Reject anything that is not uppercase alphanumeric starting with a letter.
|
|
57
|
+
if not isValidKey(key):
|
|
58
|
+
raise InvalidKeyError(f"Key '{key}' is malformed. A key must be uppercase alphanumeric and start with a letter, for example 'CORE'.")
|
|
59
|
+
|
|
60
|
+
return key
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def isValidId(ticketId: str) -> bool:
|
|
64
|
+
"""
|
|
65
|
+
Report whether a ticket id matches the required form.
|
|
66
|
+
|
|
67
|
+
This is the asking half of `parseId`, for a caller deciding what a token is rather than one that already knows.
|
|
68
|
+
|
|
69
|
+
ticketId: The id to test.
|
|
70
|
+
|
|
71
|
+
Returns `True` when the id is well formed.
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
return bool(ID_PATTERN.match(ticketId))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def parseId(ticketId: str) -> tuple[str, int]:
|
|
78
|
+
"""
|
|
79
|
+
Split a ticket id into its key and its number.
|
|
80
|
+
|
|
81
|
+
ticketId: The id to split, for example `CORE-14`.
|
|
82
|
+
|
|
83
|
+
Returns a `(key, number)` pair.
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
# Match the whole id so a trailing or leading fragment cannot slip through.
|
|
87
|
+
match: Optional[re.Match[str]] = ID_PATTERN.match(ticketId)
|
|
88
|
+
if match is None:
|
|
89
|
+
raise InvalidIdError(f"Id '{ticketId}' is malformed. An id must be a key, a hyphen, and a positive number, for example 'CORE-14'.")
|
|
90
|
+
|
|
91
|
+
return match.group(1), int(match.group(2))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def formatId(key: str, number: int) -> str:
|
|
95
|
+
"""
|
|
96
|
+
Build a ticket id from a key and a number.
|
|
97
|
+
|
|
98
|
+
key: The key the ticket belongs to.
|
|
99
|
+
number: The sequential number within that key.
|
|
100
|
+
|
|
101
|
+
Returns the formatted id.
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
# Validate both halves here so a malformed id can never be constructed.
|
|
105
|
+
requireValidKey(key)
|
|
106
|
+
if number < 1:
|
|
107
|
+
raise InvalidIdError(f"Number {number} is invalid. Ticket numbers start at 1.")
|
|
108
|
+
|
|
109
|
+
return f"{key}-{number}"
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def keyOf(ticketId: str) -> str:
|
|
113
|
+
"""
|
|
114
|
+
Extract the key from a ticket id.
|
|
115
|
+
|
|
116
|
+
ticketId: The id to read.
|
|
117
|
+
|
|
118
|
+
Returns the key portion.
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
return parseId(ticketId)[0]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def nextNumber(key: str, existingIds: Iterable[str]) -> int:
|
|
125
|
+
"""
|
|
126
|
+
Derive the next available number for a key by scanning existing ids.
|
|
127
|
+
|
|
128
|
+
The result is always one past the highest number seen, never the lowest unused gap, so a deleted ticket's number is not reused.
|
|
129
|
+
|
|
130
|
+
key: The key to allocate within.
|
|
131
|
+
existingIds: Every ticket id currently in the set, of any key.
|
|
132
|
+
|
|
133
|
+
Returns the next number to use.
|
|
134
|
+
"""
|
|
135
|
+
|
|
136
|
+
requireValidKey(key)
|
|
137
|
+
|
|
138
|
+
# Collect the numbers already taken under this key, ignoring ids belonging to other keys.
|
|
139
|
+
highest: int = 0
|
|
140
|
+
for existingId in existingIds:
|
|
141
|
+
match: Optional[re.Match[str]] = ID_PATTERN.match(existingId)
|
|
142
|
+
if match is None or match.group(1) != key:
|
|
143
|
+
continue
|
|
144
|
+
|
|
145
|
+
highest = max(highest, int(match.group(2)))
|
|
146
|
+
|
|
147
|
+
return highest + 1
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def nextId(key: str, existingIds: Iterable[str]) -> str:
|
|
151
|
+
"""
|
|
152
|
+
Derive the next available id for a key.
|
|
153
|
+
|
|
154
|
+
key: The key to allocate within.
|
|
155
|
+
existingIds: Every ticket id currently in the set.
|
|
156
|
+
|
|
157
|
+
Returns the formatted next id.
|
|
158
|
+
"""
|
|
159
|
+
|
|
160
|
+
return formatId(key, nextNumber(key, existingIds))
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def slugify(title: str) -> str:
|
|
164
|
+
"""
|
|
165
|
+
Convert a free-text title into a camelCase filename slug.
|
|
166
|
+
|
|
167
|
+
A title is untrusted input, so this works from an allowlist of characters rather than a blocklist.
|
|
168
|
+
Path separators, `..`, quotes, and control characters are discarded as a consequence of that rule rather than by explicit rejection.
|
|
169
|
+
|
|
170
|
+
title: The ticket title to convert.
|
|
171
|
+
|
|
172
|
+
Returns the slug, or `untitled` when nothing survives.
|
|
173
|
+
"""
|
|
174
|
+
|
|
175
|
+
# Fold accented characters onto their ASCII bases, then drop anything still outside ASCII.
|
|
176
|
+
normalized: str = unicodedata.normalize("NFKD", title)
|
|
177
|
+
asciiOnly: str = normalized.encode("ascii", "ignore").decode("ascii")
|
|
178
|
+
|
|
179
|
+
# Split on every run of non-alphanumeric characters, which is what makes traversal impossible by construction.
|
|
180
|
+
tokens: list[str] = [token for token in SLUG_SEPARATOR_PATTERN.split(asciiOnly) if token]
|
|
181
|
+
if not tokens:
|
|
182
|
+
return SLUG_FALLBACK
|
|
183
|
+
|
|
184
|
+
# Lowercase the first token whole, then capitalize each later token so an acronym like `HTTP` becomes `Http` rather than shouting.
|
|
185
|
+
parts: list[str] = [tokens[0].lower()]
|
|
186
|
+
parts.extend(token[0].upper() + token[1:].lower() for token in tokens[1:])
|
|
187
|
+
|
|
188
|
+
# Append tokens while they fit, so truncation lands on a word boundary wherever possible.
|
|
189
|
+
slug: str = ""
|
|
190
|
+
for part in parts:
|
|
191
|
+
if slug and len(slug) + len(part) > SLUG_MAX_LENGTH:
|
|
192
|
+
break
|
|
193
|
+
|
|
194
|
+
slug += part
|
|
195
|
+
|
|
196
|
+
# A single opening token longer than the cap has no boundary to break on, so cut it hard.
|
|
197
|
+
return slug[:SLUG_MAX_LENGTH]
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def buildFilename(ticketId: str, title: str) -> str:
|
|
201
|
+
"""
|
|
202
|
+
Build the on-disk filename for a ticket.
|
|
203
|
+
|
|
204
|
+
The id prefix is what makes the filename unique, which is why a slug collision between two titles is harmless and why a slug matching a Windows reserved device name is harmless too.
|
|
205
|
+
|
|
206
|
+
ticketId: The ticket's id, which is validated here.
|
|
207
|
+
title: The title the slug derives from.
|
|
208
|
+
|
|
209
|
+
Returns the filename, including the `.md` extension.
|
|
210
|
+
"""
|
|
211
|
+
|
|
212
|
+
# Validate the id rather than trusting it, since this result is used as a path.
|
|
213
|
+
parseId(ticketId)
|
|
214
|
+
|
|
215
|
+
return f"{ticketId}_{slugify(title)}.md"
|
docket/core/inputs.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Docket Inputs
|
|
3
|
+
|
|
4
|
+
Checks on values supplied directly by a caller, rather than read back from a file.
|
|
5
|
+
|
|
6
|
+
A value reaching the core came either from a command line or from an MCP tool call, and neither shell may be trusted to have checked it. POSIX shells pass an empty string through to the process, so an empty title or an empty destination arrives intact and would otherwise be written. PowerShell discards it before the process starts, which produces its own usage error and never reaches here.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
# MARK: Imports
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from docket.core.errors import EmptyValueError, OutputPathError
|
|
15
|
+
|
|
16
|
+
# MARK: Functions
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def requireText(value: str, name: str) -> str:
|
|
20
|
+
"""
|
|
21
|
+
Reject a value that carries no text.
|
|
22
|
+
|
|
23
|
+
Whitespace counts as empty, since a title of spaces is as unusable as a title of nothing and would leave the same blank cell in every listing.
|
|
24
|
+
|
|
25
|
+
value: The value to check.
|
|
26
|
+
name: What to name in the error message, for example `title`.
|
|
27
|
+
|
|
28
|
+
Returns the value unchanged, with its surrounding whitespace intact.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
if not value.strip():
|
|
32
|
+
raise EmptyValueError(f"The {name} cannot be empty.")
|
|
33
|
+
|
|
34
|
+
return value
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def requireWritableFile(path: str, name: str) -> Path:
|
|
38
|
+
"""
|
|
39
|
+
Reject a destination that cannot be written as a file.
|
|
40
|
+
|
|
41
|
+
The checks that can be made without touching the disk are made here, so a caller learns the destination is unusable before any work is done for it. A filesystem may still refuse the write afterwards for a reason no check can predict, which is why `writeFile` exists to catch that too.
|
|
42
|
+
|
|
43
|
+
path: The destination as the caller supplied it.
|
|
44
|
+
name: What to name in the error message, for example `--out path`.
|
|
45
|
+
|
|
46
|
+
Returns the destination as a `Path`.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
requireText(path, name)
|
|
50
|
+
|
|
51
|
+
resolved: Path = Path(path)
|
|
52
|
+
|
|
53
|
+
# A directory can never be opened as a file, and this is the case an empty path used to reach by resolving to the working directory.
|
|
54
|
+
if resolved.is_dir():
|
|
55
|
+
raise OutputPathError(f"The {name} '{path}' is a directory, not a file.")
|
|
56
|
+
|
|
57
|
+
# An existing file the process cannot open for writing fails no matter what its parent allows.
|
|
58
|
+
if resolved.exists() and not os.access(resolved, os.W_OK):
|
|
59
|
+
raise OutputPathError(f"The {name} '{path}' is not writable.")
|
|
60
|
+
|
|
61
|
+
# An existing parent that refuses new entries fails before the directory tree is touched. A parent that does not exist yet is not an error, since the write creates it.
|
|
62
|
+
parent: Path = resolved.parent
|
|
63
|
+
if parent.is_dir() and not os.access(parent, os.W_OK):
|
|
64
|
+
raise OutputPathError(f"The {name} '{path}' is inside a directory that is not writable.")
|
|
65
|
+
|
|
66
|
+
return resolved
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def writeFile(path: Path, text: str, name: str) -> Path:
|
|
70
|
+
"""
|
|
71
|
+
Write text to a destination, translating whatever the filesystem refuses into a docket error.
|
|
72
|
+
|
|
73
|
+
Every check `requireWritableFile` can make is a prediction, and a prediction can be wrong. A refusal escaping here as a bare `OSError` would reach the user as a traceback rather than as a message, so it is translated instead.
|
|
74
|
+
|
|
75
|
+
path: The destination, already checked.
|
|
76
|
+
text: The content to write.
|
|
77
|
+
name: What to name in the error message, for example `--out path`.
|
|
78
|
+
|
|
79
|
+
Returns the path written.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
try:
|
|
83
|
+
# Create the tree only once the destination itself has been accepted, so a rejected path leaves no directories behind.
|
|
84
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
85
|
+
|
|
86
|
+
# Write LF explicitly so the file does not churn on a Windows checkout.
|
|
87
|
+
path.write_text(text, encoding="utf-8", newline="\n")
|
|
88
|
+
except OSError as error:
|
|
89
|
+
raise OutputPathError(f"Could not write the {name} '{path}': {error.strerror or error}.") from error
|
|
90
|
+
|
|
91
|
+
return path
|
docket/core/lock.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Docket Lock
|
|
3
|
+
|
|
4
|
+
Serializing reads and writes across separate processes sharing one repository.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
# MARK: Imports
|
|
8
|
+
|
|
9
|
+
from contextlib import contextmanager
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Iterator
|
|
12
|
+
|
|
13
|
+
from filelock import ReadWriteLock, Timeout
|
|
14
|
+
|
|
15
|
+
from docket.core.errors import LockTimeoutError
|
|
16
|
+
|
|
17
|
+
# MARK: Constants
|
|
18
|
+
|
|
19
|
+
# The lock file, kept beside `.docket.toml` because one lock covers both the tickets and the configuration.
|
|
20
|
+
LOCK_FILENAME: str = ".docket.lock"
|
|
21
|
+
|
|
22
|
+
# MARK: Functions
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def lockPath(repoRoot: Path) -> Path:
|
|
26
|
+
"""
|
|
27
|
+
Resolve where a repository's lock file belongs.
|
|
28
|
+
|
|
29
|
+
repoRoot: The directory holding `.docket.toml`.
|
|
30
|
+
|
|
31
|
+
Returns the absolute path of the lock file.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
# Resolve the path, since the lock is shared per resolved path and two spellings of one directory must not produce two locks.
|
|
35
|
+
return (repoRoot / LOCK_FILENAME).resolve()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@contextmanager
|
|
39
|
+
def sharedLock(repoRoot: Path, timeout: float) -> Iterator[None]:
|
|
40
|
+
"""
|
|
41
|
+
Hold the repository's read lock for the duration of a block.
|
|
42
|
+
|
|
43
|
+
Any number of processes may read at once, and none of them may read while a writer holds the lock.
|
|
44
|
+
This is what closes the window where a reader catches `setStatus` between writing the new file and removing the old one, and reports a duplicate id that never really existed.
|
|
45
|
+
|
|
46
|
+
repoRoot: The directory holding `.docket.toml`.
|
|
47
|
+
timeout: How long to wait for a writer to finish, in seconds.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
with _held(repoRoot, timeout, writing=False):
|
|
51
|
+
yield
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@contextmanager
|
|
55
|
+
def exclusiveLock(repoRoot: Path, timeout: float) -> Iterator[None]:
|
|
56
|
+
"""
|
|
57
|
+
Hold the repository's write lock for the duration of a block.
|
|
58
|
+
|
|
59
|
+
One process writes at a time and no process reads while it does, so a read followed by a write back is indivisible from any other process's point of view.
|
|
60
|
+
The whole read-modify-write span belongs inside the block, not just the write, because holding it for the write alone would still let two processes derive their changes from the same starting state.
|
|
61
|
+
|
|
62
|
+
repoRoot: The directory holding `.docket.toml`.
|
|
63
|
+
timeout: How long to wait for the current holder to finish, in seconds.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
with _held(repoRoot, timeout, writing=True):
|
|
67
|
+
yield
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# MARK: Private Functions
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@contextmanager
|
|
74
|
+
def _held(repoRoot: Path, timeout: float, writing: bool) -> Iterator[None]:
|
|
75
|
+
"""
|
|
76
|
+
Hold one side of the repository lock, translating a timeout into a docket error.
|
|
77
|
+
|
|
78
|
+
`filelock` raises its own `Timeout`, which no caller of `docket.core` should have to know about, so it is converted here into the error every other failure in this package already uses.
|
|
79
|
+
|
|
80
|
+
repoRoot: The directory holding `.docket.toml`.
|
|
81
|
+
timeout: How long to wait, in seconds.
|
|
82
|
+
writing: Whether to take the exclusive side rather than the shared one.
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
path: Path = lockPath(repoRoot)
|
|
86
|
+
|
|
87
|
+
# The lock instance is shared per resolved path, so the timeout is passed at acquisition rather than construction, where a later caller's value would be ignored.
|
|
88
|
+
lock: ReadWriteLock = ReadWriteLock(path)
|
|
89
|
+
acquire = lock.write_lock if writing else lock.read_lock
|
|
90
|
+
|
|
91
|
+
try:
|
|
92
|
+
with acquire(timeout=timeout):
|
|
93
|
+
yield
|
|
94
|
+
except Timeout as error:
|
|
95
|
+
raise LockTimeoutError(f"Another docket process has been {'writing to' if writing else 'locking'} {repoRoot} for longer than {timeout} seconds. Nothing was changed. Retry the call.") from error
|
docket/core/mermaid.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Docket Mermaid
|
|
3
|
+
|
|
4
|
+
Renders a resolved graph to mermaid source.
|
|
5
|
+
|
|
6
|
+
This is one renderer over `graph.ResolvedGraph` and holds no traversal logic of its own, so a second renderer costs only another module like this one.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
# MARK: Imports
|
|
10
|
+
|
|
11
|
+
from docket.core.graph import Edge, GraphNode, ResolvedGraph
|
|
12
|
+
from docket.core.ticket import STATUSES
|
|
13
|
+
|
|
14
|
+
# MARK: Constants
|
|
15
|
+
|
|
16
|
+
# Top-down reads naturally for dependencies, since an arrow then points from what must happen first to what follows.
|
|
17
|
+
GRAPH_HEADER: str = "graph TD"
|
|
18
|
+
|
|
19
|
+
# Two spaces per level, matching the shape the format is documented in.
|
|
20
|
+
INDENT: str = " "
|
|
21
|
+
|
|
22
|
+
# Fills chosen to stay legible on both a light and a dark backdrop, since mermaid renders inside whatever theme the viewer has.
|
|
23
|
+
STATUS_STYLES: dict[str, str] = {
|
|
24
|
+
"todo": "fill:#495057,color:#fff",
|
|
25
|
+
"wip": "fill:#9a6700,color:#fff",
|
|
26
|
+
"done": "fill:#2d6a4f,color:#fff",
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
# The class marking a node borrowed from another key, dashed so the boundary reads at a glance.
|
|
30
|
+
EXTERNAL_CLASS: str = "external"
|
|
31
|
+
EXTERNAL_STYLE: str = "fill:#212529,color:#adb5bd,stroke-dasharray: 3 3"
|
|
32
|
+
|
|
33
|
+
# Mermaid parses these inside a node label, so they are replaced with the HTML entities it understands.
|
|
34
|
+
LABEL_REPLACEMENTS: tuple[tuple[str, str], ...] = (
|
|
35
|
+
("&", "&"),
|
|
36
|
+
('"', "#quot;"),
|
|
37
|
+
("<", "<"),
|
|
38
|
+
(">", ">"),
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
# MARK: Functions
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def renderGraph(graph: ResolvedGraph) -> str:
|
|
45
|
+
"""
|
|
46
|
+
Render a resolved graph to mermaid source.
|
|
47
|
+
|
|
48
|
+
graph: The graph to render.
|
|
49
|
+
|
|
50
|
+
Returns the mermaid source, with a trailing newline and no code fence.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
lines: list[str] = [GRAPH_HEADER]
|
|
54
|
+
|
|
55
|
+
# One subgraph per key, so related work reads as a block.
|
|
56
|
+
for key in graph.keys():
|
|
57
|
+
lines.append(f"{INDENT}subgraph {key}")
|
|
58
|
+
for node in graph.nodesForKey(key):
|
|
59
|
+
lines.append(f"{INDENT * 2}{renderNode(node)}")
|
|
60
|
+
|
|
61
|
+
lines.append(f"{INDENT}end")
|
|
62
|
+
|
|
63
|
+
# Edges sit outside the subgraphs, since an edge may cross between them.
|
|
64
|
+
for edge in graph.edges:
|
|
65
|
+
lines.append(f"{INDENT}{renderEdge(edge)}")
|
|
66
|
+
|
|
67
|
+
lines.extend(renderStyles(graph))
|
|
68
|
+
|
|
69
|
+
return "\n".join(lines) + "\n"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def renderNode(node: GraphNode) -> str:
|
|
73
|
+
"""
|
|
74
|
+
Render one node declaration.
|
|
75
|
+
|
|
76
|
+
Priority is written into the label rather than carried by the class, so it survives in a renderer that ignores `classDef` entirely.
|
|
77
|
+
|
|
78
|
+
node: The node to render.
|
|
79
|
+
|
|
80
|
+
Returns the declaration line.
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
return f'{sanitizeId(node.id)}["{escapeLabel(node.id)} {escapeLabel(node.title)}<br/>p{node.priority} {escapeLabel(node.status)}"]'
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def renderEdge(edge: Edge) -> str:
|
|
87
|
+
"""
|
|
88
|
+
Render one edge.
|
|
89
|
+
|
|
90
|
+
edge: The edge to render.
|
|
91
|
+
|
|
92
|
+
Returns the edge line, pointing from dependency to dependent.
|
|
93
|
+
"""
|
|
94
|
+
|
|
95
|
+
return f"{sanitizeId(edge.fromId)} --> {sanitizeId(edge.toId)}"
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def renderStyles(graph: ResolvedGraph) -> list[str]:
|
|
99
|
+
"""
|
|
100
|
+
Render the class definitions and the class assignments for a graph.
|
|
101
|
+
|
|
102
|
+
graph: The graph to style.
|
|
103
|
+
|
|
104
|
+
Returns the style lines, empty when there is nothing to style.
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
if not graph.nodes:
|
|
108
|
+
return []
|
|
109
|
+
|
|
110
|
+
lines: list[str] = [f"{INDENT}classDef {status} {STATUS_STYLES[status]}" for status in STATUSES]
|
|
111
|
+
|
|
112
|
+
# Group nodes by the class they take, with external winning over status so the boundary stays visible.
|
|
113
|
+
grouped: dict[str, list[str]] = {}
|
|
114
|
+
for node in graph.nodes.values():
|
|
115
|
+
className: str = EXTERNAL_CLASS if node.isExternal else node.status
|
|
116
|
+
|
|
117
|
+
# A status that arrived by hand-editing has no class, and is left unstyled rather than inventing one.
|
|
118
|
+
if className != EXTERNAL_CLASS and className not in STATUS_STYLES:
|
|
119
|
+
continue
|
|
120
|
+
|
|
121
|
+
grouped.setdefault(className, []).append(sanitizeId(node.id))
|
|
122
|
+
|
|
123
|
+
# Only declare the external class when something actually uses it.
|
|
124
|
+
if EXTERNAL_CLASS in grouped:
|
|
125
|
+
lines.append(f"{INDENT}classDef {EXTERNAL_CLASS} {EXTERNAL_STYLE}")
|
|
126
|
+
|
|
127
|
+
for className in sorted(grouped):
|
|
128
|
+
lines.append(f"{INDENT}class {','.join(sorted(grouped[className]))} {className}")
|
|
129
|
+
|
|
130
|
+
return lines
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def sanitizeId(ticketId: str) -> str:
|
|
134
|
+
"""
|
|
135
|
+
Convert a ticket id into a mermaid node identifier.
|
|
136
|
+
|
|
137
|
+
Mermaid dislikes a hyphen in an identifier, so it becomes an underscore. The hyphenated id stays in the label, which is what the reader sees.
|
|
138
|
+
|
|
139
|
+
ticketId: The id to convert.
|
|
140
|
+
|
|
141
|
+
Returns the identifier.
|
|
142
|
+
"""
|
|
143
|
+
|
|
144
|
+
return ticketId.replace("-", "_")
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def escapeLabel(text: str) -> str:
|
|
148
|
+
"""
|
|
149
|
+
Escape text for use inside a quoted mermaid label.
|
|
150
|
+
|
|
151
|
+
A title is free text, so it may hold a quote or an angle bracket that would otherwise end the label early or be read as markup.
|
|
152
|
+
|
|
153
|
+
text: The text to escape.
|
|
154
|
+
|
|
155
|
+
Returns the escaped text.
|
|
156
|
+
"""
|
|
157
|
+
|
|
158
|
+
escaped: str = text
|
|
159
|
+
|
|
160
|
+
# The ampersand is replaced first, so the entities introduced afterwards are not themselves re-escaped.
|
|
161
|
+
for character, replacement in LABEL_REPLACEMENTS:
|
|
162
|
+
escaped = escaped.replace(character, replacement)
|
|
163
|
+
|
|
164
|
+
return escaped
|