@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/LICENSE +21 -0
- package/README.md +5 -2
- package/dist/add.js +105 -0
- package/dist/archive.js +140 -0
- package/dist/claim.js +106 -0
- package/dist/cli.js +529 -0
- package/dist/finish.js +47 -0
- package/dist/git.js +88 -0
- package/dist/lint.js +115 -0
- package/dist/list.js +246 -0
- package/dist/read.js +137 -0
- package/dist/rename.js +191 -0
- package/dist/resolve.js +139 -0
- package/dist/set.js +196 -0
- package/package.json +27 -3
package/dist/lint.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { readFileSync, realpathSync, statSync } from 'node:fs';
|
|
2
|
+
import { basename, dirname, extname, relative } from 'node:path';
|
|
3
|
+
import { parse } from 'yaml';
|
|
4
|
+
import { load, localDate, resolveRef, since, walk } from "./list.js";
|
|
5
|
+
import { readTask } from "./read.js";
|
|
6
|
+
import { real } from "./resolve.js";
|
|
7
|
+
import { flowList, replaceFile, withField } from "./set.js";
|
|
8
|
+
/**
|
|
9
|
+
* `ken task lint`: every deviation from the canonical shape in the task folder, one line
|
|
10
|
+
* each, the path first. With `fix`, the lossless upgrades of each file are written through
|
|
11
|
+
* `set`'s one-line writer, all or none, and printed as done. `deviates` is whether any is
|
|
12
|
+
* left.
|
|
13
|
+
*/
|
|
14
|
+
export function lintTasks(root, configured, fix) {
|
|
15
|
+
const folder = real(configured);
|
|
16
|
+
const paths = walk(folder);
|
|
17
|
+
const live = new Set(paths);
|
|
18
|
+
const created = since(root, folder);
|
|
19
|
+
const lines = [];
|
|
20
|
+
let deviates = false;
|
|
21
|
+
for (const path of paths) {
|
|
22
|
+
const read = load(path);
|
|
23
|
+
const found = deviations(path, read);
|
|
24
|
+
const fixes = found.filter((d) => d.set);
|
|
25
|
+
const refused = fix && fixes.length ? upgrade(path, read, fixes) : undefined;
|
|
26
|
+
if (refused)
|
|
27
|
+
lines.push(`${path}: ${refused}`);
|
|
28
|
+
for (const d of found) {
|
|
29
|
+
const line = d.set?.join(': ');
|
|
30
|
+
if (fix && line && !refused)
|
|
31
|
+
lines.push(`${path}: ${d.what}: wrote \`${line}\``);
|
|
32
|
+
else {
|
|
33
|
+
deviates = true;
|
|
34
|
+
lines.push(`${path}: ${d.what}${d.upgrade ? `: ${d.upgrade}` : ''}`);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return { lines, deviates };
|
|
39
|
+
function deviations(path, read) {
|
|
40
|
+
const found = [...read.problems, ...read.flags].map((what) => ({ what }));
|
|
41
|
+
const ext = extname(path);
|
|
42
|
+
if (ext !== '.md') {
|
|
43
|
+
const md = `${ext ? path.slice(0, -ext.length) : path}.md`;
|
|
44
|
+
found.push({
|
|
45
|
+
what: `${ext ? `a ${ext}` : 'a file with no extension'} has no front matter, so every field is its default`,
|
|
46
|
+
upgrade: `make it a .md, \`mv "${path}" "${md}"\`, and name the .md in any blocked-by that names it`
|
|
47
|
+
});
|
|
48
|
+
return found;
|
|
49
|
+
}
|
|
50
|
+
// nothing can be written into a file that is not fully read, or not closed
|
|
51
|
+
if (read.problems.length || !read.written)
|
|
52
|
+
return found;
|
|
53
|
+
const { fields } = read;
|
|
54
|
+
const lossless = (what, field, value) => ({
|
|
55
|
+
what,
|
|
56
|
+
upgrade: `\`ken task lint --fix\` writes \`${field}: ${value}\``,
|
|
57
|
+
set: [field, value]
|
|
58
|
+
});
|
|
59
|
+
if (!read.written.includes('status')) {
|
|
60
|
+
found.push(lossless('no status line, so it reads as todo', 'status', 'todo'));
|
|
61
|
+
}
|
|
62
|
+
if (!fields.created) {
|
|
63
|
+
const [date, by] = created(path);
|
|
64
|
+
found.push(lossless(`no created line, so it is taken from ${by}`, 'created', date));
|
|
65
|
+
}
|
|
66
|
+
if ((fields.status === 'done' || fields.status === 'wontfix') && !fields.closed) {
|
|
67
|
+
const date = localDate(statSync(path).mtime);
|
|
68
|
+
found.push(lossless(`status ${fields.status} with no closed line; its mtime says when`, 'closed', date));
|
|
69
|
+
}
|
|
70
|
+
const reshape = [...read.reshape];
|
|
71
|
+
const refs = fields['blocked-by'].map((ref) => {
|
|
72
|
+
const to = resolveRef(root, folder, live, path, ref);
|
|
73
|
+
if (!to) {
|
|
74
|
+
found.push({
|
|
75
|
+
what: `blocked-by ${ref} is in neither the folder nor its .archive/, so it blocks the task`,
|
|
76
|
+
upgrade: `name the task it waits on, \`ken task set ${path} blocked-by <tasks>\`, or remove it`
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
if (!to?.from)
|
|
80
|
+
return ref;
|
|
81
|
+
reshape.push(`blocked-by ${ref} resolves from ${to.from}, not from this file`);
|
|
82
|
+
return relative(dirname(path), to.target);
|
|
83
|
+
});
|
|
84
|
+
if (reshape.length)
|
|
85
|
+
found.push(lossless(reshape.join('; '), 'blocked-by', flowList(refs)));
|
|
86
|
+
return found;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Write `fixes` into the file at `path`, as read in `read`: every other field must read back
|
|
91
|
+
* as it was and the file in the canonical shape, or nothing is written and the reason is
|
|
92
|
+
* returned.
|
|
93
|
+
*/
|
|
94
|
+
function upgrade(path, read, fixes) {
|
|
95
|
+
const file = realpathSync(path);
|
|
96
|
+
let next = readFileSync(file, 'utf8');
|
|
97
|
+
try {
|
|
98
|
+
for (const { set } of fixes)
|
|
99
|
+
if (set)
|
|
100
|
+
next = withField(next, ...set);
|
|
101
|
+
}
|
|
102
|
+
catch (e) {
|
|
103
|
+
return `its upgrades cannot be written (${e.message}), so it is left as it was; make them by hand`;
|
|
104
|
+
}
|
|
105
|
+
const back = readTask(basename(path), next);
|
|
106
|
+
const expected = {
|
|
107
|
+
...read.fields,
|
|
108
|
+
...Object.fromEntries(fixes.flatMap(({ set }) => (set ? [[set[0], parse(set[1])]] : [])))
|
|
109
|
+
};
|
|
110
|
+
const sorted = (fields) => JSON.stringify(Object.entries(fields).sort(([a], [b]) => (a < b ? -1 : 1)));
|
|
111
|
+
if (back.problems.length || back.reshape.length || sorted(back.fields) !== sorted(expected)) {
|
|
112
|
+
return 'its upgrades would not read back as written, so it is left as it was; make them by hand, then run `ken task lint`';
|
|
113
|
+
}
|
|
114
|
+
replaceFile(file, next);
|
|
115
|
+
}
|
package/dist/list.js
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, lstatSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
|
3
|
+
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
|
4
|
+
import { branchOf, codePath, dirty, repos } from "./git.js";
|
|
5
|
+
import { CANONICAL, readTask } from "./read.js";
|
|
6
|
+
import { archived, real } from "./resolve.js";
|
|
7
|
+
/** `date` as `YYYY-MM-DD`, local. */
|
|
8
|
+
export const localDate = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
|
|
9
|
+
/**
|
|
10
|
+
* Every task under `folder` by absolute path: every file or symlink except README.md and
|
|
11
|
+
* dot entries, told apart by what `readdir` says, so nothing is looked at twice. A folder
|
|
12
|
+
* that cannot be read is itself an entry, which then fails to read as a task.
|
|
13
|
+
*/
|
|
14
|
+
export function walk(folder) {
|
|
15
|
+
let entries;
|
|
16
|
+
try {
|
|
17
|
+
entries = readdirSync(folder, { withFileTypes: true });
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return [folder];
|
|
21
|
+
}
|
|
22
|
+
return entries.flatMap((entry) => {
|
|
23
|
+
const path = join(folder, entry.name);
|
|
24
|
+
if (entry.name.startsWith('.') || entry.name === 'README.md')
|
|
25
|
+
return [];
|
|
26
|
+
if (entry.isDirectory())
|
|
27
|
+
return walk(path);
|
|
28
|
+
return entry.isFile() || entry.isSymbolicLink() ? [path] : [];
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
/** The task at `path`; whatever stops it being read makes it a problem, with the fix. */
|
|
32
|
+
export function load(path) {
|
|
33
|
+
try {
|
|
34
|
+
// a link may lead to a folder, a pipe or a device, which a read would fail on, block on
|
|
35
|
+
// or never finish
|
|
36
|
+
if (!statSync(path).isFile())
|
|
37
|
+
throw new Error('it is not a regular file');
|
|
38
|
+
return readTask(basename(path), readFileSync(path, 'utf8'));
|
|
39
|
+
}
|
|
40
|
+
catch (e) {
|
|
41
|
+
const read = readTask(basename(path), '');
|
|
42
|
+
read.problems.push(`it could not be read (${e.message}): make it a readable file, or remove it; \`ls -ld ${path}\` shows it`);
|
|
43
|
+
return read;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const isOpen = (read) => read.problems.length > 0 || (read.fields.status !== 'done' && read.fields.status !== 'wontfix');
|
|
47
|
+
/** When the root's git added each file under `folder`, by absolute path; empty outside git. */
|
|
48
|
+
function addedDates(root, folder) {
|
|
49
|
+
const dates = new Map();
|
|
50
|
+
const r = spawnSync('git', [
|
|
51
|
+
...['-c', 'core.quotePath=false', 'log', '--no-renames', '--diff-filter=A', '--relative'],
|
|
52
|
+
...['--name-only', '--format=%x00%as', '--', folder]
|
|
53
|
+
], { cwd: root, encoding: 'utf8' });
|
|
54
|
+
if (r.status !== 0)
|
|
55
|
+
return dates;
|
|
56
|
+
let date = '';
|
|
57
|
+
// newest commit first, so the last date set for a path is the first time it was added
|
|
58
|
+
for (const line of r.stdout.split('\n')) {
|
|
59
|
+
if (line.startsWith('\0'))
|
|
60
|
+
date = line.slice(1);
|
|
61
|
+
else if (line)
|
|
62
|
+
dates.set(resolve(root, line), date);
|
|
63
|
+
}
|
|
64
|
+
return dates;
|
|
65
|
+
}
|
|
66
|
+
const days = (from, to) => Math.round((Date.parse(to) - Date.parse(from)) / 864e5);
|
|
67
|
+
export function since(root, folder) {
|
|
68
|
+
let added;
|
|
69
|
+
return (path, created) => {
|
|
70
|
+
if (created)
|
|
71
|
+
return [created, 'created'];
|
|
72
|
+
added ??= addedDates(root, folder);
|
|
73
|
+
const git = added.get(path);
|
|
74
|
+
return git ? [git, 'the date git added it'] : [localDate(lstatSync(path).mtime), 'its mtime'];
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Where `ref`, written in the file at `path` in `folder`, a folder of `root`, leads:
|
|
79
|
+
* `target`, its live task, one of `live`, unless it is archived, `file` the file it names,
|
|
80
|
+
* live or archived, and `from` what it resolved from when that is not the file; undefined
|
|
81
|
+
* if nowhere.
|
|
82
|
+
*/
|
|
83
|
+
export function resolveRef(root, folder, live, path, ref) {
|
|
84
|
+
for (const [base, from] of [
|
|
85
|
+
[dirname(path), ''],
|
|
86
|
+
[folder, 'the folder'],
|
|
87
|
+
[root, 'the root']
|
|
88
|
+
]) {
|
|
89
|
+
const target = resolve(base, ref);
|
|
90
|
+
const rel = relative(folder, target);
|
|
91
|
+
if (rel === '..' || rel.startsWith('../') || isAbsolute(rel))
|
|
92
|
+
continue;
|
|
93
|
+
// a reference into the archive names the archived file, at any suffix, as a live one would
|
|
94
|
+
if (rel.startsWith('.archive/')) {
|
|
95
|
+
const file = archived(folder, rel.slice('.archive/'.length));
|
|
96
|
+
if (file)
|
|
97
|
+
return { target, file, from };
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
// the path as written, else as the disk names it, which may differ in case
|
|
101
|
+
const found = live.has(target) ? target : real(target);
|
|
102
|
+
if (live.has(found))
|
|
103
|
+
return { target, live: found, file: found, from };
|
|
104
|
+
const file = archived(folder, rel);
|
|
105
|
+
if (file)
|
|
106
|
+
return { target, file, from };
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* The ready tasks in `configured` as of `today`, in the order to take them: earliest `due`,
|
|
111
|
+
* then earliest created, then path, so two runs agree.
|
|
112
|
+
*/
|
|
113
|
+
export function readyTasks(root, configured, today) {
|
|
114
|
+
const created = since(root, real(configured));
|
|
115
|
+
const key = (row) => [row.due ?? '~', created(row.path, row.created)[0], row.path];
|
|
116
|
+
return listTasks(root, configured, today, { created })
|
|
117
|
+
.filter((row) => row.state === 'ready')
|
|
118
|
+
.map((row) => ({ row, key: key(row) }))
|
|
119
|
+
.sort((a, b) => (a.key.join('\0') < b.key.join('\0') ? -1 : 1))
|
|
120
|
+
.map(({ row }) => row);
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Every task in `folder`, a folder of the root `root`, by path, with its state as of
|
|
124
|
+
* `today`. Each row is made on its own: whatever throws while making one makes that row a
|
|
125
|
+
* problem, so no file can stop the listing. `quiet` leaves unsaid which repos are not
|
|
126
|
+
* cloned here, for a caller that says it itself.
|
|
127
|
+
*/
|
|
128
|
+
export function listTasks(root, configured, today, { created = since(root, real(configured)), quiet = false } = {}) {
|
|
129
|
+
// the real path, as the root is, so that every path compares as the disk names it
|
|
130
|
+
const folder = real(configured);
|
|
131
|
+
const tasks = new Map(walk(folder).map((path) => [path, load(path)]));
|
|
132
|
+
const repo = repos(quiet);
|
|
133
|
+
return [...tasks.entries()]
|
|
134
|
+
.sort(([a], [b]) => (a < b ? -1 : 1))
|
|
135
|
+
.map(([path, read]) => {
|
|
136
|
+
try {
|
|
137
|
+
return row(path, read);
|
|
138
|
+
}
|
|
139
|
+
catch (e) {
|
|
140
|
+
const failed = readTask(basename(path), '');
|
|
141
|
+
failed.problems.push(`ken-task could not list it (${e.message}): fix what that names, then rerun \`ken task list\``);
|
|
142
|
+
return row(path, failed);
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
/** The repo of the task at `path` and its branch, when the branch exists on this machine. */
|
|
146
|
+
function branch(path, read) {
|
|
147
|
+
const found = read.fields.repo && !read.problems.length ? repo(read.fields.repo) : undefined;
|
|
148
|
+
const name = branchOf(folder, path);
|
|
149
|
+
return found?.exists(name) ? { repo: found, name } : undefined;
|
|
150
|
+
}
|
|
151
|
+
/** Done, but its branch exists and is not on the default branch: not landed yet. */
|
|
152
|
+
function isLanding(path, read) {
|
|
153
|
+
const b = read.fields.status === 'done' ? branch(path, read) : undefined;
|
|
154
|
+
return !!b && !b.repo.landed(b.name);
|
|
155
|
+
}
|
|
156
|
+
function row(path, read) {
|
|
157
|
+
const { title, fields, problems } = read;
|
|
158
|
+
const flags = [...read.flags, ...read.reshape.map((what) => `${what}: ${CANONICAL}`)];
|
|
159
|
+
const unmet = fields['blocked-by'].flatMap((ref) => {
|
|
160
|
+
const found = resolveRef(root, folder, tasks, path, ref);
|
|
161
|
+
if (!found)
|
|
162
|
+
return [{ ref, reason: 'missing' }];
|
|
163
|
+
if (found.from) {
|
|
164
|
+
flags.push(`blocked-by ${ref} resolves from ${found.from}, not from this file: write it as ${relative(dirname(path), found.target)}`);
|
|
165
|
+
}
|
|
166
|
+
const live = found.live && tasks.get(found.live);
|
|
167
|
+
if (!found.live || !live)
|
|
168
|
+
return [];
|
|
169
|
+
if (isOpen(live))
|
|
170
|
+
return [{ ref, path: found.live, reason: 'open' }];
|
|
171
|
+
return isLanding(found.live, live) ? [{ ref, path: found.live, reason: 'landing' }] : [];
|
|
172
|
+
});
|
|
173
|
+
const open = isOpen(read);
|
|
174
|
+
const b = branch(path, read);
|
|
175
|
+
const state = problems.length
|
|
176
|
+
? 'problem'
|
|
177
|
+
: isLanding(path, read)
|
|
178
|
+
? 'landing'
|
|
179
|
+
: fields.status === 'done' || fields.status === 'wontfix'
|
|
180
|
+
? fields.status
|
|
181
|
+
: b
|
|
182
|
+
? 'claimed'
|
|
183
|
+
: unmet.length
|
|
184
|
+
? 'blocked'
|
|
185
|
+
: fields.scheduled && fields.scheduled > today
|
|
186
|
+
? 'later'
|
|
187
|
+
: 'ready';
|
|
188
|
+
const notes = [
|
|
189
|
+
...problems.map((p) => `problem: ${p}`),
|
|
190
|
+
...flags.map((f) => `flagged: ${f}; \`ken task lint\` names the upgrade`)
|
|
191
|
+
];
|
|
192
|
+
if (b)
|
|
193
|
+
notes.push(...branchNotes(path, state, b.repo, b.name));
|
|
194
|
+
if (open && fields.due && fields.due < today)
|
|
195
|
+
notes.push(`overdue: due ${fields.due}`);
|
|
196
|
+
// a problem row's note is its fix; it is never asked its age, so it cannot fail again
|
|
197
|
+
if (open && !problems.length) {
|
|
198
|
+
const [from, by] = created(path, fields.created);
|
|
199
|
+
const age = days(from, today);
|
|
200
|
+
if (age > 90)
|
|
201
|
+
notes.push(`open ${age} days, since ${from} by ${by}: finish it, or close it`);
|
|
202
|
+
}
|
|
203
|
+
return { path, title, ...fields, state, unmet: open ? unmet : [], notes };
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
/** What needs you about the branch `name` of the task at `path`, in state `state`. */
|
|
207
|
+
function branchNotes(path, state, repo, name) {
|
|
208
|
+
const { key, clone } = repo;
|
|
209
|
+
const notes = [];
|
|
210
|
+
const finish = `\`ken task finish ${path}\` removes its worktree and branch`;
|
|
211
|
+
if (state === 'landing') {
|
|
212
|
+
notes.push(`landing: branch ${name} of ${key} is not on the default branch, and dependents wait until it is: ` +
|
|
213
|
+
`rebase it onto the default branch, then \`git -C ${clone} merge --no-ff ${name}\`; then ${finish}`);
|
|
214
|
+
}
|
|
215
|
+
else if (state === 'done' || state === 'wontfix') {
|
|
216
|
+
notes.push(`${state}, but its branch ${name} remains in ${key}: ${finish}`);
|
|
217
|
+
}
|
|
218
|
+
const worktree = repo.worktree(name);
|
|
219
|
+
if (state === 'claimed') {
|
|
220
|
+
const expected = codePath(key, name);
|
|
221
|
+
const held = repo.holds(expected);
|
|
222
|
+
if (held && held !== name) {
|
|
223
|
+
notes.push(`claimed, but its worktree ${expected} holds branch ${held}, so work there lands on the wrong branch: ` +
|
|
224
|
+
`\`git -C ${expected} switch ${name}\``);
|
|
225
|
+
}
|
|
226
|
+
else if (!worktree || !existsSync(worktree)) {
|
|
227
|
+
notes.push(`claimed, but its worktree ${expected} is missing, so no one can be working on it: ` +
|
|
228
|
+
`\`git -C ${clone} worktree prune && ken get ${key} -b ${name}\` makes it again`);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
if (worktree && existsSync(worktree) && dirty(worktree)) {
|
|
232
|
+
notes.push(`uncommitted changes in ${worktree}, which finishing it would refuse to remove: commit them on ${name}, or discard them; \`git -C ${worktree} status\` shows them`);
|
|
233
|
+
}
|
|
234
|
+
return notes;
|
|
235
|
+
}
|
|
236
|
+
/** The rows as `ken task list` prints them: state, path, unmet blockers, then each note indented. */
|
|
237
|
+
export function formatRows(rows) {
|
|
238
|
+
const width = Math.max(...rows.map((r) => r.state.length));
|
|
239
|
+
return rows
|
|
240
|
+
.map((row) => {
|
|
241
|
+
const waits = row.unmet.map((u) => `${u.ref} (${u.reason === 'missing' ? 'missing: no such file in the folder or its archive' : u.reason})`);
|
|
242
|
+
const line = `${row.state.padEnd(width)} ${row.path}${waits.length ? ` blocked by ${waits.join(', ')}` : ''}`;
|
|
243
|
+
return [line, ...row.notes.map((n) => `${' '.repeat(width + 2)}${n}`)].join('\n');
|
|
244
|
+
})
|
|
245
|
+
.join('\n');
|
|
246
|
+
}
|
package/dist/read.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { isSeq, parseDocument } from 'yaml';
|
|
2
|
+
const SCALARS = new Set(['status', 'created', 'closed', 'repo', 'scheduled', 'due']);
|
|
3
|
+
const DATES = new Set(['created', 'closed', 'scheduled', 'due']);
|
|
4
|
+
const ALIASES = new Set(['blocked_by', 'blockedBy', 'depends_on', 'depends-on']);
|
|
5
|
+
const STATUSES = ['todo', 'done', 'wontfix'];
|
|
6
|
+
export const CANONICAL = 'the canonical form is one line, `blocked-by: [a.md, b.md]`';
|
|
7
|
+
export function isDate(text) {
|
|
8
|
+
const date = new Date(`${text}T00:00:00Z`);
|
|
9
|
+
return (/^\d{4}-\d{2}-\d{2}$/.test(text) &&
|
|
10
|
+
!Number.isNaN(date.getTime()) &&
|
|
11
|
+
date.toISOString().startsWith(text));
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Read a task file named `name`. Only a `.md` has front matter: YAML between `---` lines,
|
|
15
|
+
* read by a YAML parser, then held to the tolerance list of docs/ken-task.md, so that a
|
|
16
|
+
* deviation is flagged, never refused. The title is the first `# ` heading, else the name
|
|
17
|
+
* without its extension, dashes as spaces.
|
|
18
|
+
*/
|
|
19
|
+
export function readTask(name, text) {
|
|
20
|
+
const lines = text.replace(/^/, '').split(/\r?\n/);
|
|
21
|
+
const read = {
|
|
22
|
+
title: '',
|
|
23
|
+
fields: { status: 'todo', 'blocked-by': [], other: {} },
|
|
24
|
+
flags: [],
|
|
25
|
+
problems: [],
|
|
26
|
+
reshape: [],
|
|
27
|
+
written: []
|
|
28
|
+
};
|
|
29
|
+
let body = 0;
|
|
30
|
+
if (name.endsWith('.md') && /^---\s*$/.test(lines[0] ?? '')) {
|
|
31
|
+
const end = lines.findIndex((line, i) => i > 0 && /^---\s*$/.test(line));
|
|
32
|
+
if (end < 0) {
|
|
33
|
+
read.written = undefined;
|
|
34
|
+
read.flags.push('its front matter has no closing `---`, so every field reads as absent: add a `---` line after the last field');
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
frontMatter(lines.slice(1, end).join('\n'), read);
|
|
38
|
+
body = end + 1;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const status = read.fields.status;
|
|
42
|
+
if (!STATUSES.includes(status)) {
|
|
43
|
+
read.flags.push(`status ${JSON.stringify(status)} is none of ${STATUSES.join(', ')}, so it reads as open: set one of them`);
|
|
44
|
+
}
|
|
45
|
+
read.title = heading(lines.slice(body)) ?? name.replace(/(.)\.[^.]*$/, '$1').replaceAll('-', ' ');
|
|
46
|
+
return read;
|
|
47
|
+
}
|
|
48
|
+
function frontMatter(source, read) {
|
|
49
|
+
const { fields, problems } = read;
|
|
50
|
+
const doc = parseDocument(source);
|
|
51
|
+
let data;
|
|
52
|
+
try {
|
|
53
|
+
const [error] = doc.errors;
|
|
54
|
+
if (error)
|
|
55
|
+
throw error;
|
|
56
|
+
// an alias to no anchor is no parse error, but throws here
|
|
57
|
+
data = doc.toJS();
|
|
58
|
+
}
|
|
59
|
+
catch (e) {
|
|
60
|
+
const { message, linePos } = e;
|
|
61
|
+
// the front matter starts on the file's second line
|
|
62
|
+
const at = linePos?.[0] ? `line ${linePos[0].line + 1}: ` : '';
|
|
63
|
+
problems.push(`its front matter is not YAML (${at}${message.split(/ at line |\n/)[0]}): fix that line, or quote its value`);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
try {
|
|
67
|
+
// what a row carries must print as JSON; an alias inside its own anchor never would
|
|
68
|
+
data = JSON.parse(JSON.stringify(data) ?? 'null');
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
problems.push('its front matter has a value that contains itself, through a YAML alias inside its own anchor: write the value out');
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (data === null)
|
|
75
|
+
return;
|
|
76
|
+
if (typeof data !== 'object' || Array.isArray(data)) {
|
|
77
|
+
problems.push('its front matter is not `field: value` lines: write it as such, or remove it');
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const seen = new Map();
|
|
81
|
+
for (const [key, value] of Object.entries(data)) {
|
|
82
|
+
const field = ALIASES.has(key) ? 'blocked-by' : key;
|
|
83
|
+
if (field !== 'blocked-by' && !SCALARS.has(field)) {
|
|
84
|
+
fields.other[key] = value;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const before = seen.get(field);
|
|
88
|
+
seen.set(field, key);
|
|
89
|
+
if (value !== null)
|
|
90
|
+
read.written?.push(field);
|
|
91
|
+
if (before !== undefined) {
|
|
92
|
+
problems.push(`${field} is written twice, as ${before} and as ${key}, so which one holds is unclear: keep one`);
|
|
93
|
+
}
|
|
94
|
+
else if (field === 'blocked-by') {
|
|
95
|
+
if (key !== field)
|
|
96
|
+
read.reshape.push(`${key} reads as blocked-by`);
|
|
97
|
+
const node = doc.get(key, true);
|
|
98
|
+
const form = isSeq(node) ? (node.flow ? 'list' : 'block list') : 'single value';
|
|
99
|
+
fields['blocked-by'] = list(key, value, form, read);
|
|
100
|
+
}
|
|
101
|
+
else if (value === null) {
|
|
102
|
+
// `field:` with nothing after it is absent
|
|
103
|
+
}
|
|
104
|
+
else if (typeof value === 'object') {
|
|
105
|
+
problems.push(`${key} is not a single value: write it as \`${key}: <value>\``);
|
|
106
|
+
}
|
|
107
|
+
else if (DATES.has(key) && !isDate(String(value))) {
|
|
108
|
+
problems.push(`${key} ${JSON.stringify(String(value))} is not a date: write it as \`${key}: YYYY-MM-DD\``);
|
|
109
|
+
}
|
|
110
|
+
else
|
|
111
|
+
Object.assign(fields, { [key]: String(value) });
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/** `blocked-by` as read: a one-line list, or a block list or a single value, flagged. */
|
|
115
|
+
function list(key, value, form, read) {
|
|
116
|
+
if (value === null)
|
|
117
|
+
return [];
|
|
118
|
+
const items = Array.isArray(value) ? value : [value];
|
|
119
|
+
if (items.some((item) => item === null || typeof item === 'object')) {
|
|
120
|
+
read.problems.push(`${key} is not a list of paths: ${CANONICAL}`);
|
|
121
|
+
return [];
|
|
122
|
+
}
|
|
123
|
+
if (form !== 'list')
|
|
124
|
+
read.reshape.push(`${key} is a ${form}`);
|
|
125
|
+
return items.map(String);
|
|
126
|
+
}
|
|
127
|
+
/** The text of the first `# ` heading of `lines`, outside fenced code. */
|
|
128
|
+
function heading(lines) {
|
|
129
|
+
let fenced = false;
|
|
130
|
+
for (const line of lines) {
|
|
131
|
+
if (/^ {0,3}(```|~~~)/.test(line))
|
|
132
|
+
fenced = !fenced;
|
|
133
|
+
const text = fenced ? undefined : /^ {0,3}#[ \t]+(.*\S)/.exec(line)?.[1];
|
|
134
|
+
if (text)
|
|
135
|
+
return text;
|
|
136
|
+
}
|
|
137
|
+
}
|