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/cli/grammar.py
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Docket CLI Grammar
|
|
3
|
+
|
|
4
|
+
The vocabulary the CLI accepts, and the exit codes it answers with.
|
|
5
|
+
|
|
6
|
+
This is the shape of the interface and nothing behind it. The parser lives here, along with the small parsers for the values individual arguments carry.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
# MARK: Imports
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
from typing import Optional
|
|
13
|
+
|
|
14
|
+
from rich_argparse import RichHelpFormatter
|
|
15
|
+
|
|
16
|
+
from docket import __version__
|
|
17
|
+
from docket.core.config import Config, discoverConfig
|
|
18
|
+
from docket.core.errors import ConflictingArgumentsError, DocketError, InvalidArgumentError, InvalidIdError
|
|
19
|
+
from docket.core.ids import isValidId, isValidKey
|
|
20
|
+
from docket.core.ticket import STATUSES
|
|
21
|
+
|
|
22
|
+
# MARK: Constants
|
|
23
|
+
|
|
24
|
+
# The program name used in help output and error messages.
|
|
25
|
+
PROGRAM_NAME: str = "docket"
|
|
26
|
+
|
|
27
|
+
# Exit codes, distinguishing a set that failed validation from a command that could not run at all.
|
|
28
|
+
EXIT_OK: int = 0
|
|
29
|
+
EXIT_INVALID: int = 1
|
|
30
|
+
EXIT_USAGE: int = 2
|
|
31
|
+
|
|
32
|
+
# The name the one-ticket branch is registered under. It is a placeholder rather than a word, because what reaches it is a ticket id and never this string. Registering it anyway is what lets `argparse` describe the branch in help and name it in an error, instead of it being an undocumented trick.
|
|
33
|
+
TICKET_COMMAND: str = "<ID>"
|
|
34
|
+
|
|
35
|
+
# What a bare positional token can be read as. Every class is decided by the token's own shape, and no token can fall into two, since an id carries a hyphen and a number, a key is uppercase, a status is one of a fixed lowercase set, and a priority is digits.
|
|
36
|
+
TOKEN_ID: str = "id"
|
|
37
|
+
TOKEN_KEY: str = "key"
|
|
38
|
+
TOKEN_STATUS: str = "status"
|
|
39
|
+
TOKEN_PRIORITY: str = "priority"
|
|
40
|
+
|
|
41
|
+
# The word that clears a comma-separated list argument. An id can never collide with it, since every id is an uppercase key followed by a hyphen and a number.
|
|
42
|
+
CLEAR_SENTINEL: str = "none"
|
|
43
|
+
|
|
44
|
+
# How the graph destination is named when a message has to talk about it.
|
|
45
|
+
OUT_ARGUMENT: str = "--out path"
|
|
46
|
+
|
|
47
|
+
# MARK: Functions
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def describeKeys(config: Optional[Config]) -> str:
|
|
51
|
+
"""
|
|
52
|
+
Describe the keys an argument accepts, for appending to its help text.
|
|
53
|
+
|
|
54
|
+
The registry is per-repository, so the options can only be named once a configuration has been found. Without one the description stays general rather than guessing.
|
|
55
|
+
|
|
56
|
+
config: The configuration holding the registry, or `None` when none was found.
|
|
57
|
+
|
|
58
|
+
Returns the sentence to append.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
if config is None:
|
|
62
|
+
return "Must be registered."
|
|
63
|
+
|
|
64
|
+
registered: str = ", ".join(sorted(config.registeredKeys))
|
|
65
|
+
|
|
66
|
+
# A registry with nothing in it is a real state after a fresh deploy, so name it rather than printing an empty list.
|
|
67
|
+
return f"One of: {registered}." if registered else "None are registered yet. Add one with 'docket key add'."
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def describePriorities(config: Optional[Config]) -> str:
|
|
71
|
+
"""
|
|
72
|
+
Describe the priorities an argument accepts, for appending to its help text.
|
|
73
|
+
|
|
74
|
+
The band runs from 0 through the configured `maxPriority`, so like the key registry it can only be listed once a configuration has been found.
|
|
75
|
+
|
|
76
|
+
config: The configuration holding the band, or `None` when none was found.
|
|
77
|
+
|
|
78
|
+
Returns the sentence to append.
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
if config is None:
|
|
82
|
+
return "0 is most urgent."
|
|
83
|
+
|
|
84
|
+
return f"One of: {', '.join(str(priority) for priority in range(config.maxPriority + 1))}. 0 is most urgent."
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def tryDiscoverConfig() -> Optional[Config]:
|
|
88
|
+
"""
|
|
89
|
+
Load the configuration governing the current directory, without insisting that one exists.
|
|
90
|
+
|
|
91
|
+
Only the help text depends on this, and every command that truly needs a configuration discovers it again through `dispatch`, so a missing one must not stop the parser from being built. That is what keeps `--help`, `--version`, and `deploy` working outside a repository.
|
|
92
|
+
|
|
93
|
+
Returns the loaded `Config`, or `None` when none could be loaded.
|
|
94
|
+
"""
|
|
95
|
+
|
|
96
|
+
try:
|
|
97
|
+
return discoverConfig()
|
|
98
|
+
except DocketError:
|
|
99
|
+
return None
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def classifyToken(token: str) -> Optional[str]:
|
|
103
|
+
"""
|
|
104
|
+
Decide what a bare positional token names, from its shape alone.
|
|
105
|
+
|
|
106
|
+
This is the whole of the rule that lets `docket list todo CORE 1` and `docket graph CORE-14` be written without a flag between them. The four classes cannot overlap, so no token is ever ambiguous and no ordering between the checks changes an answer.
|
|
107
|
+
|
|
108
|
+
token: The token to read.
|
|
109
|
+
|
|
110
|
+
Returns one of the `TOKEN_` names, or `None` when the token is none of them.
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
if isValidId(token):
|
|
114
|
+
return TOKEN_ID
|
|
115
|
+
|
|
116
|
+
if isValidKey(token):
|
|
117
|
+
return TOKEN_KEY
|
|
118
|
+
|
|
119
|
+
if token in STATUSES:
|
|
120
|
+
return TOKEN_STATUS
|
|
121
|
+
|
|
122
|
+
# A priority is a plain number, so a signed or decimal one is deliberately not a priority.
|
|
123
|
+
if token.isdigit():
|
|
124
|
+
return TOKEN_PRIORITY
|
|
125
|
+
|
|
126
|
+
return None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def rewriteIdFirst(argv: list[str]) -> list[str]:
|
|
130
|
+
"""
|
|
131
|
+
Rewrite an invocation that opens with a ticket id into the branch that handles one.
|
|
132
|
+
|
|
133
|
+
`docket CORE-14 done` is the shape a person types, and `argparse` cannot express "a subcommand, or else an id". It does not have to, because the two are distinguishable before parsing begins: every command name is lowercase and every id is an uppercase key followed by a hyphen and a number. So naming the branch is all this does, and the parser is left to do the rest, including the help and every error.
|
|
134
|
+
|
|
135
|
+
argv: The raw argument list.
|
|
136
|
+
|
|
137
|
+
Returns the list to parse, unchanged when it does not open with an id.
|
|
138
|
+
"""
|
|
139
|
+
|
|
140
|
+
if not argv or not isValidId(argv[0]):
|
|
141
|
+
return argv
|
|
142
|
+
|
|
143
|
+
return [TICKET_COMMAND, *argv]
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def resolveListFilters(tokens: list[str], status: Optional[str], key: Optional[str], priorityMax: Optional[int]) -> tuple[Optional[str], Optional[str], Optional[int]]:
|
|
147
|
+
"""
|
|
148
|
+
Resolve `list`'s filters from its bare tokens and its flags together.
|
|
149
|
+
|
|
150
|
+
A token says which filter it is by its own shape, so `docket list todo CORE 1` needs no flags at all. The flags remain for scripts and for anyone who would rather be explicit, and naming one filter twice is refused rather than quietly resolved in whichever direction the code happens to read.
|
|
151
|
+
|
|
152
|
+
tokens: The bare filter tokens, in any order.
|
|
153
|
+
status: The status named by `--status`, or `None`.
|
|
154
|
+
key: The key named by `--key`, or `None`.
|
|
155
|
+
priorityMax: The ceiling named by `--priority-max`, or `None`.
|
|
156
|
+
|
|
157
|
+
Returns the resolved `(status, key, priorityMax)` triple.
|
|
158
|
+
"""
|
|
159
|
+
|
|
160
|
+
# Held as text so one loop can fill any of the three, then converted back on the way out.
|
|
161
|
+
resolved: dict[str, Optional[str]] = {
|
|
162
|
+
TOKEN_STATUS: status,
|
|
163
|
+
TOKEN_KEY: key,
|
|
164
|
+
TOKEN_PRIORITY: None if priorityMax is None else str(priorityMax),
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
for token in tokens:
|
|
168
|
+
kind: Optional[str] = classifyToken(token)
|
|
169
|
+
|
|
170
|
+
# An id is a whole other command rather than a filter, so name that command instead of calling the token unreadable.
|
|
171
|
+
if kind == TOKEN_ID:
|
|
172
|
+
raise InvalidArgumentError(f"'{token}' is a ticket id, which does not filter a list. Show it with '{PROGRAM_NAME} {token}'.")
|
|
173
|
+
|
|
174
|
+
if kind is None:
|
|
175
|
+
raise InvalidArgumentError(f"Cannot read '{token}' as a filter. Expected a status ({', '.join(STATUSES)}), a key, or a priority number.")
|
|
176
|
+
|
|
177
|
+
if resolved[kind] is not None:
|
|
178
|
+
raise ConflictingArgumentsError(f"The {kind} filter was given twice, the second time as '{token}'. Pass it once.")
|
|
179
|
+
|
|
180
|
+
resolved[kind] = token
|
|
181
|
+
|
|
182
|
+
ceiling: Optional[str] = resolved[TOKEN_PRIORITY]
|
|
183
|
+
|
|
184
|
+
return resolved[TOKEN_STATUS], resolved[TOKEN_KEY], None if ceiling is None else int(ceiling)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def resolveGraphScope(scope: Optional[str], ticketId: Optional[str], key: Optional[str]) -> tuple[Optional[str], Optional[str]]:
|
|
188
|
+
"""
|
|
189
|
+
Resolve the graph's scope from its bare token and its flags together.
|
|
190
|
+
|
|
191
|
+
An id and a key are told apart by shape, which is what makes `docket graph CORE-14` and `docket graph GEN` both unambiguous. The flags stay for the explicit form, and combining the two spellings is refused, since `argparse` can enforce that `--id` and `--key` exclude each other but cannot reach across to a positional.
|
|
192
|
+
|
|
193
|
+
scope: The bare scope token, or `None`.
|
|
194
|
+
ticketId: The id named by `--id`, or `None`.
|
|
195
|
+
key: The key named by `--key`, or `None`.
|
|
196
|
+
|
|
197
|
+
Returns the resolved `(id, key)` pair, at most one of which is set.
|
|
198
|
+
"""
|
|
199
|
+
|
|
200
|
+
if scope is None:
|
|
201
|
+
return ticketId, key
|
|
202
|
+
|
|
203
|
+
if ticketId is not None or key is not None:
|
|
204
|
+
raise ConflictingArgumentsError(f"'{scope}' already scopes the graph, so it cannot be combined with -i/--id or -k/--key.")
|
|
205
|
+
|
|
206
|
+
kind: Optional[str] = classifyToken(scope)
|
|
207
|
+
|
|
208
|
+
if kind == TOKEN_ID:
|
|
209
|
+
return scope, None
|
|
210
|
+
|
|
211
|
+
if kind == TOKEN_KEY:
|
|
212
|
+
return None, scope
|
|
213
|
+
|
|
214
|
+
raise InvalidArgumentError(f"Cannot read '{scope}' as a scope. Expected a ticket id, for example 'CORE-14', or a key.")
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def buildParser(config: Optional[Config] = None) -> argparse.ArgumentParser:
|
|
218
|
+
"""
|
|
219
|
+
Build the top-level argument parser and every subcommand parser.
|
|
220
|
+
|
|
221
|
+
config: The configuration whose keys and priority band the help text names, or `None` to describe both in general terms.
|
|
222
|
+
|
|
223
|
+
Returns the configured `argparse.ArgumentParser`.
|
|
224
|
+
"""
|
|
225
|
+
|
|
226
|
+
parser: argparse.ArgumentParser = argparse.ArgumentParser(
|
|
227
|
+
prog=PROGRAM_NAME,
|
|
228
|
+
description="A per-repo ticketing system that is plain markdown for humans and structured MCP for agents.",
|
|
229
|
+
formatter_class=RichHelpFormatter,
|
|
230
|
+
)
|
|
231
|
+
parser.add_argument("-V", "--version", action="version", version=f"{PROGRAM_NAME} {__version__}")
|
|
232
|
+
|
|
233
|
+
commands = parser.add_subparsers(dest="command", metavar="COMMAND")
|
|
234
|
+
|
|
235
|
+
# Name the discrete options once, since every argument that takes a key or a priority describes the same set.
|
|
236
|
+
keyOptions: str = describeKeys(config)
|
|
237
|
+
priorityOptions: str = describePriorities(config)
|
|
238
|
+
|
|
239
|
+
buildTicketParser(commands, priorityOptions)
|
|
240
|
+
|
|
241
|
+
# Creating a ticket, which allocates the id and freezes the filename. The key and the title are positional because both are required, and a required flag is a flag that should have been an argument.
|
|
242
|
+
newParser: argparse.ArgumentParser = commands.add_parser("new", help="Create a ticket.", formatter_class=RichHelpFormatter)
|
|
243
|
+
newParser.add_argument("key", metavar="KEY", help=f"The key to mint under. {keyOptions}")
|
|
244
|
+
newParser.add_argument("title", metavar="TITLE", help="The ticket title. The filename slug derives from this once, here.")
|
|
245
|
+
newParser.add_argument("-r", "--requires", help="Comma-separated ids this ticket depends on.")
|
|
246
|
+
newParser.add_argument("-p", "--priority", type=int, help=f"Priority, defaulting to the configured defaultPriority. {priorityOptions}")
|
|
247
|
+
newParser.add_argument("-b", "--body", help="Prose for the body, placed under a heading built from the title.")
|
|
248
|
+
|
|
249
|
+
listParser: argparse.ArgumentParser = commands.add_parser("list", help="List ticket summaries.", formatter_class=RichHelpFormatter)
|
|
250
|
+
listParser.add_argument("filters", nargs="*", metavar="FILTER", help=f"Filters in any order, each read from its own shape: a status ({', '.join(STATUSES)}), a key, or a priority ceiling. The flags below are the same three, named explicitly.")
|
|
251
|
+
listParser.add_argument("-s", "--status", choices=STATUSES, help="Keep only tickets with this status.")
|
|
252
|
+
listParser.add_argument("-k", "--key", help=f"Keep only tickets carrying this key. {keyOptions}")
|
|
253
|
+
listParser.add_argument("-m", "--priority-max", type=int, dest="priorityMax", help=f"Keep only tickets at or below this priority number. {priorityOptions}")
|
|
254
|
+
|
|
255
|
+
graphParser: argparse.ArgumentParser = commands.add_parser("graph", help="Render the dependency graph as mermaid source.", formatter_class=RichHelpFormatter)
|
|
256
|
+
graphParser.add_argument("scope", nargs="?", metavar="SCOPE", help="What to scope to, read from its own shape: a ticket id, or a key. The flags below are the same two, named explicitly.")
|
|
257
|
+
graphScope = graphParser.add_mutually_exclusive_group()
|
|
258
|
+
graphScope.add_argument("-i", "--id", help="Scope to one ticket's ancestors and descendants.")
|
|
259
|
+
graphScope.add_argument("-k", "--key", help=f"Scope to one key, plus its immediate cross-key neighbors. {keyOptions}")
|
|
260
|
+
graphParser.add_argument("-o", "--out", help="Write to a file rather than to stdout.")
|
|
261
|
+
|
|
262
|
+
keyParser: argparse.ArgumentParser = commands.add_parser("key", help="Inspect and manage the key registry.", formatter_class=RichHelpFormatter)
|
|
263
|
+
keyCommands = keyParser.add_subparsers(dest="keyCommand", metavar="SUBCOMMAND")
|
|
264
|
+
|
|
265
|
+
keyCommands.add_parser("list", help="List the registered keys.", formatter_class=RichHelpFormatter)
|
|
266
|
+
|
|
267
|
+
keyAddParser: argparse.ArgumentParser = keyCommands.add_parser("add", help="Register a new key.", formatter_class=RichHelpFormatter)
|
|
268
|
+
keyAddParser.add_argument("key", help="The key to add.")
|
|
269
|
+
keyAddParser.add_argument("description", help="What the key groups.")
|
|
270
|
+
keyAddParser.add_argument("-r", "--rationale", help="Why the key was added, written as a comment above it.")
|
|
271
|
+
|
|
272
|
+
keyRemoveParser: argparse.ArgumentParser = keyCommands.add_parser("remove", help="Remove a key no ticket uses.", formatter_class=RichHelpFormatter)
|
|
273
|
+
keyRemoveParser.add_argument("key", help=f"The key to remove. {keyOptions}")
|
|
274
|
+
|
|
275
|
+
commands.add_parser("validate", help="Run every integrity rule.", formatter_class=RichHelpFormatter)
|
|
276
|
+
|
|
277
|
+
deployParser: argparse.ArgumentParser = commands.add_parser("deploy", help="Install docket into a repository.", formatter_class=RichHelpFormatter)
|
|
278
|
+
deployParser.add_argument("path", help="The repository root to deploy into.")
|
|
279
|
+
|
|
280
|
+
upgradeParser: argparse.ArgumentParser = commands.add_parser("upgrade", help="Refresh the deployed templates in a repository.", formatter_class=RichHelpFormatter)
|
|
281
|
+
upgradeParser.add_argument("path", help="The repository root to upgrade.")
|
|
282
|
+
|
|
283
|
+
return parser
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def buildTicketParser(commands: argparse._SubParsersAction, priorityOptions: str) -> argparse.ArgumentParser:
|
|
287
|
+
"""
|
|
288
|
+
Build the branch that works with one ticket, named by its id.
|
|
289
|
+
|
|
290
|
+
`prog` is set to the program name alone, and the id is added before the subcommands, so `argparse` derives every child's usage line as `docket ID <command>`. That is exactly what was typed, rather than the placeholder the branch is registered under.
|
|
291
|
+
|
|
292
|
+
commands: The top-level subparser action to register into.
|
|
293
|
+
priorityOptions: The sentence describing the priority band, already built.
|
|
294
|
+
|
|
295
|
+
Returns the branch parser.
|
|
296
|
+
"""
|
|
297
|
+
|
|
298
|
+
ticketParser: argparse.ArgumentParser = commands.add_parser(
|
|
299
|
+
TICKET_COMMAND,
|
|
300
|
+
prog=PROGRAM_NAME,
|
|
301
|
+
help="Work with one ticket. A bare id shows it, a status word sets it.",
|
|
302
|
+
description="Work with the ticket named by ID. Status is the truth and the directory follows it, so setting a status may move the file.",
|
|
303
|
+
formatter_class=RichHelpFormatter,
|
|
304
|
+
)
|
|
305
|
+
ticketParser.add_argument("id", metavar="ID", help="The ticket id, for example CORE-14.")
|
|
306
|
+
|
|
307
|
+
# Not required, so a bare id parses and falls through to showing the ticket.
|
|
308
|
+
ticketCommands = ticketParser.add_subparsers(dest="ticketCommand", metavar="COMMAND")
|
|
309
|
+
|
|
310
|
+
ticketCommands.add_parser("show", help="Show the ticket with its resolved dependency context. This is what a bare id does.", formatter_class=RichHelpFormatter)
|
|
311
|
+
ticketCommands.add_parser("status", help="Print the ticket's status and nothing else, for a pipe to read.", formatter_class=RichHelpFormatter)
|
|
312
|
+
|
|
313
|
+
# One parser per status is what makes 'docket CORE-14 done' work. It also puts the whole vocabulary into the error when a command is misspelled, which a single `choices` list on a value argument could not do.
|
|
314
|
+
for status in STATUSES:
|
|
315
|
+
ticketCommands.add_parser(status, help=f"Set the status to {status}.", formatter_class=RichHelpFormatter)
|
|
316
|
+
|
|
317
|
+
setParser: argparse.ArgumentParser = ticketCommands.add_parser("set", help="Change the ticket's title, priority, or dependencies.", formatter_class=RichHelpFormatter)
|
|
318
|
+
setParser.add_argument("-t", "--title", help="A new title. The filename does not follow it, since filenames are frozen at creation.")
|
|
319
|
+
setParser.add_argument("-p", "--priority", type=int, help=f"A new priority. {priorityOptions}")
|
|
320
|
+
setParser.add_argument("-r", "--requires", help=f"A replacement comma-separated dependency list. Pass '{CLEAR_SENTINEL}' to clear it.")
|
|
321
|
+
setParser.add_argument("-ra", "--requires-add", dest="requiresAdd", help="Comma-separated ids to append to the existing dependency list, leaving the rest of it alone.")
|
|
322
|
+
setParser.add_argument("-rr", "--requires-remove", dest="requiresRemove", help="Comma-separated ids to drop from the existing dependency list, leaving the rest of it alone.")
|
|
323
|
+
|
|
324
|
+
# How much of the call was typed is what it means, the same way a status reads with no value and writes with one.
|
|
325
|
+
metaParser: argparse.ArgumentParser = ticketCommands.add_parser("meta", help="Inspect and manage the ticket's metadata map.", formatter_class=RichHelpFormatter)
|
|
326
|
+
metaParser.add_argument("key", nargs="?", metavar="KEY", help="The metadata key. Namespace it, for example 'video', so it cannot collide with another tool's key. Omit it to show the whole map.")
|
|
327
|
+
metaParser.add_argument("value", nargs="?", metavar="VALUE", help="The value to store. Omit it to print the key's value and nothing else.")
|
|
328
|
+
metaParser.add_argument("-c", "--clear", action="store_true", help="Remove the key instead of setting it.")
|
|
329
|
+
|
|
330
|
+
return ticketParser
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def parseIdList(value: Optional[str]) -> Optional[list[str]]:
|
|
334
|
+
"""
|
|
335
|
+
Split a comma-separated id list.
|
|
336
|
+
|
|
337
|
+
Both `none` and an empty string yield an empty list rather than `None`, which is how `set --requires` clears a ticket's dependencies. The sentinel exists because PowerShell discards an empty-string argument before the process ever sees it, leaving the documented empty-string form unreachable on Windows.
|
|
338
|
+
|
|
339
|
+
value: The raw argument value.
|
|
340
|
+
|
|
341
|
+
Returns the ids, or `None` when the argument was absent.
|
|
342
|
+
"""
|
|
343
|
+
|
|
344
|
+
if value is None:
|
|
345
|
+
return None
|
|
346
|
+
|
|
347
|
+
entries: list[str] = [entry.strip() for entry in value.split(",") if entry.strip()]
|
|
348
|
+
|
|
349
|
+
# The sentinel clears the whole list, so mixing it with real ids asks for two contradictory things at once.
|
|
350
|
+
if any(entry.lower() == CLEAR_SENTINEL for entry in entries):
|
|
351
|
+
if len(entries) > 1:
|
|
352
|
+
raise InvalidIdError(f"'{CLEAR_SENTINEL}' clears the whole list, so it cannot be combined with an id. Pass either '{CLEAR_SENTINEL}' alone or only ids.")
|
|
353
|
+
|
|
354
|
+
return []
|
|
355
|
+
|
|
356
|
+
return entries
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def parseEditIdList(value: Optional[str], flag: str) -> Optional[list[str]]:
|
|
360
|
+
"""
|
|
361
|
+
Split a comma-separated id list for an argument that edits a list rather than replacing one.
|
|
362
|
+
|
|
363
|
+
Clearing is what `--requires` is for, so an empty result here means the caller named an edit and then named nothing to do, which is a usage error rather than a silent no-op.
|
|
364
|
+
|
|
365
|
+
value: The raw argument value.
|
|
366
|
+
flag: The flag the value came from, named in the error.
|
|
367
|
+
|
|
368
|
+
Returns the ids, or `None` when the argument was absent.
|
|
369
|
+
"""
|
|
370
|
+
|
|
371
|
+
entries: Optional[list[str]] = parseIdList(value)
|
|
372
|
+
|
|
373
|
+
if entries is not None and not entries:
|
|
374
|
+
raise InvalidIdError(f"'{flag}' needs at least one id. Use '--requires {CLEAR_SENTINEL}' to clear the list instead.")
|
|
375
|
+
|
|
376
|
+
return entries
|
docket/cli/output.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Docket CLI Output
|
|
3
|
+
|
|
4
|
+
Everything the CLI prints, and the styling decisions behind it.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
# MARK: Imports
|
|
8
|
+
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Optional
|
|
12
|
+
|
|
13
|
+
from rich.console import Console
|
|
14
|
+
from rich.table import Table
|
|
15
|
+
from rich.text import Text
|
|
16
|
+
|
|
17
|
+
# MARK: Constants
|
|
18
|
+
|
|
19
|
+
# Styles for the status column, matching the intent of the mermaid classes without depending on them.
|
|
20
|
+
STATUS_STYLES: dict[str, str] = {"todo": "dim", "wip": "yellow", "done": "green"}
|
|
21
|
+
|
|
22
|
+
# MARK: Classes
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Output:
|
|
26
|
+
"""
|
|
27
|
+
Everything the CLI prints.
|
|
28
|
+
|
|
29
|
+
Human-facing output goes through `rich`. Machine-readable output does not, because a pipe must receive bare text with no wrapping, highlighting, or escape sequences in it.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
# MARK: Initializer
|
|
33
|
+
|
|
34
|
+
def __init__(self) -> None:
|
|
35
|
+
"""
|
|
36
|
+
Build the consoles.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
self.console: Console = Console()
|
|
40
|
+
self.errorConsole: Console = Console(stderr=True)
|
|
41
|
+
|
|
42
|
+
# MARK: Functions
|
|
43
|
+
|
|
44
|
+
def print(self, renderable: object) -> None:
|
|
45
|
+
"""
|
|
46
|
+
Print human-facing output.
|
|
47
|
+
|
|
48
|
+
renderable: Anything `rich` can render.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
self.console.print(renderable)
|
|
52
|
+
|
|
53
|
+
def raw(self, text: str) -> None:
|
|
54
|
+
"""
|
|
55
|
+
Write machine-readable output with no styling applied.
|
|
56
|
+
|
|
57
|
+
Mermaid source goes through here, so redirecting it to a file or a pipe yields exactly the source and nothing else.
|
|
58
|
+
|
|
59
|
+
text: The text to write.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
sys.stdout.write(text)
|
|
63
|
+
|
|
64
|
+
def warn(self, message: str) -> None:
|
|
65
|
+
"""
|
|
66
|
+
Report a non-fatal warning.
|
|
67
|
+
|
|
68
|
+
message: The warning text.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
self.errorConsole.print(Text(f"warning: {message}", style="yellow"))
|
|
72
|
+
|
|
73
|
+
def error(self, message: str) -> None:
|
|
74
|
+
"""
|
|
75
|
+
Report a failure.
|
|
76
|
+
|
|
77
|
+
message: The error text.
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
self.errorConsole.print(Text(f"error: {message}", style="bold red"))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# MARK: Functions
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def buildContextTable(heading: str, entries: list[dict[str, object]]) -> Table:
|
|
87
|
+
"""
|
|
88
|
+
Build the table showing one direction of a ticket's resolved dependencies.
|
|
89
|
+
|
|
90
|
+
heading: What to title the table.
|
|
91
|
+
entries: The resolved records.
|
|
92
|
+
|
|
93
|
+
Returns the table.
|
|
94
|
+
"""
|
|
95
|
+
|
|
96
|
+
table: Table = Table(title=heading, title_justify="left", box=None, pad_edge=False, title_style="bold")
|
|
97
|
+
table.add_column("ID")
|
|
98
|
+
table.add_column("STATUS")
|
|
99
|
+
table.add_column("TITLE")
|
|
100
|
+
|
|
101
|
+
if not entries:
|
|
102
|
+
table.add_row("[dim]none[/dim]", "", "")
|
|
103
|
+
|
|
104
|
+
return table
|
|
105
|
+
|
|
106
|
+
for entry in entries:
|
|
107
|
+
# A dependency naming a missing id is shown rather than hidden, since a broken link the reader cannot see is worse than one they can.
|
|
108
|
+
if not entry["exists"]:
|
|
109
|
+
table.add_row(str(entry["id"]), Text("missing", style="bold red"), "[dim]no such ticket[/dim]")
|
|
110
|
+
continue
|
|
111
|
+
|
|
112
|
+
status: str = str(entry["status"])
|
|
113
|
+
table.add_row(str(entry["id"]), Text(status, style=STATUS_STYLES.get(status, "white")), str(entry["title"]))
|
|
114
|
+
|
|
115
|
+
return table
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def relativeToRoot(path: Optional[Path], root: Path) -> str:
|
|
119
|
+
"""
|
|
120
|
+
Describe a path relative to a repository root, so output stays readable in a narrow terminal.
|
|
121
|
+
|
|
122
|
+
path: The path to describe.
|
|
123
|
+
root: The directory to describe it against.
|
|
124
|
+
|
|
125
|
+
Returns the relative path, falling back to the absolute one when it lies outside the root.
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
if path is None:
|
|
129
|
+
return "an unwritten file"
|
|
130
|
+
|
|
131
|
+
try:
|
|
132
|
+
return str(path.relative_to(root))
|
|
133
|
+
except ValueError:
|
|
134
|
+
return str(path)
|
docket/core/__init__.py
ADDED
docket/core/atomic.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Docket Atomic
|
|
3
|
+
|
|
4
|
+
Replacing a file's contents in one indivisible step, so no reader ever sees a partial write.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
# MARK: Imports
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import tempfile
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import IO, Any
|
|
13
|
+
|
|
14
|
+
# MARK: Constants
|
|
15
|
+
|
|
16
|
+
# Marks a temporary file as this module's, so a leftover from a killed process is recognizable rather than mysterious.
|
|
17
|
+
TEMP_PREFIX: str = ".docket-"
|
|
18
|
+
TEMP_SUFFIX: str = ".tmp"
|
|
19
|
+
|
|
20
|
+
# MARK: Functions
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def writeTextAtomic(path: Path, text: str) -> None:
|
|
24
|
+
"""
|
|
25
|
+
Replace a file's contents in one step, leaving no window where the file is half written.
|
|
26
|
+
|
|
27
|
+
The text goes to a temporary file in the destination's own directory and is then moved into place with `os.replace`, which is atomic on both POSIX and Windows.
|
|
28
|
+
Writing the temporary file beside the destination rather than in the system temporary directory is what keeps the move on one filesystem, since a cross-device move is a copy and a copy is not atomic.
|
|
29
|
+
|
|
30
|
+
Newlines are written as LF explicitly, matching what every direct write in this repository already did, so a checkout on Windows does not churn the file.
|
|
31
|
+
|
|
32
|
+
path: The file to replace. Its parent directory must already exist.
|
|
33
|
+
text: The full contents to write.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
# Hold the temporary path outside the try, so cleanup can find it even when the write itself is what failed.
|
|
37
|
+
temporaryPath: Path
|
|
38
|
+
|
|
39
|
+
handle: IO[Any] = tempfile.NamedTemporaryFile(
|
|
40
|
+
mode="w",
|
|
41
|
+
encoding="utf-8",
|
|
42
|
+
newline="\n",
|
|
43
|
+
dir=path.parent,
|
|
44
|
+
prefix=TEMP_PREFIX,
|
|
45
|
+
suffix=TEMP_SUFFIX,
|
|
46
|
+
delete=False,
|
|
47
|
+
)
|
|
48
|
+
temporaryPath = Path(handle.name)
|
|
49
|
+
|
|
50
|
+
try:
|
|
51
|
+
# Flush through the library buffer and then through the operating system's, so the move promotes fully written bytes rather than a queued write.
|
|
52
|
+
with handle:
|
|
53
|
+
handle.write(text)
|
|
54
|
+
handle.flush()
|
|
55
|
+
os.fsync(handle.fileno())
|
|
56
|
+
|
|
57
|
+
os.replace(temporaryPath, path)
|
|
58
|
+
except BaseException:
|
|
59
|
+
# A failed write must not leave its temporary file behind, since the destination is untouched and the leftover would only confuse the next reader of the directory.
|
|
60
|
+
temporaryPath.unlink(missing_ok=True)
|
|
61
|
+
|
|
62
|
+
raise
|