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/core/config.py ADDED
@@ -0,0 +1,386 @@
1
+ """
2
+ Docket Config
3
+
4
+ Reading and writing `.docket.toml`, including the key registry.
5
+ """
6
+
7
+ # MARK: Imports
8
+
9
+ from pathlib import Path
10
+ from typing import Any, ContextManager, Optional
11
+
12
+ import tomlkit
13
+ from tomlkit import TOMLDocument
14
+ from tomlkit.items import Comment, Table
15
+
16
+ from docket.core.atomic import writeTextAtomic
17
+ from docket.core.errors import ConfigError, ConfigNotFoundError, InvalidKeyError, UnknownKeyError
18
+ from docket.core.fields import readFloat, readInt, readString
19
+ from docket.core.ids import requireValidKey
20
+ from docket.core.lock import exclusiveLock, sharedLock
21
+ from docket.core.inputs import requireText
22
+
23
+ # MARK: Constants
24
+
25
+ # The filename looked for when walking up from a starting directory.
26
+ CONFIG_FILENAME: str = ".docket.toml"
27
+
28
+ # The table holding registered keys.
29
+ KEYS_TABLE: str = "keys"
30
+
31
+ # Field defaults, applied when a configuration omits an optional field.
32
+ DEFAULT_ROOT: str = "docs/tickets"
33
+ DEFAULT_TODO_DIR: str = "todo"
34
+ DEFAULT_DONE_DIR: str = "done"
35
+ DEFAULT_PRIORITY: int = 2
36
+ DEFAULT_MAX_PRIORITY: int = 4
37
+ DEFAULT_LOCK_TIMEOUT: float = 5.0
38
+
39
+ # MARK: Classes
40
+
41
+
42
+ class Config:
43
+ """
44
+ A loaded `.docket.toml`, backed by the `tomlkit` document it was parsed from.
45
+
46
+ The document is retained rather than discarded because writes must preserve the comments, spacing, and key order a human wrote around their key descriptions.
47
+ """
48
+
49
+ # MARK: Initializer
50
+
51
+ def __init__(self, path: Path, document: TOMLDocument) -> None:
52
+ """
53
+ Wrap a parsed document.
54
+
55
+ path: The path the document was read from, and the path `save` writes back to.
56
+ document: The parsed `tomlkit` document, retained for round-tripping.
57
+ """
58
+
59
+ self.path: Path = path
60
+ self.document: TOMLDocument = document
61
+
62
+ # Name the file in field errors, since a user may have several repositories open.
63
+ source: str = f"Configuration {path}"
64
+
65
+ # Read the scalar fields once, since they are plain values with no round-trip concerns.
66
+ self.root: str = readString(document, "root", ConfigError, source, DEFAULT_ROOT)
67
+ self.todoDir: str = readString(document, "todoDir", ConfigError, source, DEFAULT_TODO_DIR)
68
+ self.doneDir: str = readString(document, "doneDir", ConfigError, source, DEFAULT_DONE_DIR)
69
+ self.defaultPriority: int = readInt(document, "defaultPriority", ConfigError, source, DEFAULT_PRIORITY)
70
+ self.maxPriority: int = readInt(document, "maxPriority", ConfigError, source, DEFAULT_MAX_PRIORITY)
71
+ self.lockTimeout: float = readFloat(document, "lockTimeout", ConfigError, source, DEFAULT_LOCK_TIMEOUT)
72
+
73
+ # A default outside the allowed band would make every created ticket invalid, so catch it at load.
74
+ if not 0 <= self.defaultPriority <= self.maxPriority:
75
+ raise ConfigError(f"defaultPriority {self.defaultPriority} is outside 0 through maxPriority {self.maxPriority} in {self.path}.")
76
+
77
+ # A timeout of zero or less would fail every operation that ever met contention, so it is never what the writer meant.
78
+ if self.lockTimeout <= 0:
79
+ raise ConfigError(f"lockTimeout {self.lockTimeout} in {self.path} must be greater than 0. It is a wait in seconds.")
80
+
81
+ # MARK: Properties
82
+
83
+ @property
84
+ def repoRoot(self) -> Path:
85
+ """
86
+ The directory holding the configuration file, which is the repository root.
87
+ """
88
+
89
+ return self.path.parent
90
+
91
+ @property
92
+ def rootPath(self) -> Path:
93
+ """
94
+ The absolute path of the ticket root directory.
95
+ """
96
+
97
+ return self.repoRoot / self.root
98
+
99
+ @property
100
+ def todoPath(self) -> Path:
101
+ """
102
+ The absolute path of the directory holding `todo` and `wip` tickets.
103
+ """
104
+
105
+ return self.rootPath / self.todoDir
106
+
107
+ @property
108
+ def donePath(self) -> Path:
109
+ """
110
+ The absolute path of the directory holding `done` tickets.
111
+ """
112
+
113
+ return self.rootPath / self.doneDir
114
+
115
+ @property
116
+ def registeredKeys(self) -> dict[str, str]:
117
+ """
118
+ Registered keys mapped to their descriptions.
119
+ """
120
+
121
+ # Skip any nested sub-table, so a configuration left over from an older layout is ignored rather than read as a key.
122
+ return {name: str(value) for name, value in self.__keysTable().items() if not isinstance(value, dict)}
123
+
124
+ # MARK: Private Functions
125
+
126
+ def __reload(self) -> None:
127
+ """
128
+ Re-read the document from disk, discarding the copy held in memory.
129
+
130
+ Only the document is refreshed. The scalar fields are left as they were read at load, since the callers of this are editing `[keys]` and a configuration that changed its own root mid-operation would be a stranger problem than the one this solves.
131
+ """
132
+
133
+ self.document = _parseDocument(self.path)
134
+
135
+ def __keysTable(self) -> Table:
136
+ """
137
+ Return the `[keys]` table, creating it in the document when absent.
138
+
139
+ Returns the table.
140
+ """
141
+
142
+ if KEYS_TABLE not in self.document:
143
+ self.document[KEYS_TABLE] = tomlkit.table()
144
+
145
+ table: Any = self.document[KEYS_TABLE]
146
+ if not isinstance(table, Table):
147
+ raise ConfigError(f"Section '[{KEYS_TABLE}]' in {self.path} must be a table.")
148
+
149
+ return table
150
+
151
+ def __dropFromKeysTable(self, key: str) -> None:
152
+ """
153
+ Remove a key from `[keys]` along with the rationale comment sitting immediately above it, so the reasoning does not outlive what it explained.
154
+
155
+ A comment a human wrote elsewhere in the table is untouched, since only the run directly above the key is considered part of it.
156
+ The table is rebuilt rather than edited in place, because deleting a comment line from the document's body directly would leave `tomlkit`'s internal index pointing at the wrong entries.
157
+
158
+ key: The key to drop.
159
+ """
160
+
161
+ body: list[Any] = self.__keysTable().value.body
162
+
163
+ # Find the key's own entry, which is the anchor the comment run is measured back from.
164
+ index: int = -1
165
+ for position, (name, _) in enumerate(body):
166
+ if name is not None and name.key == key:
167
+ index = position
168
+ break
169
+
170
+ if index < 0:
171
+ return
172
+
173
+ # Walk backwards over the comment lines directly above it, stopping at the first entry that is anything else.
174
+ start: int = index
175
+ while start > 0:
176
+ name, item = body[start - 1]
177
+ if name is not None or not isinstance(item, Comment):
178
+ break
179
+
180
+ start -= 1
181
+
182
+ # Copy everything else across in order, so the surviving keys keep their positions and their own comments.
183
+ rebuilt: Table = tomlkit.table()
184
+ for position, (name, item) in enumerate(body):
185
+ if start <= position <= index:
186
+ continue
187
+
188
+ if name is None:
189
+ rebuilt.add(item)
190
+ continue
191
+
192
+ rebuilt.add(name, item)
193
+
194
+ self.document[KEYS_TABLE] = rebuilt
195
+
196
+ # MARK: Functions
197
+
198
+ def sharedLock(self) -> ContextManager[None]:
199
+ """
200
+ Hold this repository's read lock, waiting no longer than the configured `lockTimeout`.
201
+
202
+ Returns the context manager to hold for the duration of the read.
203
+ """
204
+
205
+ return sharedLock(self.repoRoot, self.lockTimeout)
206
+
207
+ def exclusiveLock(self) -> ContextManager[None]:
208
+ """
209
+ Hold this repository's write lock, waiting no longer than the configured `lockTimeout`.
210
+
211
+ Returns the context manager to hold for the duration of the read-modify-write.
212
+ """
213
+
214
+ return exclusiveLock(self.repoRoot, self.lockTimeout)
215
+
216
+ def isRegisteredKey(self, key: str) -> bool:
217
+ """
218
+ Report whether a key has been approved.
219
+
220
+ key: The key to test.
221
+
222
+ Returns `True` when the key is registered.
223
+ """
224
+
225
+ return key in self.registeredKeys
226
+
227
+ def requireKnownKey(self, key: str) -> str:
228
+ """
229
+ Return the key unchanged, raising when it is not usable on a ticket.
230
+
231
+ The message points at `add_key`, since that is the recovery path an agent has.
232
+
233
+ key: The key to check.
234
+
235
+ Returns the same key.
236
+ """
237
+
238
+ requireValidKey(key)
239
+
240
+ if not self.isRegisteredKey(key):
241
+ known: str = ", ".join(sorted(self.registeredKeys)) or "none"
242
+ raise UnknownKeyError(f"Key '{key}' is not registered. Known keys: {known}. Ask the user whether to add a new one, then call add_key.")
243
+
244
+ return key
245
+
246
+ def addKey(self, key: str, description: str, rationale: Optional[str] = None) -> str:
247
+ """
248
+ Register a key so tickets may be created under it.
249
+
250
+ key: The key to register.
251
+ description: What the key groups, shown alongside the other keys.
252
+ rationale: Why the key was added, written as a comment above it so the reasoning survives in the file.
253
+
254
+ Returns the same key.
255
+ """
256
+
257
+ requireValidKey(key)
258
+
259
+ # The description is the only thing telling a later reader what the key groups, so an empty one defeats the point of registering it.
260
+ requireText(description, "key description")
261
+
262
+ with self.exclusiveLock():
263
+ # The document may have been parsed long before this call, so re-read it inside the lock. Adding to a stale copy and writing the whole file back would drop whatever another process registered in the meantime, which is the exact loss the lock exists to prevent.
264
+ self.__reload()
265
+
266
+ # A key that already exists is not an addition, it is a mistake worth naming.
267
+ if self.isRegisteredKey(key):
268
+ raise InvalidKeyError(f"Key '{key}' is already registered.")
269
+
270
+ table: Table = self.__keysTable()
271
+
272
+ # Write the rationale first, so it lands on the line above the key rather than beside it.
273
+ if rationale:
274
+ table.add(tomlkit.comment(rationale))
275
+
276
+ table[key] = description
277
+ self.save()
278
+
279
+ return key
280
+
281
+ def removeKey(self, key: str, usedBy: Optional[list[str]] = None) -> None:
282
+ """
283
+ Remove a registered key.
284
+
285
+ Removing a key that tickets already carry would strand those tickets with an unknown key, so the caller passes the ids it found and this refuses loudly.
286
+
287
+ key: The key to remove.
288
+ usedBy: Ids of tickets currently carrying the key, if any.
289
+ """
290
+
291
+ # Refuse while tickets depend on the key, and name them so the user can act.
292
+ if usedBy:
293
+ raise InvalidKeyError(f"Key '{key}' cannot be removed because {len(usedBy)} ticket(s) use it: {', '.join(sorted(usedBy))}.")
294
+
295
+ with self.exclusiveLock():
296
+ # Re-read inside the lock for the same reason as `addKey`, since this also rewrites the whole file.
297
+ self.__reload()
298
+
299
+ if not self.isRegisteredKey(key):
300
+ raise UnknownKeyError(f"Key '{key}' is not registered, so there is nothing to remove.")
301
+
302
+ # Take the rationale comment with it, since a comment explaining a key that no longer exists only misleads.
303
+ self.__dropFromKeysTable(key)
304
+
305
+ self.save()
306
+
307
+ def save(self) -> None:
308
+ """
309
+ Write the document back to disk, preserving comments, spacing, and key order.
310
+ """
311
+
312
+ # Replace the file in one step, so a concurrent reader sees either the old configuration or the new one and never a truncated file.
313
+ writeTextAtomic(self.path, tomlkit.dumps(self.document))
314
+
315
+
316
+ # MARK: Functions
317
+
318
+
319
+ def findConfigPath(startDir: Optional[Path] = None) -> Path:
320
+ """
321
+ Locate `.docket.toml` by walking up from a starting directory.
322
+
323
+ The walk stops at the git root, so a parent repository's configuration is never picked up by a nested one.
324
+
325
+ startDir: The directory to start from, defaulting to the current working directory.
326
+
327
+ Returns the path to the configuration file.
328
+ """
329
+
330
+ current: Path = (startDir if startDir is not None else Path.cwd()).resolve()
331
+
332
+ # Walk upward, checking each directory before deciding whether the walk may continue past it.
333
+ searched: list[str] = []
334
+ for directory in [current, *current.parents]:
335
+ candidate: Path = directory / CONFIG_FILENAME
336
+ if candidate.is_file():
337
+ return candidate
338
+
339
+ searched.append(str(directory))
340
+
341
+ # A `.git` entry marks the repository boundary. It may be a file rather than a directory in a worktree or submodule, so test existence rather than type.
342
+ if (directory / ".git").exists():
343
+ break
344
+
345
+ raise ConfigNotFoundError(f"No {CONFIG_FILENAME} found. Searched: {', '.join(searched)}. Run 'docket deploy .' at the repository root to create one.")
346
+
347
+
348
+ def loadConfig(configPath: Path) -> Config:
349
+ """
350
+ Parse a configuration file.
351
+
352
+ configPath: The path to read.
353
+
354
+ Returns the loaded `Config`.
355
+ """
356
+
357
+ return Config(path=configPath, document=_parseDocument(configPath))
358
+
359
+
360
+ def _parseDocument(configPath: Path) -> TOMLDocument:
361
+ """
362
+ Read and parse a configuration file into a round-trippable document.
363
+
364
+ configPath: The path to read.
365
+
366
+ Returns the parsed document.
367
+ """
368
+
369
+ try:
370
+ return tomlkit.parse(configPath.read_text(encoding="utf-8"))
371
+ except OSError as error:
372
+ raise ConfigError(f"Could not read {configPath}: {error}") from error
373
+ except Exception as error:
374
+ raise ConfigError(f"Could not parse {configPath}: {error}") from error
375
+
376
+
377
+ def discoverConfig(startDir: Optional[Path] = None) -> Config:
378
+ """
379
+ Find and load the configuration governing a directory.
380
+
381
+ startDir: The directory to start the walk from, defaulting to the current working directory.
382
+
383
+ Returns the loaded `Config`.
384
+ """
385
+
386
+ return loadConfig(findConfigPath(startDir))
docket/core/deploy.py ADDED
@@ -0,0 +1,288 @@
1
+ """
2
+ Docket Deploy
3
+
4
+ Installing docket's data and configuration into a consumer repository.
5
+
6
+ The consumer receives ticket directories, a `CLAUDE.md`, a `.docket.toml`, one entry in `.mcp.json`, and one entry in `.gitignore`. It never receives the tool's source.
7
+ """
8
+
9
+ # MARK: Imports
10
+
11
+ import json
12
+ from dataclasses import dataclass, field
13
+ from importlib.resources import files
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from docket.core.atomic import writeTextAtomic
18
+ from docket.core.config import CONFIG_FILENAME, Config, loadConfig
19
+ from docket.core.errors import DeployError
20
+ from docket.core.lock import LOCK_FILENAME
21
+
22
+ # MARK: Constants
23
+
24
+ # The template files shipped inside the package.
25
+ TEMPLATE_CLAUDE: str = "CLAUDE.md"
26
+ TEMPLATE_CONFIG: str = "docket.toml"
27
+
28
+ # What the consumer repository receives.
29
+ CLAUDE_FILENAME: str = "CLAUDE.md"
30
+ MCP_FILENAME: str = ".mcp.json"
31
+ GITIGNORE_FILENAME: str = ".gitignore"
32
+
33
+ # The lock file is machine state, so it is ignored rather than committed. The trailing wildcard covers the journal the lock's own storage may write beside it.
34
+ LOCK_IGNORE_ENTRY: str = f"{LOCK_FILENAME}*"
35
+ LOCK_IGNORE_COMMENT: str = "# Docket's cross-process lock. Machine state, never committed."
36
+
37
+ # The key docket claims inside `.mcp.json`, and the console script it points at.
38
+ MCP_SERVERS_KEY: str = "mcpServers"
39
+ MCP_SERVER_NAME: str = "docket"
40
+ MCP_COMMAND: str = "docket-mcp"
41
+
42
+ # MARK: Classes
43
+
44
+
45
+ @dataclass
46
+ class DeployReport:
47
+ """
48
+ What a deploy or upgrade actually did.
49
+
50
+ Deploy is idempotent, so the caller needs to be told which steps changed something and which were already satisfied.
51
+ """
52
+
53
+ # MARK: Properties
54
+
55
+ created: list[Path] = field(default_factory=list)
56
+ updated: list[Path] = field(default_factory=list)
57
+ skipped: list[Path] = field(default_factory=list)
58
+
59
+ # MARK: Functions
60
+
61
+ def record(self, path: Path, existed: bool) -> None:
62
+ """
63
+ Note that a path was written.
64
+
65
+ path: The path written.
66
+ existed: Whether the file was already there.
67
+ """
68
+
69
+ (self.updated if existed else self.created).append(path)
70
+
71
+ def toDict(self) -> dict[str, list[str]]:
72
+ """
73
+ Build the serializable form.
74
+
75
+ Returns the report as plain data.
76
+ """
77
+
78
+ return {
79
+ "created": [str(path) for path in self.created],
80
+ "updated": [str(path) for path in self.updated],
81
+ "skipped": [str(path) for path in self.skipped],
82
+ }
83
+
84
+
85
+ # MARK: Functions
86
+
87
+
88
+ def deploy(target: Path) -> DeployReport:
89
+ """
90
+ Install docket into a consumer repository.
91
+
92
+ This is idempotent. Missing pieces are created and templates are refreshed, but an existing `.docket.toml` is never rewritten, because it holds the key registry a human has curated.
93
+
94
+ target: The repository root to deploy into.
95
+
96
+ Returns what was done.
97
+ """
98
+
99
+ root: Path = _requireDirectory(target)
100
+ report: DeployReport = DeployReport()
101
+
102
+ # The configuration has to land first, since every other path derives from it.
103
+ configPath: Path = root / CONFIG_FILENAME
104
+ if configPath.exists():
105
+ report.skipped.append(configPath)
106
+ else:
107
+ _write(configPath, readTemplate(TEMPLATE_CONFIG))
108
+ report.created.append(configPath)
109
+
110
+ config: Config = loadConfig(configPath)
111
+
112
+ # Both status directories, so a freshly deployed repository has somewhere to put a ticket.
113
+ for directory in (config.todoPath, config.donePath):
114
+ if directory.is_dir():
115
+ report.skipped.append(directory)
116
+ else:
117
+ directory.mkdir(parents=True, exist_ok=True)
118
+ report.created.append(directory)
119
+
120
+ _writeClaudeTemplate(config, report)
121
+ _mergeMcpConfig(root, report)
122
+ _ignoreLockFile(root, report)
123
+
124
+ return report
125
+
126
+
127
+ def upgrade(target: Path) -> DeployReport:
128
+ """
129
+ Refresh the deployed templates in a consumer repository.
130
+
131
+ This rewrites what docket owns and nothing else. The configuration is left alone because it holds the key registry, and tickets are left alone because they are the repository's data.
132
+ The `.gitignore` is the one file docket does not own but still appends to, since a repository deployed before the lock existed has no entry for it and would otherwise commit one.
133
+
134
+ target: The repository root to upgrade.
135
+
136
+ Returns what was done.
137
+ """
138
+
139
+ root: Path = _requireDirectory(target)
140
+
141
+ configPath: Path = root / CONFIG_FILENAME
142
+ if not configPath.is_file():
143
+ raise DeployError(f"No {CONFIG_FILENAME} in {root}. Run 'docket deploy {root}' first.")
144
+
145
+ report: DeployReport = DeployReport()
146
+ config: Config = loadConfig(configPath)
147
+
148
+ # The configuration is deliberately untouched, and saying so is more useful than staying silent about it.
149
+ report.skipped.append(configPath)
150
+
151
+ _writeClaudeTemplate(config, report)
152
+ _mergeMcpConfig(root, report)
153
+ _ignoreLockFile(root, report)
154
+
155
+ return report
156
+
157
+
158
+ def readTemplate(name: str) -> str:
159
+ """
160
+ Read a template shipped inside the package.
161
+
162
+ name: The template filename.
163
+
164
+ Returns the template text.
165
+ """
166
+
167
+ return files("docket").joinpath("templates", name).read_text(encoding="utf-8")
168
+
169
+
170
+ def _writeClaudeTemplate(config: Config, report: DeployReport) -> None:
171
+ """
172
+ Write the agent instructions into the ticket root.
173
+
174
+ This lands beside the tickets rather than at the repository root, so an agent opening the ticket directory reads it in place.
175
+
176
+ config: The loaded configuration, naming the ticket root.
177
+ report: The report to record the write against.
178
+ """
179
+
180
+ path: Path = config.rootPath / CLAUDE_FILENAME
181
+ existed: bool = path.exists()
182
+
183
+ _write(path, readTemplate(TEMPLATE_CLAUDE))
184
+ report.record(path, existed)
185
+
186
+
187
+ def _mergeMcpConfig(root: Path, report: DeployReport) -> None:
188
+ """
189
+ Add docket's server entry to the repository's `.mcp.json`.
190
+
191
+ This is the step most likely to damage something, so it reads, modifies, and writes rather than overwriting. Docket's own entry is replaced and every other entry is preserved. A file that is not valid JSON is refused rather than clobbered.
192
+
193
+ root: The repository root.
194
+ report: The report to record the write against.
195
+ """
196
+
197
+ path: Path = root / MCP_FILENAME
198
+ existed: bool = path.exists()
199
+
200
+ document: dict[str, Any] = {}
201
+ if existed:
202
+ try:
203
+ loaded: Any = json.loads(path.read_text(encoding="utf-8"))
204
+ except json.JSONDecodeError as error:
205
+ raise DeployError(f"{path} is not valid JSON, so it was left untouched: {error}") from error
206
+
207
+ # A top-level array or string is not something an entry can be merged into, and overwriting it would destroy whatever it was.
208
+ if not isinstance(loaded, dict):
209
+ raise DeployError(f"{path} does not hold a JSON object, so it was left untouched.")
210
+
211
+ document = loaded
212
+
213
+ servers: Any = document.get(MCP_SERVERS_KEY, {})
214
+ if not isinstance(servers, dict):
215
+ raise DeployError(f"'{MCP_SERVERS_KEY}' in {path} is not a JSON object, so it was left untouched.")
216
+
217
+ # Replace only docket's entry, leaving every other server exactly as it was.
218
+ servers[MCP_SERVER_NAME] = {"type": "stdio", "command": MCP_COMMAND, "args": []}
219
+ document[MCP_SERVERS_KEY] = servers
220
+
221
+ _write(path, json.dumps(document, indent=2) + "\n")
222
+ report.record(path, existed)
223
+
224
+
225
+ def _ignoreLockFile(root: Path, report: DeployReport) -> None:
226
+ """
227
+ Ensure the repository's `.gitignore` covers docket's lock file.
228
+
229
+ The lock file is machine state rather than repository content, so committing it would put one developer's lock in another developer's checkout.
230
+ Only the entry is appended. Everything already in the file is preserved, and a file that already covers the lock is left exactly as it is.
231
+
232
+ root: The repository root.
233
+ report: The report to record the write against.
234
+ """
235
+
236
+ path: Path = root / GITIGNORE_FILENAME
237
+ existed: bool = path.exists()
238
+
239
+ lines: list[str] = []
240
+ if existed:
241
+ try:
242
+ lines = path.read_text(encoding="utf-8").splitlines()
243
+ except OSError as error:
244
+ raise DeployError(f"Could not read {path}: {error}") from error
245
+
246
+ # An entry already present means there is nothing to do, and rewriting the file to say so would only churn it.
247
+ if any(line.strip() == LOCK_IGNORE_ENTRY for line in lines):
248
+ report.skipped.append(path)
249
+
250
+ return
251
+
252
+ # Separate the entry from whatever came before it, so it does not land on the end of an existing line or crowd an unrelated block.
253
+ if lines and lines[-1].strip():
254
+ lines.append("")
255
+
256
+ lines.extend([LOCK_IGNORE_COMMENT, LOCK_IGNORE_ENTRY])
257
+
258
+ _write(path, "\n".join(lines) + "\n")
259
+ report.record(path, existed)
260
+
261
+
262
+ def _requireDirectory(target: Path) -> Path:
263
+ """
264
+ Resolve a deploy target, refusing anything that is not an existing directory.
265
+
266
+ target: The path given by the caller.
267
+
268
+ Returns the resolved directory.
269
+ """
270
+
271
+ resolved: Path = target.resolve()
272
+
273
+ if not resolved.is_dir():
274
+ raise DeployError(f"{resolved} is not a directory.")
275
+
276
+ return resolved
277
+
278
+
279
+ def _write(path: Path, text: str) -> None:
280
+ """
281
+ Write a file, creating its parent directories.
282
+
283
+ path: Where to write.
284
+ text: What to write.
285
+ """
286
+
287
+ path.parent.mkdir(parents=True, exist_ok=True)
288
+ writeTextAtomic(path, text)