@unclex/ken-task 0.0.0-stage → 0.1.1

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.
package/dist/cli.js ADDED
@@ -0,0 +1,532 @@
1
+ #!/usr/bin/env node
2
+ // The task system, an external subcommand of ken: see docs/ken-task.md.
3
+ import { spawnSync } from 'node:child_process';
4
+ import { readFileSync, statSync } from 'node:fs';
5
+ import { join, resolve } from 'node:path';
6
+ import { addTask } from "./add.js";
7
+ import { archiveTasks, purgeArchive } from "./archive.js";
8
+ import { claimTask } from "./claim.js";
9
+ import { finishTask } from "./finish.js";
10
+ import { lintTasks } from "./lint.js";
11
+ import { formatRows, listTasks, localDate, readyTasks } from "./list.js";
12
+ import { renameTask } from "./rename.js";
13
+ import { readmeChain, resolveTask } from "./resolve.js";
14
+ import { setTask } from "./set.js";
15
+ const HELP = `ken task <command>
16
+
17
+ Plain-text tasks in one folder of the ken root: task.folder in .ken, relative to the
18
+ root or absolute, default tasks. Every file in it, at any depth, is a task, except
19
+ README.md and dot entries; its path is its identity.
20
+
21
+ A command that names a task takes any path that reaches the file: absolute, from here,
22
+ from the root or from the folder, with or without its extension when one file has that
23
+ stem.
24
+
25
+ Commands:
26
+ list [--json] every task with its state, what it waits on, and what needs you
27
+ ready the paths of the ready tasks, in the order to take them
28
+ path <task> [--readmes]
29
+ the absolute path of a task, live or archived; with --readmes, then
30
+ the README.md of each folder up to the root
31
+ add <path> [-r <key>] [-b <task>]...
32
+ create a task file, print its path
33
+ set <task> <field> <value>
34
+ rewrite one front matter line: status, repo, blocked-by, scheduled, due
35
+ rename <task> <path>
36
+ move a task file, rewriting every blocked-by that names it
37
+ claim [<task>] give a ready repo task its branch and worktree, print the worktree
38
+ finish <task> remove the worktree and branch of a done or wontfix task
39
+ lint [--fix] every file not in the canonical shape, with the upgrade
40
+ archive <task>...
41
+ move closed tasks into the folder's .archive/, print the new paths
42
+ purge --older-than <days>
43
+ delete archived tasks closed more than <days> ago; for a person to run
44
+
45
+ Examples:
46
+ ken task list
47
+ ken task ready | head -1
48
+ ken task add portal/fix-login -b portal/web-view-profiles
49
+ ken task path tasks/portal/print-web-views-to-pdf --readmes | xargs cat
50
+ cd "$(ken task claim)"
51
+ ken task set tasks/portal/print-web-views-to-pdf status done
52
+ ken task rename tasks/portal/print-web-views-to-pdf portal/print-to-pdf
53
+ ken task finish tasks/portal/print-web-views-to-pdf
54
+ ken task lint --fix
55
+ ken task archive tasks/portal/print-web-views-to-pdf
56
+
57
+ Run \`ken task <command> --help\` for one command.`;
58
+ const LIST_HELP = `ken task list [--json]
59
+
60
+ Every task in the folder, by path: its state, the blockers it waits on, and what needs
61
+ you. Always exits 0: a file that cannot be fully read is a row, never an abort.
62
+
63
+ States, in this order. A task's branch is its path in the folder without extension, in
64
+ the clone of its repo that \`ken path code <repo>\` prints:
65
+ problem the file could not be fully read; its note says the fix
66
+ landing status: done, but its branch exists and is not on the default branch
67
+ done status: done
68
+ wontfix status: wontfix
69
+ claimed open, and its branch exists
70
+ blocked a blocked-by entry is open, landing, or found in neither the folder nor its
71
+ .archive/
72
+ later scheduled is after today
73
+ ready none of the above
74
+
75
+ A repo not cloned here has no branches, said once on stderr.
76
+
77
+ Notes under a row: overdue; open more than 90 days, by created, else the date git added
78
+ the file, else its mtime; landing; closed but its branch remains; claimed but its
79
+ worktree is missing or holds another branch; uncommitted changes in its worktree; a
80
+ problem with its fix; a deviation from the canonical shape, read anyway, with the
81
+ upgrade.
82
+
83
+ --json one array of objects: path, rel (the path in the folder, extension kept),
84
+ title, every field read, other (the fields ken-task does not know), state,
85
+ unmet blockers and notes; created as the 90-day note reads it, on every row
86
+ but a problem, so sorting ready rows by due, created, path is
87
+ \`ken task ready\`'s order
88
+
89
+ Examples:
90
+ ken task list
91
+ ken task list --json | jq -r '.[] | select(.state == "blocked") | .path'
92
+ ken task list --json | jq '.[] | select(.notes | length > 0) | {path, notes}'`;
93
+ const READY_HELP = `ken task ready
94
+
95
+ The absolute paths of the ready tasks, one per line, in the order to take them: earliest
96
+ due (none last), then earliest created (else the date git added the file, else its
97
+ mtime), then path. A task is ready when it is open, no blocker is open or missing, and
98
+ it is not scheduled after today. Nothing ready prints nothing and exits 0.
99
+
100
+ Examples:
101
+ ken task ready
102
+ ken task ready | head -1
103
+ ken task ready | xargs -n1 head -5`;
104
+ const PATH_HELP = `ken task path <task> [--readmes]
105
+
106
+ The absolute path of the task file, in the folder or its .archive/. <task> is any path
107
+ that reaches it: absolute, from here, from the root or from the folder, with or without its extension
108
+ when exactly one file has that stem. A path outside the folder is refused; a task found
109
+ nowhere exits 1.
110
+
111
+ --readmes after the file, the README.md of each folder from the task's up to the
112
+ root, root last, one per line; a folder without one adds no line. They hold
113
+ the conventions the task is worked under and name where what it taught
114
+ goes. An archived task reads the chain of the folder it was archived from.
115
+
116
+ Examples:
117
+ ken task path tasks/portal/print-web-views-to-pdf.md
118
+ cd tasks && ken task path portal/print-web-views-to-pdf
119
+ ken task path tasks/portal/print-web-views-to-pdf --readmes | xargs cat # with its README chain`;
120
+ const ADD_HELP = `ken task add <path> [-r <key>] [-b <task>]...
121
+
122
+ Create the task file and print its absolute path. <path> is where it goes in the folder:
123
+ absolute, from here, from the root or from the folder; it is a .md, the one format with
124
+ front matter, so .md is added when it has no extension and any other is refused; folders
125
+ on the way are made. A task's path is its branch name, so it is
126
+ lowercased and spaces become dashes, said on stderr; other punctuation is refused with
127
+ the name to use instead. The file is:
128
+
129
+ ---
130
+ status: todo
131
+ created: <today>
132
+ repo: <key> with -r, or inside a clone
133
+ blocked-by: [<task>, ...] with -b
134
+ ---
135
+
136
+ # <the name, dashes as spaces>
137
+
138
+ -r <key> the repo the work is in, <host>/<owner>/<repo>; inside a clone or worktree
139
+ it defaults to the key \`ken which\` prints there
140
+ -b <task> a task this one waits on, any path that reaches it, live or archived;
141
+ repeat for more; written relative to the new file
142
+
143
+ Refused before anything is written: a path outside the folder; a file that exists, or
144
+ another extension of the same name; a -b found nowhere; a -r that is no repo key.
145
+
146
+ Examples:
147
+ ken task add portal/fix-login
148
+ ken task add "Fix Login" # tasks/fix-login.md
149
+ ken task add portal/fix-login -r github.com/acme/portal -b portal/web-view-profiles
150
+ echo 'Login fails after a password reset.' >> "$(ken task add portal/fix-login)"`;
151
+ const SET_HELP = `ken task set <task> <field> <value>
152
+
153
+ Rewrite the one front matter line of <field> in the task file and print its absolute
154
+ path. Every other byte stays: other fields, comments on the line, the body, the line
155
+ endings. A missing line is added to the front matter; a file with none gets one at the
156
+ top. An empty value removes the line.
157
+
158
+ Fields:
159
+ status todo, done or wontfix; done or wontfix also writes closed: <today>, todo
160
+ removes closed
161
+ repo a repo key, <host>/<owner>/<repo>, e.g. github.com/acme/join-web
162
+ blocked-by comma-separated tasks, each any path that reaches the file from here, the
163
+ root or the folder, found live or archived; written relative to the file
164
+ scheduled YYYY-MM-DD, the day the task becomes ready
165
+ due YYYY-MM-DD, its deadline
166
+
167
+ Only a .md has front matter; another file is refused, as is one \`ken task list\` shows
168
+ as a problem, until the fix its note names is made. status done is refused on a task
169
+ whose branch, its path in the folder without extension, exists in its repo and is not on
170
+ the default branch: done means landed, by a rebase then a merge that keeps the commits.
171
+
172
+ Examples:
173
+ ken task set tasks/portal/print-web-views-to-pdf status done
174
+ ken task set tasks/portal/print-web-views-to-pdf repo github.com/xiaoxinghu/portal
175
+ ken task set tasks/portal/print-web-views-to-pdf blocked-by tasks/portal/a,tasks/ken/b.md
176
+ ken task set tasks/portal/print-web-views-to-pdf due 2026-11-30
177
+ ken task set tasks/portal/print-web-views-to-pdf scheduled '' # remove the line`;
178
+ /** The root and the task folder, absolute: KEN_ROOT, as `ken` dispatch sets it, and task.folder in its .ken. */
179
+ function settings() {
180
+ const root = process.env.KEN_ROOT;
181
+ if (!root) {
182
+ throw new Error('ken-task reads the root from KEN_ROOT, which `ken` sets when it runs `ken task`, and KEN_ROOT is unset. ' +
183
+ 'Run it as `ken task <command>`, e.g. `ken task list`.');
184
+ }
185
+ const file = join(root, '.ken');
186
+ let text;
187
+ try {
188
+ text = readFileSync(file, 'utf8');
189
+ }
190
+ catch (e) {
191
+ throw new Error(`ken-task reads task.folder from ${file}, which could not be read (${e instanceof Error ? e.message : String(e)}), so it cannot find the tasks. ` +
192
+ 'Run `ken task` from inside a ken root, or `ken init` to make one.');
193
+ }
194
+ // a repeated key reads as its last line; the value is the rest of the line, trimmed
195
+ const lines = text.split('\n').filter((line) => line.startsWith('task.folder='));
196
+ const folder = lines.length ? (lines.at(-1) ?? '').slice('task.folder='.length).trim() : 'tasks';
197
+ if (!folder) {
198
+ throw new Error(`task.folder in ${file} is empty, so ken-task cannot find the tasks: it is a folder, relative to the root or absolute, like \`task.folder=tasks\`. ` +
199
+ `Fix the line, or delete it for the default, tasks; \`sed -n 's/^task\\.folder=//p' ${file}\` prints it.`);
200
+ }
201
+ return { root, folder: resolve(root, folder) };
202
+ }
203
+ /** Whether `folder` is a folder; one that cannot be looked at counts, so its error is a row. */
204
+ function isFolder(folder) {
205
+ try {
206
+ return statSync(folder, { throwIfNoEntry: false })?.isDirectory() ?? false;
207
+ }
208
+ catch {
209
+ return true;
210
+ }
211
+ }
212
+ function list(args) {
213
+ const json = args[0] === '--json';
214
+ if (args.length > (json ? 1 : 0)) {
215
+ throw new Error(`ken task list takes only --json, got ${JSON.stringify(args.join(' '))}. Run \`ken task list\` or \`ken task list --json\`.`);
216
+ }
217
+ const { root, folder } = settings();
218
+ const found = isFolder(folder);
219
+ const rows = found ? listTasks(root, folder, localDate(new Date())) : [];
220
+ if (!rows.length) {
221
+ process.stderr.write(`${found ? `No tasks in ${folder}` : `${folder} is not a folder, so there are no tasks`}. ` +
222
+ `Add one by writing a file there, e.g. \`mkdir -p ${folder} && echo '# Do the thing' > ${folder}/do-the-thing.md\`, ` +
223
+ 'or point task.folder in .ken at your tasks.\n');
224
+ }
225
+ if (json)
226
+ process.stdout.write(`${JSON.stringify(rows, null, 2)}\n`);
227
+ else if (rows.length)
228
+ process.stdout.write(`${formatRows(rows)}\n`);
229
+ }
230
+ function ready(args) {
231
+ if (args.length) {
232
+ throw new Error(`ken task ready takes no arguments, got ${JSON.stringify(args.join(' '))}. Run \`ken task ready\`.`);
233
+ }
234
+ const { root, folder } = settings();
235
+ const paths = readyTasks(root, folder, localDate(new Date())).map((row) => row.path);
236
+ if (paths.length)
237
+ process.stdout.write(`${paths.join('\n')}\n`);
238
+ else {
239
+ process.stderr.write(`No task in ${folder} is ready. Run \`ken task list\` to see what each task waits on.\n`);
240
+ }
241
+ }
242
+ function path(args) {
243
+ const readmes = args.includes('--readmes');
244
+ const tasks = args.filter((arg) => arg !== '--readmes');
245
+ if (tasks.length !== 1) {
246
+ throw new Error(`ken task path takes one task, got ${tasks.length}. Run \`ken task path <task> [--readmes]\`, e.g. \`ken task path tasks/do-the-thing.md\`.`);
247
+ }
248
+ const { root, folder } = settings();
249
+ const file = resolveTask(root, folder, process.cwd(), tasks[0] ?? '');
250
+ const lines = readmes ? readmeChain(root, folder, file) : [file];
251
+ process.stdout.write(`${lines.join('\n')}\n`);
252
+ }
253
+ function add(args) {
254
+ const usage = 'Run `ken task add <path> [-r <key>] [-b <task>]...`, e.g. `ken task add portal/fix-login -b portal/web-view-profiles`.';
255
+ const paths = [];
256
+ const blockedBy = [];
257
+ let repo;
258
+ for (let i = 0; i < args.length; i++) {
259
+ const arg = args[i] ?? '';
260
+ const value = args[i + 1];
261
+ if ((arg === '-r' || arg === '-b') && value === undefined) {
262
+ throw new Error(`${arg} takes a value, and none followed it. ${usage}`);
263
+ }
264
+ if (arg === '-r') {
265
+ if (repo !== undefined)
266
+ throw new Error(`-r is given twice, and a task has one repo. ${usage}`);
267
+ repo = value;
268
+ i++;
269
+ }
270
+ else if (arg === '-b') {
271
+ blockedBy.push(value ?? '');
272
+ i++;
273
+ }
274
+ else if (arg.startsWith('-')) {
275
+ throw new Error(`ken task add takes -r and -b, not ${arg}. ${usage}`);
276
+ }
277
+ else
278
+ paths.push(arg);
279
+ }
280
+ if (paths.length !== 1) {
281
+ throw new Error(`ken task add takes one path, got ${paths.length}: quote a name with spaces. ${usage}`);
282
+ }
283
+ const { root, folder } = settings();
284
+ if (repo === undefined) {
285
+ // `ken which` prints `<key> <clone|worktree> [<branch>]`, and fails outside a checkout
286
+ const r = spawnSync('ken', ['which'], { encoding: 'utf8' });
287
+ repo = r.status === 0 ? r.stdout.split(' ')[0]?.trim() || undefined : undefined;
288
+ if (repo) {
289
+ process.stderr.write(`repo: ${repo}, the clone this runs in, as \`ken which\` says; pass -r <key> for another repo.\n`);
290
+ }
291
+ }
292
+ const added = addTask(root, folder, process.cwd(), paths[0] ?? '', {
293
+ repo,
294
+ blockedBy,
295
+ today: localDate(new Date())
296
+ });
297
+ if (added.renamed)
298
+ process.stderr.write(`${added.renamed}\n`);
299
+ process.stdout.write(`${added.path}\n`);
300
+ }
301
+ function set(args) {
302
+ const [task, field, value] = args;
303
+ if (args.length !== 3 || task === undefined || field === undefined || value === undefined) {
304
+ throw new Error(`ken task set takes a task, a field and a value, got ${args.length} arguments. ` +
305
+ "Run `ken task set <task> <field> <value>`, e.g. `ken task set tasks/do-the-thing.md status done`, or `''` as the value to remove the line.");
306
+ }
307
+ const { root, folder } = settings();
308
+ const path = setTask(root, folder, process.cwd(), [task, field, value], localDate(new Date()));
309
+ process.stdout.write(`${path}\n`);
310
+ if (field === 'status' && value === 'done') {
311
+ process.stderr.write(`Done. Before the task is archived, distil what it taught into the knowledge section its folder's README.md names; \`ken task path "${path}" --readmes\` prints that README chain.\n`);
312
+ }
313
+ }
314
+ const RENAME_HELP = `ken task rename <task> <path>
315
+
316
+ Move the task file to <path> and print its new absolute path. <path> is read as add reads
317
+ one: absolute, from here, from the root or from the folder; lowercased with dashes for
318
+ spaces, said on stderr; a .md, .md added when it has no extension; folders on the way are
319
+ made. A task's path is its identity, so rename keeps every reference true:
320
+
321
+ - every live task whose blocked-by names it gets that value rewritten, relative to its
322
+ own file, the rest of the line, a comment included, kept
323
+ - moved to another folder, its own blocked-by is rewritten so each value still resolves
324
+ - before anything is written, every reference must name, as it will read after the move,
325
+ the file it names now
326
+
327
+ The heading is content and is left alone. Files in .archive/ are never touched, so a
328
+ reference from an archived task may go stale. The new file is made first and the old one
329
+ removed last; a write that fails midway is undone, so nothing is renamed.
330
+
331
+ Refused before anything is written: a task whose branch, its path in the folder without
332
+ extension, exists in its repo (claimed, landing, or not finished), since the branch
333
+ carries the old name: close it and run \`ken task finish\` first; an archived task; a link
334
+ to it, which the move would break, or whose blocked-by names it, since the file behind it
335
+ may be archived; a live task that cannot be fully read, a problem in \`ken task list\`,
336
+ since it may name it; a file of another extension whose text would read as other fields
337
+ once a .md; a new name that would change what a reference names, as by shadowing an
338
+ archived task; a target that exists, or another extension of its name; other punctuation
339
+ in <path>.
340
+
341
+ Examples:
342
+ ken task rename tasks/fix-login tasks/fix-login-after-reset
343
+ ken task rename tasks/fix-login portal/fix-login # into tasks/portal/
344
+ ken task rename "$(ken task ready | head -1)" portal/next-up`;
345
+ const CLAIM_HELP = `ken task claim [<task>]
346
+
347
+ Start work on a ready task: make its branch, its path in the folder without extension,
348
+ in the clone of its repo, from the default branch as it stands (no fetch); then \`ken get
349
+ <repo> -b <branch>\` makes the worktree beside the clone, its output on stderr. Prints
350
+ only the worktree's path.
351
+
352
+ Without a task: the first ready task, in \`ken task ready\` order, that has a repo cloned
353
+ here. Making the branch is the claim: of two callers only one makes it, and the other is
354
+ told so, or, without a task, goes on to the next.
355
+
356
+ Refused: a task that is not ready, with its state and what it waits on; one with no
357
+ repo, with the \`ken task set\` to run; one whose repo is not cloned here, with the
358
+ \`ken get\` to run. When the worktree fails after the branch is made, the branch stays,
359
+ so the task stays claimed, and the \`ken get -b\` to rerun is printed.
360
+
361
+ Examples:
362
+ cd "$(ken task claim)"
363
+ cd "$(ken task claim tasks/portal/fix-login)" # branch portal/fix-login
364
+ ken task claim portal/fix-login # ken path code <repo> portal/fix-login`;
365
+ function claim(args) {
366
+ if (args.length > 1) {
367
+ throw new Error(`ken task claim takes at most one task, got ${args.length}. Run \`ken task claim\` for the next ready task, or \`ken task claim <task>\`.`);
368
+ }
369
+ const { root, folder } = settings();
370
+ const path = claimTask(root, folder, process.cwd(), args[0], localDate(new Date()));
371
+ process.stdout.write(`${path}\n`);
372
+ }
373
+ const FINISH_HELP = `ken task finish <task>
374
+
375
+ Remove the worktree, then the branch, of a done or wontfix task: \`git worktree remove\`
376
+ then \`git branch -d\`, in the clone \`ken path code <repo>\` prints. The branch is the
377
+ task's path in the folder without extension. Run it from outside the worktree. Prints
378
+ nothing on stdout; stderr says what was removed. A task with no repo, or no branch here,
379
+ has nothing to remove.
380
+
381
+ Refused: an open task, so work in progress is never thrown away; set it done first.
382
+ Git's own refusals pass through, uncommitted changes in the worktree or commits not on
383
+ the default branch, with the --force form to run by hand when they are to go.
384
+
385
+ Examples:
386
+ ken task set tasks/portal/print-web-views-to-pdf status done
387
+ ken task finish tasks/portal/print-web-views-to-pdf
388
+ ken task list --json | jq -r '.[] | select(.state == "done") | .path' | xargs -n1 ken task finish`;
389
+ function rename(args) {
390
+ if (args.length !== 2) {
391
+ throw new Error(`ken task rename takes a task and a path, got ${args.length} arguments: quote a name with spaces. ` +
392
+ 'Run `ken task rename <task> <path>`, e.g. `ken task rename tasks/fix-login.md portal/fix-login`.');
393
+ }
394
+ const { root, folder } = settings();
395
+ const renamed = renameTask(root, folder, process.cwd(), args[0] ?? '', args[1] ?? '');
396
+ if (renamed.renamed)
397
+ process.stderr.write(`${renamed.renamed}\n`);
398
+ process.stdout.write(`${renamed.path}\n`);
399
+ }
400
+ function finish(args) {
401
+ if (args.length !== 1) {
402
+ throw new Error(`ken task finish takes one task, got ${args.length}. Run \`ken task finish <task>\`, e.g. \`ken task finish tasks/do-the-thing.md\`.`);
403
+ }
404
+ const { root, folder } = settings();
405
+ process.stderr.write(`${finishTask(root, folder, process.cwd(), args[0] ?? '')}\n`);
406
+ }
407
+ const LINT_HELP = `ken task lint [--fix]
408
+
409
+ Every file in the task folder not in the canonical shape, one line per deviation: its
410
+ absolute path, what deviates, and the upgrade, as a command or an edit. Exits 0 when
411
+ nothing deviates, 1 otherwise, so a hook can run it. The archive is not linted.
412
+
413
+ --fix apply the upgrades that lose nothing, each printed as done; the rest stay
414
+ listed, and the exit code says whether any is left
415
+
416
+ Applied by --fix, through the one-line writer of \`ken task set\`, every other byte kept:
417
+ no status line status: todo
418
+ no created line created: <the date git added it, else its mtime>
419
+ status done or wontfix, no closed closed: <its mtime>
420
+ blocked_by, blockedBy, depends_on, depends-on, a single value, a block list
421
+ blocked-by: [a.md, b.md]
422
+ a blocked-by path that resolves only from the folder or the root
423
+ the path relative to the file
424
+
425
+ Only named, for you to fix: a status other than todo, done or wontfix; front matter with
426
+ no closing ---; a blocked-by found nowhere; a file that is not a .md; a file \`ken task
427
+ list\` shows as a problem. The body is never touched.
428
+
429
+ Examples:
430
+ ken task lint
431
+ ken task lint --fix
432
+ ken task lint | cut -d: -f1 | sort -u # the files that deviate`;
433
+ function lint(args) {
434
+ const fix = args[0] === '--fix';
435
+ if (args.length > (fix ? 1 : 0)) {
436
+ throw new Error(`ken task lint takes only --fix, got ${JSON.stringify(args.join(' '))}. Run \`ken task lint\` or \`ken task lint --fix\`.`);
437
+ }
438
+ const { root, folder } = settings();
439
+ if (!isFolder(folder))
440
+ return;
441
+ const { lines, deviates } = lintTasks(root, folder, fix);
442
+ if (lines.length)
443
+ process.stdout.write(`${lines.join('\n')}\n`);
444
+ if (deviates)
445
+ process.exitCode = 1;
446
+ }
447
+ const ARCHIVE_HELP = `ken task archive <task>...
448
+
449
+ Move each task to <folder>/.archive/<its path in the folder> and print its new absolute
450
+ path. Nothing else is read or written: a blocked-by naming it still resolves, through the
451
+ archive, and an archived blocker blocks nothing. A name already in the archive keeps its
452
+ file; the new one takes a numeric suffix before its extension, fix-login-2.md, said on
453
+ stderr. To bring one back, \`mv\` it.
454
+
455
+ Refused, every task checked before any is moved: an open task (todo, an unknown status,
456
+ or a file that could not be fully read), since its dependents would become ready; a task
457
+ whose branch still exists in its repo here, to remove first with \`ken task finish\`; a
458
+ task already archived.
459
+
460
+ Examples:
461
+ ken task archive tasks/portal/print-web-views-to-pdf
462
+ ken task archive tasks/portal/a.md tasks/portal/b.md
463
+ ken task list --json | jq -r '.[] | select(.state == "done" or .state == "wontfix") | .path' | xargs ken task archive`;
464
+ function archive(args) {
465
+ if (!args.length) {
466
+ throw new Error('ken task archive takes one task or more, got none. Run `ken task archive <task>...`, e.g. `ken task archive tasks/do-the-thing.md`.');
467
+ }
468
+ const { root, folder } = settings();
469
+ for (const { path, renamed } of archiveTasks(root, folder, process.cwd(), args)) {
470
+ if (renamed)
471
+ process.stderr.write(`${renamed}\n`);
472
+ process.stdout.write(`${path}\n`);
473
+ }
474
+ }
475
+ const PURGE_HELP = `ken task purge --older-than <days>
476
+
477
+ Delete every file in <folder>/.archive/ whose closed date, else its mtime, is more than
478
+ <days> days before today, and print each path deleted. Then say once whether the folder
479
+ is in a git work tree: if it is, its history holds what was committed of them; if not,
480
+ nothing holds a copy. --older-than has no default. The one command that deletes a task:
481
+ run it by hand, never from a hook or an agent.
482
+
483
+ Examples:
484
+ ken task purge --older-than 365
485
+ ken task purge --older-than 90 | wc -l`;
486
+ function purge(args) {
487
+ const [flag, days] = args;
488
+ if (args.length !== 2 || flag !== '--older-than' || !/^\d+$/.test(days ?? '')) {
489
+ throw new Error(`ken task purge takes --older-than <days>, a whole number with no default, since it deletes; got ${JSON.stringify(args.join(' '))}. ` +
490
+ 'Run `ken task purge --older-than <days>`, e.g. `ken task purge --older-than 365`.');
491
+ }
492
+ const { folder } = settings();
493
+ const { deleted, said } = purgeArchive(folder, Number(days), new Date());
494
+ if (deleted.length)
495
+ process.stdout.write(`${deleted.join('\n')}\n`);
496
+ process.stderr.write(`${said}\n`);
497
+ }
498
+ const COMMANDS = {
499
+ list: [LIST_HELP, list],
500
+ ready: [READY_HELP, ready],
501
+ path: [PATH_HELP, path],
502
+ add: [ADD_HELP, add],
503
+ set: [SET_HELP, set],
504
+ rename: [RENAME_HELP, rename],
505
+ claim: [CLAIM_HELP, claim],
506
+ finish: [FINISH_HELP, finish],
507
+ lint: [LINT_HELP, lint],
508
+ archive: [ARCHIVE_HELP, archive],
509
+ purge: [PURGE_HELP, purge]
510
+ };
511
+ const [command, ...args] = process.argv.slice(2);
512
+ const help = (a) => a.includes('--help') || a.includes('-h');
513
+ const found = command !== undefined && Object.hasOwn(COMMANDS, command) && COMMANDS[command];
514
+ try {
515
+ if (command === undefined || command === 'help' || help([command])) {
516
+ process.stdout.write(`${HELP}\n`);
517
+ }
518
+ else if (found) {
519
+ const [text, run] = found;
520
+ if (help(args))
521
+ process.stdout.write(`${text}\n`);
522
+ else
523
+ run(args);
524
+ }
525
+ else {
526
+ throw new Error(`${JSON.stringify(command)} is not a ken task command. Run \`ken task --help\` for the commands.`);
527
+ }
528
+ }
529
+ catch (e) {
530
+ process.stderr.write(`ken task: ${e instanceof Error ? e.message : String(e)}\n`);
531
+ process.exit(1);
532
+ }
package/dist/finish.js ADDED
@@ -0,0 +1,47 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { basename, isAbsolute, relative } from 'node:path';
3
+ import { branchOf, git, repos } from "./git.js";
4
+ import { readTask } from "./read.js";
5
+ import { real, resolveTask } from "./resolve.js";
6
+ /** Run `git` in `clone`; its refusal passes through, with `next` after it. */
7
+ function pass(clone, args, next) {
8
+ try {
9
+ git(clone, ...args);
10
+ }
11
+ catch (e) {
12
+ throw new Error(`${e.message}\n${next}`);
13
+ }
14
+ }
15
+ /**
16
+ * `ken task finish`: remove the worktree, then the branch, of the closed task `arg` names,
17
+ * in the clone `ken path code` prints, and say what was removed. Its status is all that
18
+ * counts; git's own refusals pass through, with the `--force` form to run by hand.
19
+ */
20
+ export function finishTask(root, folder, cwd, arg) {
21
+ const path = resolveTask(root, folder, cwd, arg);
22
+ const { fields, problems } = readTask(basename(path), readFileSync(path, 'utf8'));
23
+ if (problems.length || (fields.status !== 'done' && fields.status !== 'wontfix')) {
24
+ throw new Error(`${path} is open (${problems.length ? 'it could not be fully read' : `status ${fields.status ?? 'todo'}`}), ` +
25
+ 'and ken task finish removes the worktree and branch of a done or wontfix task only, so work in progress is never thrown away. ' +
26
+ `Once it has landed, run \`ken task set ${path} status done\`, then \`ken task finish ${path}\`.`);
27
+ }
28
+ if (!fields.repo)
29
+ return `${path} has no repo, so it has no branch or worktree to remove.`;
30
+ const repo = repos()(fields.repo);
31
+ const name = branchOf(real(folder), path);
32
+ if (!repo?.exists(name)) {
33
+ return `${path} has no branch ${name} in ${fields.repo} on this machine, so there is nothing to remove.`;
34
+ }
35
+ const { clone } = repo;
36
+ const worktree = repo.worktree(name);
37
+ const rerun = `then rerun \`ken task finish ${path}\``;
38
+ if (worktree) {
39
+ const rel = relative(real(worktree), real(cwd));
40
+ if (rel !== '..' && !rel.startsWith('../') && !isAbsolute(rel)) {
41
+ throw new Error(`You are in ${worktree}, the worktree ken task finish would remove from under you: \`cd ${clone}\`, ${rerun}.`);
42
+ }
43
+ pass(clone, ['worktree', 'remove', worktree], `Commit or discard what git names; to throw it away, \`git -C ${clone} worktree remove --force ${worktree}\`; ${rerun}.`);
44
+ }
45
+ pass(clone, ['branch', '-d', name], `Its commits are not on the default branch: land them, or, if they are to go (a squash merge, a wontfix), \`git -C ${clone} branch -D ${name}\`.`);
46
+ return `Finished ${path}: removed ${worktree ? `its worktree ${worktree} and ` : ''}its branch ${name} of ${fields.repo}.`;
47
+ }
package/dist/git.js ADDED
@@ -0,0 +1,88 @@
1
+ // The one place ken-task meets a repo's git: the git CLI, run in the clone `ken path code` prints.
2
+ import { spawnSync } from 'node:child_process';
3
+ import { join, relative } from 'node:path';
4
+ import { real } from "./resolve.js";
5
+ /** Run `command` with `args` in `cwd`; its stdout, trimmed, or a throw with what it said. */
6
+ function run(command, args, cwd) {
7
+ const r = spawnSync(command, args, { cwd, encoding: 'utf8' });
8
+ if (r.error) {
9
+ throw new Error(`ken-task runs ${command}, which could not be started: ${r.error.message}. Install it so it is on PATH, then rerun`);
10
+ }
11
+ if (r.status !== 0)
12
+ throw new Error(`\`${command} ${args.join(' ')}\` failed: ${r.stderr.trim()}`);
13
+ return r.stdout.trim();
14
+ }
15
+ /** `git <args>` in `cwd`. */
16
+ export const git = (cwd, ...args) => run('git', args, cwd);
17
+ /** What `ken path code <key> [<branch>]` prints: the clone, or the worktree of `branch` beside it. */
18
+ export const codePath = (key, branch) => run('ken', ['path', 'code', key, ...(branch === undefined ? [] : [branch])]);
19
+ /**
20
+ * Whether `path` is a clone: git, asked there, finds its own `.git` folder. A plain folder
21
+ * inside the root's own repo would otherwise send every git command to that repo.
22
+ */
23
+ export function isClone(path) {
24
+ const r = spawnSync('git', ['rev-parse', '--absolute-git-dir'], { cwd: path, encoding: 'utf8' });
25
+ return r.status === 0 && real(r.stdout.trim()) === real(join(path, '.git'));
26
+ }
27
+ /**
28
+ * The repo of each key, each asked of git once per run, its answers as of then: one
29
+ * `for-each-ref` for its branches, one for those on the default branch and one `worktree
30
+ * list`, each the first time it is needed. A key whose clone is not on this machine has no
31
+ * repo, so its tasks have no branch; that is said once on stderr, unless `quiet`.
32
+ */
33
+ export function repos(quiet = false) {
34
+ const seen = new Map();
35
+ return (key) => {
36
+ if (!seen.has(key))
37
+ seen.set(key, open(key, quiet));
38
+ return seen.get(key);
39
+ };
40
+ }
41
+ function open(key, quiet) {
42
+ const clone = codePath(key);
43
+ if (!isClone(clone)) {
44
+ if (quiet)
45
+ return undefined;
46
+ process.stderr.write(`${key} is not cloned on this machine (${clone}), so ken-task sees no branch of it: its tasks show the state their status gives. ` +
47
+ `Run \`ken get ${key}\` to clone it, or to be told what is in its place.\n`);
48
+ return undefined;
49
+ }
50
+ const lazy = (read) => {
51
+ let value;
52
+ return () => {
53
+ value ??= read();
54
+ return value;
55
+ };
56
+ };
57
+ const heads = (...args) => new Set(git(clone, 'for-each-ref', '--format=%(refname:lstrip=2)', ...args, 'refs/heads/')
58
+ .split('\n')
59
+ .filter(Boolean));
60
+ const branches = lazy(() => heads());
61
+ const merged = lazy(() => heads('--merged=HEAD'));
62
+ // path -> branch, NUL-separated, since a path may hold a newline
63
+ const worktrees = lazy(() => {
64
+ const found = new Map();
65
+ let path = '';
66
+ for (const line of git(clone, 'worktree', 'list', '--porcelain', '-z').split('\0')) {
67
+ if (line.startsWith('worktree ')) {
68
+ path = line.slice(9);
69
+ found.set(path, undefined);
70
+ }
71
+ else if (line.startsWith('branch refs/heads/'))
72
+ found.set(path, line.slice(18));
73
+ }
74
+ return found;
75
+ });
76
+ return {
77
+ key,
78
+ clone,
79
+ exists: (name) => branches().has(name),
80
+ landed: (name) => merged().has(name),
81
+ worktree: (name) => [...worktrees()].find(([, branch]) => branch === name)?.[0],
82
+ holds: (path) => worktrees().get(path)
83
+ };
84
+ }
85
+ /** The branch of the task at `path` in `folder`, a real path: its path there without extension. */
86
+ export const branchOf = (folder, path) => relative(folder, path).replace(/(.)\.[^./]*$/, '$1');
87
+ /** Whether the worktree at `path` has uncommitted changes, untracked files included. */
88
+ export const dirty = (path) => git(path, 'status', '--porcelain') !== '';