@unclex/ken-task 0.0.0-stage → 0.1.0

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/rename.js ADDED
@@ -0,0 +1,191 @@
1
+ import { closeSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, statSync, unlinkSync, utimesSync, writeFileSync } from 'node:fs';
2
+ import { basename, dirname, relative, resolve } from 'node:path';
3
+ import { newPath } from "./add.js";
4
+ import { branchOf, repos } from "./git.js";
5
+ import { resolveRef, walk } from "./list.js";
6
+ import { readTask } from "./read.js";
7
+ import { real, resolveTask } from "./resolve.js";
8
+ import { flowList, replaceFile, withField } from "./set.js";
9
+ /**
10
+ * `ken task rename`: move the live task `arg` names to `to`, a new path as `add` takes one,
11
+ * and keep every reference true: each live task whose `blocked-by` resolves to it gets that
12
+ * value rewritten relative to its own file, and the moved file's own `blocked-by` is
13
+ * rewritten when its folder changes. Refused for a task whose branch exists, since the
14
+ * branch carries the old name. Everything is checked first; then the new file is made, the
15
+ * references rewritten, and the old file removed last, so at every step each reference
16
+ * resolves to a file that exists.
17
+ */
18
+ export function renameTask(root, configured, cwd, arg, to) {
19
+ const folder = real(configured);
20
+ const found = resolveTask(root, folder, cwd, arg);
21
+ if (relative(folder, found).startsWith('.archive/')) {
22
+ throw new Error(`${found} is archived, and the archive is a permanent record that rename never touches: ` +
23
+ `to work on it again, move it back with \`mv ${found} ${folder}/<path>\`, then \`ken task rename ${folder}/<path> ${to}\`.`);
24
+ }
25
+ const stat = lstatSync(found);
26
+ if (!stat.isFile()) {
27
+ throw new Error(`${found} is not a regular file, and rename moves the file itself: \`ls -ld ${found}\` shows what it is; move it by hand.`);
28
+ }
29
+ // as the disk names it, the way the listing names each task
30
+ const source = real(found);
31
+ // the bytes, so a file that is not UTF-8 moves unchanged when nothing in it is rewritten
32
+ const sourceBytes = readFileSync(source);
33
+ const text = sourceBytes.toString('utf8');
34
+ const { fields, problems } = readTask(basename(source), text);
35
+ if (problems.length) {
36
+ throw new Error(`${source} could not be fully read, so its branch and blocked-by cannot be checked: ${problems.join('; ')}. Then rerun.`);
37
+ }
38
+ const target = newPath(root, folder, cwd, to, `ken task rename ${source}`);
39
+ const dest = target.path;
40
+ const name = branchOf(folder, source);
41
+ if (fields.repo && repos()(fields.repo)?.exists(name)) {
42
+ throw new Error(`${source} has a branch, ${name} of ${fields.repo}, and a branch carries its task's name, so after a rename neither \`ken task list\` nor \`ken task finish\` would find it: ` +
43
+ `close the task first, by landing it and \`ken task set ${source} status done\` (or \`status wontfix\`), then \`ken task finish ${source}\`; then rerun.`);
44
+ }
45
+ // the new text of each file whose blocked-by changes, the moved file's at its new path
46
+ // sorted, so the files are written, and on a failure restored, in one order
47
+ const tasks = new Set(walk(folder).sort());
48
+ const moves = dirname(dest) !== dirname(source);
49
+ const writes = new Map();
50
+ // each reference as written and as it will be, to check that it names the same file
51
+ const refs = [];
52
+ for (const path of tasks) {
53
+ const own = path === source;
54
+ // a link's file is elsewhere, maybe in the archive, maybe the task itself: rename moves
55
+ // and writes only files, so a link that would break or be written through is refused
56
+ const link = own ? undefined : linkTo(path);
57
+ if (link === source) {
58
+ throw new Error(`${path} is a link to ${source}, so the rename would leave it pointing nowhere, along with every blocked-by that names it: ` +
59
+ `remove it with \`rm ${path}\`, naming ${source} instead wherever it was named, then rerun.`);
60
+ }
61
+ let bytes;
62
+ try {
63
+ // walk lists a folder only when it cannot be read; a pipe or device is never read
64
+ if (!own && lstatSync(path).isDirectory())
65
+ throw new Error('it is a folder that cannot be read');
66
+ if (!own && !statSync(path).isFile())
67
+ continue;
68
+ bytes = own ? sourceBytes : readFileSync(path);
69
+ }
70
+ catch (e) {
71
+ // a link to nothing names no task
72
+ if (e.code === 'ENOENT')
73
+ continue;
74
+ throw new Error(`${path} cannot be read (${e.message}), so whether its blocked-by names ${source} is unknown, and renaming could leave that reference stale: ` +
75
+ `make it readable, or move it out of the folder, then rerun; \`ls -ld ${path}\` shows it.`);
76
+ }
77
+ const before = bytes.toString('utf8');
78
+ const read = readTask(basename(path), before);
79
+ // what could not be read may be a blocked-by that names the task
80
+ if (read.problems.length) {
81
+ throw new Error(`${path} could not be fully read, so whether its blocked-by names ${source} is unknown, and renaming could leave that reference stale: ` +
82
+ `${read.problems.join('; ')}. Then rerun.`);
83
+ }
84
+ let changed = false;
85
+ const nexts = read.fields['blocked-by'].map((ref) => {
86
+ const hit = resolveRef(root, folder, tasks, path, ref);
87
+ const named = hit?.live === source;
88
+ if (!named && !(own && moves))
89
+ return ref;
90
+ changed = true;
91
+ // a reference found nowhere keeps naming the path it named
92
+ const at = named ? dest : (hit?.target ?? resolve(dirname(path), ref));
93
+ return relative(dirname(own ? dest : path), at);
94
+ });
95
+ refs.push(...read.fields['blocked-by'].map((ref, i) => ({ path, ref, next: nexts[i] ?? ref })));
96
+ if (!changed)
97
+ continue;
98
+ if (!Buffer.from(before).equals(bytes)) {
99
+ throw new Error(`${path} is not UTF-8 text, so rewriting its blocked-by would change other bytes in it: ` +
100
+ `convert it to UTF-8, e.g. with \`iconv\`, then rerun.`);
101
+ }
102
+ if (link) {
103
+ throw new Error(`${path} names ${source} in blocked-by, but is a link to ${link}, and rename writes only the task files themselves: ` +
104
+ `replace the link with its file, \`rm ${path} && cp ${link} ${path}\`, or take the task out of its blocked-by, then rerun.`);
105
+ }
106
+ const next = withField(before, 'blocked-by', flowList(nexts));
107
+ const back = readTask(basename(own ? dest : path), next);
108
+ const same = (r) => JSON.stringify({ ...r.fields, 'blocked-by': [] });
109
+ if (back.problems.length ||
110
+ same(back) !== same(read) ||
111
+ JSON.stringify(back.fields['blocked-by']) !== JSON.stringify(nexts)) {
112
+ throw new Error(`blocked-by in ${path}, written as ${flowList(nexts)}, would not read back as written, so nothing is renamed: ` +
113
+ `write it as \`blocked-by: [<path>, ...]\` on one line by hand, then rerun`);
114
+ }
115
+ writes.set(own ? dest : path, [before, next]);
116
+ }
117
+ // the one promise: every reference names, after the move, the file it named before, the
118
+ // moved file now at its new path; the new name may shadow what a fallback found
119
+ const after = new Set([...tasks].filter((p) => p !== source).concat(dest));
120
+ for (const { path, ref, next } of refs) {
121
+ const was = resolveRef(root, folder, tasks, path, ref)?.file;
122
+ const moved = path === source ? dest : path;
123
+ const now = resolveRef(root, folder, after, moved, next)?.file;
124
+ if ((was === source ? dest : was) !== now) {
125
+ throw new Error(`${path} has blocked-by ${ref}, which names ${was ?? 'no task'}, but after this rename ${next === ref ? 'it' : `its rewrite ${next}`} would name ${now ?? 'no task'}, ` +
126
+ `and a rename must not change what a reference names: run \`ken task rename ${source} <another path>\`` +
127
+ `${was ? `, or write that reference as ${relative(dirname(path), was)}, the file it means, then rerun` : ''}.`);
128
+ }
129
+ }
130
+ // a file of another extension becomes a .md, which reads front matter its old name did not
131
+ const as = (name) => JSON.stringify(readTask(name, text).fields);
132
+ const read = readTask(basename(dest), text);
133
+ if (!writes.has(dest) && (read.problems.length || as(basename(dest)) !== as(basename(source)))) {
134
+ throw new Error(`${source} would read differently as ${basename(dest)}: front matter, which only a .md has, would start to count, ` +
135
+ `and rename keeps a task as it reads. Make it a .md where it is, \`mv ${source} ${source.replace(/(.)\.[^./]*$/, '$1')}.md\`, ` +
136
+ `fix what \`ken task list\` then says of it, then rename that.`);
137
+ }
138
+ mkdirSync(dirname(dest), { recursive: true });
139
+ let fd;
140
+ try {
141
+ fd = openSync(dest, 'wx', stat.mode & 0o777);
142
+ }
143
+ catch (e) {
144
+ if (e.code !== 'EEXIST')
145
+ throw e;
146
+ throw new Error(`${dest} exists, made since this rename looked: read it with \`cat ${dest}\`, or run \`ken task rename ${source} <another path>\`.`);
147
+ }
148
+ // from here the new file is this rename's own, so a failure removes it
149
+ const done = [];
150
+ try {
151
+ try {
152
+ writeFileSync(fd, writes.get(dest)?.[1] ?? sourceBytes);
153
+ }
154
+ finally {
155
+ closeSync(fd);
156
+ }
157
+ // a move keeps the file's age, which counts from its mtime when nothing else dates it
158
+ utimesSync(dest, stat.atime, stat.mtime);
159
+ for (const [file, [, next]] of writes) {
160
+ if (file === dest)
161
+ continue;
162
+ replaceFile(file, next);
163
+ done.push(file);
164
+ }
165
+ unlinkSync(source);
166
+ }
167
+ catch (e) {
168
+ const failed = e.message;
169
+ // undone, so every reference names the old file again, which still exists
170
+ try {
171
+ for (const file of done)
172
+ replaceFile(file, writes.get(file)?.[0] ?? '');
173
+ unlinkSync(dest);
174
+ }
175
+ catch (undo) {
176
+ throw new Error(`${failed}; undoing it failed too (${undo.message}), so ${source} and ${dest} both exist, each reference resolving to one of them: ` +
177
+ `finish the move by hand, rewriting blocked-by to name ${dest} in ${[...writes.keys()].filter((f) => f !== dest).join(', ')} where it does not yet, then \`rm ${source}\`.`);
178
+ }
179
+ throw new Error(`${failed}; so nothing is renamed, every file as it was: fix what failed, then rerun \`ken task rename ${source} ${to}\`.`);
180
+ }
181
+ return target;
182
+ }
183
+ /** The file the link at `path` leads to, as the disk names it; undefined for no link, or a link to nothing. */
184
+ function linkTo(path) {
185
+ try {
186
+ return lstatSync(path).isSymbolicLink() ? realpathSync.native(path) : undefined;
187
+ }
188
+ catch {
189
+ return undefined;
190
+ }
191
+ }
@@ -0,0 +1,139 @@
1
+ import { lstatSync, readdirSync, realpathSync, statSync } from 'node:fs';
2
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve } from 'node:path';
3
+ /**
4
+ * `path` as the disk names it, which on a case-insensitive disk may differ in case; the part
5
+ * that does not exist is kept as written, under the real path of the part that does.
6
+ */
7
+ export function real(path) {
8
+ try {
9
+ return realpathSync.native(path);
10
+ }
11
+ catch {
12
+ const parent = dirname(path);
13
+ return parent === path ? path : join(real(parent), basename(path));
14
+ }
15
+ }
16
+ const literal = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
17
+ /** The archived file for `rel`, a path relative to the folder: `.archive/<rel>`, at any numeric suffix. */
18
+ export function archived(folder, rel) {
19
+ const dir = join(folder, '.archive', dirname(rel));
20
+ const ext = extname(rel);
21
+ const stem = basename(rel, ext);
22
+ const name = new RegExp(`^${literal(stem)}(-\\d+)?${literal(ext)}$`);
23
+ let entries;
24
+ try {
25
+ entries = readdirSync(dir);
26
+ }
27
+ catch {
28
+ return undefined;
29
+ }
30
+ return [basename(rel), ...entries.filter((e) => name.test(e))]
31
+ .map((e) => join(dir, e))
32
+ .find((path) => statSync(path, { throwIfNoEntry: false })?.isFile());
33
+ }
34
+ const isTaskName = (name) => name !== 'README.md' && !name.startsWith('.');
35
+ /** The task files in `dir` other than README.md and dot entries; none if it cannot be read. */
36
+ function files(dir) {
37
+ try {
38
+ return readdirSync(dir, { withFileTypes: true })
39
+ .filter((e) => !e.isDirectory() && isTaskName(e.name))
40
+ .map((e) => e.name);
41
+ }
42
+ catch {
43
+ return [];
44
+ }
45
+ }
46
+ /** `name` in `dir` stands for each of `names`; guessing would act on the wrong task. */
47
+ const ambiguous = (dir, name, names) => new Error(`${join(dir, name)} names ${names.length} files, ${names.join(', ')}, so which task is meant is unclear: ` +
48
+ `name one with its extension, e.g. ${join(dir, names[0] ?? '')}`);
49
+ /**
50
+ * The file in `dir` that `name` names: the entry itself, else the one task file whose stem it
51
+ * is. More than one such file is refused, naming them, since guessing would act on the wrong task.
52
+ */
53
+ function named(dir, name) {
54
+ const exact = join(dir, name);
55
+ if (lstatSync(exact, { throwIfNoEntry: false })?.isDirectory() === false)
56
+ return exact;
57
+ const entries = files(dir).filter((e) => e.replace(/(.)\.[^.]*$/, '$1') === name);
58
+ if (entries.length > 1)
59
+ throw ambiguous(dir, name, entries);
60
+ return entries[0] && join(dir, entries[0]);
61
+ }
62
+ /** The task at `rel`, relative to the folder: live, else archived; a path into `.archive/` looks only there. */
63
+ function lookup(folder, rel) {
64
+ const inArchive = rel.startsWith('.archive/');
65
+ const name = inArchive ? rel.slice('.archive/'.length) : rel;
66
+ if (!name.split('/').every(isTaskName))
67
+ return undefined;
68
+ if (!inArchive) {
69
+ const live = named(join(folder, dirname(name)), basename(name));
70
+ if (live)
71
+ return live;
72
+ }
73
+ const found = archived(folder, name);
74
+ if (found)
75
+ return found;
76
+ // without its extension: the one extension archived under that name, at any numeric suffix
77
+ const dir = join(folder, '.archive', dirname(name));
78
+ const base = basename(name);
79
+ const stem = new RegExp(`^${literal(base)}(?:-\\d+)?(\\.[^.]+)$`);
80
+ const exts = [...new Set(files(dir).flatMap((e) => stem.exec(e)?.[1] ?? []))];
81
+ if (exts.length > 1)
82
+ throw ambiguous(dir, base, exts.map((ext) => base + ext));
83
+ return exts[0] && archived(folder, name + exts[0]);
84
+ }
85
+ /**
86
+ * Where `arg` leads in the task folder, relative to it: read as a path absolute, from `cwd`,
87
+ * from `root` and from the folder, in that order, keeping each reading that is in the folder.
88
+ */
89
+ export function inFolder(root, folder, cwd, arg) {
90
+ return [...new Set([resolve(cwd, arg), resolve(root, arg), resolve(folder, arg)])]
91
+ .map((target) => relative(folder, join(real(dirname(target)), basename(target))))
92
+ .filter((rel) => rel && rel !== '..' && !rel.startsWith('../') && !isAbsolute(rel));
93
+ }
94
+ /** `arg` reaches no path in the task folder `folder`, so it can name no task. */
95
+ export const outside = (root, folder, arg) => new Error(`${arg} is not in the task folder ${folder}, nor its .archive/, so it is no task: ` +
96
+ `name a file there, absolute, or from here, the root ${root} or the folder. Run \`ken task list\` to see the tasks.`);
97
+ /**
98
+ * The absolute path of the task `arg` names, live or archived: any path that reaches the
99
+ * file, absolute, from `cwd`, from `root` or from the folder, with or without its extension.
100
+ * The file must be in `configured`, the task folder, or its `.archive/`; anything else is
101
+ * refused, naming it.
102
+ */
103
+ export function resolveTask(root, configured, cwd, arg) {
104
+ const folder = real(configured);
105
+ const rels = inFolder(root, folder, cwd, arg);
106
+ if (!rels.length)
107
+ throw outside(root, folder, arg);
108
+ for (const rel of rels) {
109
+ const found = lookup(folder, rel);
110
+ if (found)
111
+ return found;
112
+ }
113
+ throw new Error(`No task ${arg} in ${folder} or its .archive/, read as a path from here, from the root ${root} and from the folder, ` +
114
+ 'with or without its extension. Run `ken task list` to see the tasks.');
115
+ }
116
+ /**
117
+ * The task file `file`, then the README.md of each folder from its own up to `root`, root
118
+ * last, the missing ones skipped. An archived task reads the chain of the folder it was
119
+ * archived from, whose README.md holds its conventions; a task folder outside the root goes
120
+ * up to the folder, then the root.
121
+ */
122
+ export function readmeChain(root, configured, file) {
123
+ const folder = real(configured);
124
+ const top = real(root);
125
+ const rel = relative(folder, dirname(file)).replace(/^\.archive(\/|$)/, '');
126
+ const up = (from, to) => {
127
+ const dirs = [from];
128
+ for (let dir = from; dir !== to && dir !== dirname(dir); dir = dirname(dir))
129
+ dirs.push(dirname(dir));
130
+ return dirs;
131
+ };
132
+ const fromTop = relative(top, folder);
133
+ const inRoot = fromTop !== '..' && !fromTop.startsWith('../');
134
+ const dirs = inRoot ? up(join(folder, rel), top) : [...up(join(folder, rel), folder), top];
135
+ const readmes = dirs
136
+ .map((dir) => join(dir, 'README.md'))
137
+ .filter((path) => statSync(path, { throwIfNoEntry: false })?.isFile());
138
+ return [file, ...readmes];
139
+ }
package/dist/set.js ADDED
@@ -0,0 +1,196 @@
1
+ import { readFileSync, realpathSync, renameSync, statSync, writeFileSync } from 'node:fs';
2
+ import { basename, dirname, join, relative } from 'node:path';
3
+ import { isMap, isNode, isScalar, parse, parseDocument } from 'yaml';
4
+ import { isKey } from "./add.js";
5
+ import { branchOf, repos } from "./git.js";
6
+ import { isDate, readTask } from "./read.js";
7
+ import { real, resolveTask } from "./resolve.js";
8
+ /** The fields `set` writes, in the order its messages name them. */
9
+ export const FIELDS = ['status', 'repo', 'blocked-by', 'scheduled', 'due'];
10
+ const STATUSES = ['todo', 'done', 'wontfix'];
11
+ const ALIASES = ['blocked_by', 'blockedBy', 'depends_on', 'depends-on'];
12
+ const FENCE = /^---\s*$/;
13
+ /**
14
+ * `text` with the front matter line of `field` set to `value`, or removed when `value` is
15
+ * undefined: only that line changes, keeping the space after its colon and a trailing
16
+ * comment, and the lines that continue its value go with it. A missing line is appended at
17
+ * the end of the front matter; a file with none gets one at the top. An alias of
18
+ * `blocked-by` is its line, written back as `blocked-by`. Every other byte stays, the line
19
+ * endings included. Throws on front matter with no closing `---`.
20
+ */
21
+ export function withField(text, field, value) {
22
+ const bom = text.startsWith('\uFEFF') ? '\uFEFF' : '';
23
+ const body = text.slice(bom.length);
24
+ // each line with its own ending, split as the reader splits, so mixed endings survive
25
+ const lines = body.match(/[^\n]*\n|[^\n]+$/g) ?? [];
26
+ const bare = (l = '') => l.replace(/\r?\n$/, '');
27
+ const ending = (l = '') => /\r?\n$/.exec(l)?.[0] ?? '\n';
28
+ const line = (indent, eol) => value === undefined ? [] : [`${indent}${field}: ${value}${eol}`];
29
+ if (!FENCE.test(bare(lines[0]))) {
30
+ const eol = ending(lines[0]);
31
+ return value === undefined ? text : `${bom}---${eol}${line('', eol).join('')}---${eol}${body}`;
32
+ }
33
+ const end = lines.findIndex((l, i) => i > 0 && FENCE.test(bare(l)));
34
+ if (end < 0) {
35
+ throw new Error('its front matter has no closing `---`, so a field written into it would not read back: add a `---` line after the last field');
36
+ }
37
+ const keys = field === 'blocked-by' ? [field, ...ALIASES] : [field];
38
+ const { found, comment, indent } = span(lines.slice(1, end).map(bare).join('\n'), keys);
39
+ if (!found) {
40
+ lines.splice(end, 0, ...line(indent, ending(lines[end - 1])));
41
+ return bom + lines.join('');
42
+ }
43
+ const [at, next] = [found[0] + 1, found[1] + 1];
44
+ const old = bare(lines[at]);
45
+ const gap = /^[ \t]*/.exec(old.slice(old.indexOf(':') + 1))?.[0] || ' ';
46
+ const set = `${indent}${field}:${gap}${value}${comment ?? ''}${ending(lines[next - 1])}`;
47
+ lines.splice(at, next - at, ...(value === undefined ? [] : [set]));
48
+ return bom + lines.join('');
49
+ }
50
+ /**
51
+ * The lines of `source`, front matter, that hold the first of `keys`, as YAML reads the key
52
+ * (quoted or not): from the key's line to past the line its value ends on, so a value over
53
+ * several lines, with blank lines or comments between its items, goes whole; the comment
54
+ * that ends the value's last line, else its key's line, to keep; and the indentation of the
55
+ * mapping's keys, for a line written into it.
56
+ */
57
+ function span(source, keys) {
58
+ const doc = parseDocument(source);
59
+ const [error] = doc.errors;
60
+ if (error)
61
+ throw new Error(`its front matter is not YAML (${error.message.split('\n')[0]}): fix it`);
62
+ if (!isMap(doc.contents))
63
+ return { indent: '' };
64
+ if (doc.contents.flow) {
65
+ throw new Error('its front matter is one `{...}` mapping, so one field cannot be rewritten without the others: write each field as `field: value` on a line of its own');
66
+ }
67
+ const line = (offset) => source.slice(0, offset).split('\n').length - 1;
68
+ const start = doc.contents.range?.[0] ?? 0;
69
+ const indent = source.slice(source.lastIndexOf('\n', start - 1) + 1, start);
70
+ for (const pair of doc.contents.items) {
71
+ const key = pair.key;
72
+ if (!isScalar(key) || !keys.includes(String(key.value)) || !key.range)
73
+ continue;
74
+ const value = isNode(pair.value) ? pair.value.range : undefined;
75
+ const last = Math.max(key.range[1], value?.[1] ?? 0);
76
+ // what follows an offset on its line, when that is a comment, after the colon and a
77
+ // block scalar's header if any
78
+ const tail = (offset) => /^(?::[ \t]*(?:[|>][-+0-9]*)?)?([ \t]+#.*)?$/.exec(source.slice(offset).split('\n')[0] ?? '')?.[1];
79
+ const comment = tail(last) ?? tail(key.range[1]);
80
+ return {
81
+ found: [line(key.range[0]), line(Math.max(last - 1, key.range[0])) + 1],
82
+ comment,
83
+ indent
84
+ };
85
+ }
86
+ return { indent };
87
+ }
88
+ /** `items` as a one-line YAML list, each item plain when YAML reads it back as written. */
89
+ export function flowList(items) {
90
+ const plain = `[${items.join(', ')}]`;
91
+ try {
92
+ if (JSON.stringify(parse(plain)) === JSON.stringify(items))
93
+ return plain;
94
+ }
95
+ catch { }
96
+ return `[${items.map((item) => JSON.stringify(item)).join(', ')}]`;
97
+ }
98
+ /** `value` checked as `field` takes it, or a refusal that names the format. */
99
+ function check(field, value) {
100
+ const refuse = (format, example) => new Error(`${field} ${JSON.stringify(value)} is not ${format}, so it would not read as one: run \`ken task set <task> ${field} ${example}\`, ` +
101
+ `or \`ken task set <task> ${field} ''\` to remove the line`);
102
+ if (field === 'status' && !STATUSES.includes(value)) {
103
+ throw refuse(`one of ${STATUSES.join(', ')}`, 'done');
104
+ }
105
+ if ((field === 'scheduled' || field === 'due') && !isDate(value)) {
106
+ throw refuse('a date, YYYY-MM-DD', '2026-11-30');
107
+ }
108
+ if (field === 'repo' && !isKey(value)) {
109
+ throw refuse('a repo key, <host>/<owner>/<repo> in lowercase', 'github.com/acme/join-web');
110
+ }
111
+ }
112
+ /**
113
+ * Refuse to call the task at `path` done while its branch exists in the repo `key` and is
114
+ * not an ancestor of the default branch: done means landed (decision 7).
115
+ */
116
+ function refuseUnlanded(folder, path, key) {
117
+ const repo = repos()(key);
118
+ const name = branchOf(real(folder), path);
119
+ if (!repo?.exists(name) || repo.landed(name))
120
+ return;
121
+ const { clone } = repo;
122
+ throw new Error(`${path} is not landed: its branch ${name} of ${key} is not on the default branch, and done means landed, ` +
123
+ 'since the tasks it blocks wait for its code. Land it as a rebase onto the default branch, then a merge that keeps the commits, ' +
124
+ `\`git -C ${clone} merge --no-ff ${name}\`; a squash merge leaves its commits off the default branch, so it is still refused. ` +
125
+ `\`git -C ${clone} log --oneline HEAD..${name}\` lists the commits not landed yet. Then rerun.`);
126
+ }
127
+ /**
128
+ * `ken task set`: rewrite the line of `field` in the task `arg` names to `value`, an empty
129
+ * value removing it, and return the file's path. `blocked-by` takes comma-separated paths
130
+ * as typed from `cwd` and writes each relative to the file; `status done` or `wontfix` also
131
+ * writes `closed: <today>`, `status todo` or none removes it; `status done` is refused while
132
+ * the task's branch is not landed. The new text must read back as
133
+ * set, and is written beside the file, then renamed over it.
134
+ */
135
+ export function setTask(root, folder, cwd, [arg, field, value], today) {
136
+ if (!FIELDS.includes(field)) {
137
+ throw new Error(`${JSON.stringify(field)} is not a field ken task set writes; it writes ${FIELDS.join(', ')}. ` +
138
+ 'Run `ken task set --help` for the formats.');
139
+ }
140
+ if (value && field !== 'blocked-by')
141
+ check(field, value);
142
+ const path = resolveTask(root, folder, cwd, arg);
143
+ if (!path.endsWith('.md')) {
144
+ throw new Error(`${path} is not a .md, so it has no front matter to hold ${field}: make it one, ` +
145
+ `\`mv "${path}" "${path.replace(/(.)\.[^./]*$/, '$1')}.md"\`, then rerun; a blocked-by that names it must name the .md too`);
146
+ }
147
+ const file = realpathSync(path);
148
+ const stat = statSync(file);
149
+ if (!stat.isFile()) {
150
+ throw new Error(`${path} is not a regular file, so it cannot be set: \`ls -ld ${path}\` shows what it is`);
151
+ }
152
+ const text = readFileSync(file, 'utf8');
153
+ const { fields: before, problems } = readTask(basename(path), text);
154
+ if (problems.length) {
155
+ throw new Error(`${path} could not be fully read, so a field written into it might not read back: ${problems.join('; ')}. Then rerun.`);
156
+ }
157
+ if (field === 'status' && value === 'done' && before.repo)
158
+ refuseUnlanded(folder, path, before.repo);
159
+ const refs = (field === 'blocked-by' ? value : '')
160
+ .split(',')
161
+ .map((ref) => ref.trim())
162
+ .filter(Boolean)
163
+ .map((ref) => relative(dirname(path), resolveTask(root, folder, cwd, ref)));
164
+ const written = !value ? undefined : field === 'blocked-by' ? flowList(refs) : value;
165
+ const closes = value === 'done' || value === 'wontfix';
166
+ let next;
167
+ try {
168
+ next = withField(text, field, written);
169
+ if (field === 'status')
170
+ next = withField(next, 'closed', closes ? today : undefined);
171
+ }
172
+ catch (e) {
173
+ throw new Error(`${path} cannot be set: ${e.message}, then rerun`);
174
+ }
175
+ const { fields: back, problems: after } = readTask(basename(path), next);
176
+ // every field but the one set, and closed with status, reads back as it was
177
+ const others = (fields) => JSON.stringify(Object.entries(fields)
178
+ .filter(([k]) => k !== field && !(field === 'status' && k === 'closed'))
179
+ .sort(([a], [b]) => (a < b ? -1 : 1)));
180
+ const expected = field === 'blocked-by' ? refs : value || (field === 'status' ? 'todo' : undefined);
181
+ if (after.length ||
182
+ others(back) !== others(before) ||
183
+ JSON.stringify(back[field]) !== JSON.stringify(expected) ||
184
+ (field === 'status' && back.closed !== (closes ? today : undefined))) {
185
+ throw new Error(`${field} written as ${JSON.stringify(written)} would not read back as set, so ${path} is left as it was: ` +
186
+ `edit the line by hand, then run \`ken task list\` to check it`);
187
+ }
188
+ replaceFile(file, next);
189
+ return path;
190
+ }
191
+ /** Write `text` beside `file`, with its mode, then rename it over `file`, so no reader sees half of it. */
192
+ export function replaceFile(file, text) {
193
+ const temp = join(dirname(file), `.${basename(file)}.${process.pid}.tmp`);
194
+ writeFileSync(temp, text, { mode: statSync(file).mode & 0o777 });
195
+ renameSync(temp, file);
196
+ }
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "@unclex/ken-task",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Plain-text tasks in one folder, one file per task, a git worktree per task. Reached as `ken task`.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/xiaoxinghu/ken.git",
10
+ "directory": "packages/ken-task"
11
+ },
12
+ "homepage": "https://unclex.net",
13
+ "bin": {
14
+ "ken-task": "./dist/cli.js"
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "!dist/testing.js"
19
+ ],
20
+ "engines": {
21
+ "node": ">=24"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "dependencies": {
27
+ "yaml": "^2.9.1"
28
+ },
29
+ "scripts": {}
6
30
  }