@unclex/ken-core 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/LICENSE +21 -0
- package/README.md +17 -2
- package/dist/cli.js +4 -0
- package/dist/die.js +11 -0
- package/dist/dispatch.js +131 -0
- package/dist/files.js +123 -0
- package/dist/get.js +304 -0
- package/dist/git.js +31 -0
- package/dist/init.js +87 -0
- package/dist/keys.js +38 -0
- package/dist/layout.js +93 -0
- package/dist/main.js +205 -0
- package/dist/registry.js +106 -0
- package/dist/repos.js +106 -0
- package/dist/root.js +77 -0
- package/package.json +21 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Xiaoxing Hu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,18 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @unclex/ken-core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The core of ken: a root's two files, `.ken` and `.repos.index`, finding the root, and the
|
|
4
|
+
primitives every other command builds on. A person installs `@unclex/ken`, which bundles it
|
|
5
|
+
with the standard commands; this package knows none of them.
|
|
6
|
+
|
|
7
|
+
It exports `main`, which runs ken with the arguments after `ken` and returns the exit
|
|
8
|
+
status: a core command, or the first `ken-<name>` found in the root's `.bin/`, the bundled
|
|
9
|
+
commands its caller passes, then `PATH`. `src/cli.ts` runs it with no bundled commands, from a
|
|
10
|
+
clone, with no build:
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
node packages/ken-core/src/cli.ts init
|
|
14
|
+
bun packages/ken-core/src/cli.ts path root
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
What it does is "The core" in `docs/prd.md` at the repo root; the files' grammar is
|
|
18
|
+
`docs/files.md`.
|
package/dist/cli.js
ADDED
package/dist/die.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// How ken stops: one function, so every refusal reads the same and ends the same.
|
|
2
|
+
/** A refusal: its message is what is the case, why it matters and what to run (PRD 24). */
|
|
3
|
+
export class KenError extends Error {
|
|
4
|
+
}
|
|
5
|
+
/** Stop the command with `parts`, joined by spaces; the entry prints it and exits 1. */
|
|
6
|
+
export function die(...parts) {
|
|
7
|
+
throw new KenError(parts.join(' '));
|
|
8
|
+
}
|
|
9
|
+
/** `s` as one shell word, so a command in a message can be pasted: as is when nothing in it is
|
|
10
|
+
* special to a shell, else single-quoted. */
|
|
11
|
+
export const q = (s) => /^[A-Za-z0-9_./@%+=:,-]+$/.test(s) ? s : `'${s.replaceAll("'", "'\\''")}'`;
|
package/dist/dispatch.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// Running `ken <name>` as the first ken-<name> found: the root's .bin/, the bundled commands,
|
|
2
|
+
// then PATH (docs/extensions.md, "Where ken finds it" and "What it gets").
|
|
3
|
+
import { spawnSync } from 'node:child_process';
|
|
4
|
+
import { accessSync, constants, mkdtempSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { constants as os, tmpdir } from 'node:os';
|
|
6
|
+
import { delimiter, join, resolve } from 'node:path';
|
|
7
|
+
import { die, q } from "./die.js";
|
|
8
|
+
import { isFile, rootIfAny } from "./root.js";
|
|
9
|
+
const runnable = (file) => {
|
|
10
|
+
try {
|
|
11
|
+
accessSync(file, constants.X_OK);
|
|
12
|
+
return isFile(file);
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
/** Where ken-<name> is looked for, in order; PATH's folders that exist, each once. */
|
|
19
|
+
const placesOf = (root) => {
|
|
20
|
+
const bin = root && join(root, '.bin');
|
|
21
|
+
const seen = new Set([bin]);
|
|
22
|
+
const path = [];
|
|
23
|
+
for (const entry of process.env.PATH?.split(delimiter) ?? []) {
|
|
24
|
+
let dir;
|
|
25
|
+
try {
|
|
26
|
+
dir = realpathSync.native(resolve(entry || '.'));
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
if (!seen.has(dir))
|
|
32
|
+
path.push({ label: 'PATH', dir });
|
|
33
|
+
seen.add(dir);
|
|
34
|
+
}
|
|
35
|
+
return [...(bin ? [{ label: "the root's .bin/", dir: bin }] : []), { label: 'bundled' }, ...path];
|
|
36
|
+
};
|
|
37
|
+
/** Run `cmd` with `args`, stdio and exit status its own, KEN_ROOT the root or unset, and first on
|
|
38
|
+
* PATH a folder whose `ken` is this ken, run by this runtime. */
|
|
39
|
+
const run = (cmd, args, root) => {
|
|
40
|
+
const shim = mkdtempSync(join(tmpdir(), 'ken-'));
|
|
41
|
+
try {
|
|
42
|
+
const entry = realpathSync.native(process.argv[1] ?? '');
|
|
43
|
+
writeFileSync(join(shim, 'ken'), `#!/bin/sh\nexec ${q(process.execPath)} ${q(entry)} "$@"\n`, {
|
|
44
|
+
mode: 0o755
|
|
45
|
+
});
|
|
46
|
+
const env = {
|
|
47
|
+
...process.env,
|
|
48
|
+
PATH: `${shim}${delimiter}${process.env.PATH ?? ''}`
|
|
49
|
+
};
|
|
50
|
+
delete env.KEN_ROOT;
|
|
51
|
+
if (root)
|
|
52
|
+
env.KEN_ROOT = root;
|
|
53
|
+
const r = spawnSync(cmd, args, { stdio: 'inherit', env });
|
|
54
|
+
if (r.error)
|
|
55
|
+
die(`could not run ${args[0] && cmd === process.execPath ? args[0] : cmd}: ${r.error.message}.`, 'An executable script needs a #! line naming what runs it, e.g. #!/bin/sh.');
|
|
56
|
+
return r.status ?? 128 + (r.signal ? os.signals[r.signal] : 0);
|
|
57
|
+
}
|
|
58
|
+
finally {
|
|
59
|
+
rmSync(shim, { recursive: true, force: true });
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
/** Run the first ken-<name> found with `args` and return its exit status, or stop, saying where
|
|
63
|
+
* ken looked. `core` is the core's commands, which ran first. */
|
|
64
|
+
export const dispatch = (name, args, bundled, core) => {
|
|
65
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9-]*$/.test(name))
|
|
66
|
+
die(`${q(name)} is not a ken command: a command's name is letters, digits and -, starting`, 'with a letter or digit. Run `ken help` for every command.');
|
|
67
|
+
const root = rootIfAny();
|
|
68
|
+
const places = placesOf(root);
|
|
69
|
+
for (const place of places) {
|
|
70
|
+
if (!place.dir) {
|
|
71
|
+
const file = Object.hasOwn(bundled, name) ? bundled[name] : undefined;
|
|
72
|
+
if (file)
|
|
73
|
+
return run(process.execPath, [file, ...args], root);
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
const file = join(place.dir, `ken-${name}`);
|
|
77
|
+
if (runnable(file))
|
|
78
|
+
return run(file, args, root);
|
|
79
|
+
if (root && place === places[0] && isFile(file))
|
|
80
|
+
die(`${file} would run as \`ken ${name}\`, but it is not executable.`, `Run \`chmod +x ${q(file)}\`, then \`ken ${name}\` again.`);
|
|
81
|
+
}
|
|
82
|
+
const looked = [
|
|
83
|
+
`the core commands: ${listed(core)}`,
|
|
84
|
+
root
|
|
85
|
+
? `${join(root, '.bin')}, the root's .bin/`
|
|
86
|
+
: "the root's .bin/: skipped, as there is no root here",
|
|
87
|
+
`the bundled commands: ${listed(Object.keys(bundled))}`,
|
|
88
|
+
'PATH, each folder in order, as `echo "$PATH"` prints them'
|
|
89
|
+
];
|
|
90
|
+
const add = root ? join(root, '.bin') : 'the .bin/ of a root, and run ken inside it';
|
|
91
|
+
die(`${name} is not a ken command, and no executable ken-${name} was found. Looked in, in order:${looked.map((l) => `\n ${l}`).join('')}\nAdd an executable ken-${name} to ${add}, or run`, '`ken help` for every command found.');
|
|
92
|
+
};
|
|
93
|
+
const listed = (names) => (names.length ? names.join(', ') : 'none');
|
|
94
|
+
/** The names of the ken-<name> files in `dir` that run, or with `all` that are files; none when
|
|
95
|
+
* ken may not list it. */
|
|
96
|
+
const commandsIn = (dir, all) => {
|
|
97
|
+
try {
|
|
98
|
+
return readdirSync(dir)
|
|
99
|
+
.filter((f) => /^ken-[A-Za-z0-9][A-Za-z0-9-]*$/.test(f) && (all ? isFile : runnable)(join(dir, f)))
|
|
100
|
+
.map((f) => f.slice(4));
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
return [];
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
/** The extensions `ken help` lists: by where each was found, one shadowed saying by what. A
|
|
107
|
+
* ken-<name> in the root's .bin/ that is not executable is listed, as dispatch stops at it. */
|
|
108
|
+
export const extensions = (root, bundled, core) => {
|
|
109
|
+
const first = new Map(core.map((name) => [name, 'the core command, which always wins']));
|
|
110
|
+
const groups = [];
|
|
111
|
+
const places = placesOf(root);
|
|
112
|
+
for (const place of places) {
|
|
113
|
+
const top = root !== undefined && place === places[0];
|
|
114
|
+
const names = place.dir ? commandsIn(place.dir, top) : Object.keys(bundled);
|
|
115
|
+
const lines = names.sort().map((name) => {
|
|
116
|
+
const by = first.get(name);
|
|
117
|
+
if (by)
|
|
118
|
+
return ` ${name}, shadowed by ${by}`;
|
|
119
|
+
const file = place.dir && join(place.dir, `ken-${name}`);
|
|
120
|
+
first.set(name, file || 'the bundled one');
|
|
121
|
+
return file && top && !runnable(file)
|
|
122
|
+
? ` ${name}, not executable: run \`chmod +x ${q(file)}\``
|
|
123
|
+
: ` ${name}`;
|
|
124
|
+
});
|
|
125
|
+
if (lines.length)
|
|
126
|
+
groups.push(` ${place.dir ? `${place.label}, ${place.dir}` : place.label}\n${lines.join('\n')}`);
|
|
127
|
+
}
|
|
128
|
+
return groups.length
|
|
129
|
+
? `Extensions, each a ken-<name> run as \`ken <name>\`, by where it was found, the first winning:\n${groups.join('\n')}\n`
|
|
130
|
+
: `Extensions: none found. Add one as an executable ken-<name> in ${root ? join(root, '.bin') : "a root's .bin/"}.\n`;
|
|
131
|
+
};
|
package/dist/files.js
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// The two files ken reads and writes, `.ken` and `.repos.index`, by docs/files.md: a reader
|
|
2
|
+
// that cannot read a line stops naming it, and a writer changes only the lines it means to.
|
|
3
|
+
import { renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { die, q } from "./die.js";
|
|
5
|
+
const SPEC = 'docs/files.md in github.com/xiaoxinghu/ken';
|
|
6
|
+
/** The settings of a `.ken`'s text, read from `file`: a key repeated reads as its last line. */
|
|
7
|
+
export const parseSettings = (text, file) => {
|
|
8
|
+
const settings = new Map();
|
|
9
|
+
for (const [i, line] of text.split('\n').entries()) {
|
|
10
|
+
if (line.startsWith('#') || line.trim() === '')
|
|
11
|
+
continue;
|
|
12
|
+
const m = /^([A-Za-z0-9_.-]+)=(.*)$/.exec(line);
|
|
13
|
+
if (!m?.[1])
|
|
14
|
+
die(`${file} line ${i + 1}, ${q(line)}, is not a line ken can read, so ken cannot tell`, 'what the root is set to. It expects a comment starting with #, or <key>=<value> with', `the key letters, digits, _, . and - and no space before the =, as ${SPEC} says.`, 'Fix or delete that line, then rerun.');
|
|
15
|
+
else
|
|
16
|
+
settings.set(m[1], (m[2] ?? '').trim());
|
|
17
|
+
}
|
|
18
|
+
return settings;
|
|
19
|
+
};
|
|
20
|
+
/** `text`, a `.ken`, with `key` set to `value`: its last line replaced, else one appended. */
|
|
21
|
+
export const setSetting = (text, key, value) => {
|
|
22
|
+
const lines = splitLines(text);
|
|
23
|
+
const at = lines.findLastIndex((line) => line.startsWith(`${key}=`));
|
|
24
|
+
if (at < 0)
|
|
25
|
+
lines.push(`${key}=${value}`);
|
|
26
|
+
else
|
|
27
|
+
lines[at] = `${key}=${value}`;
|
|
28
|
+
return `${lines.join('\n')}\n`;
|
|
29
|
+
};
|
|
30
|
+
const FIELD = /^([A-Za-z0-9_-]+):(?:[ \t](.*))?$/;
|
|
31
|
+
export const KEY = {
|
|
32
|
+
repo: /^[a-z0-9._-]+\/[a-z0-9._-]+\/[a-z0-9._-]+$/,
|
|
33
|
+
owner: /^[a-z0-9._-]+\/[a-z0-9._-]+$/
|
|
34
|
+
};
|
|
35
|
+
/** The stanzas of a `.repos.index`'s text, read from `file`. */
|
|
36
|
+
export const parseIndex = (text, file) => {
|
|
37
|
+
const stanzas = [];
|
|
38
|
+
let stanza;
|
|
39
|
+
for (const [i, line] of text.split('\n').entries()) {
|
|
40
|
+
if (line.startsWith('#'))
|
|
41
|
+
continue;
|
|
42
|
+
if (line.trim() === '') {
|
|
43
|
+
stanza = undefined;
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
const bad = (expected) => die(`${file} line ${i + 1}, ${q(line)}, is not a line ken can read: it expects ${expected},`, `as ${SPEC} says. Without it ken cannot tell what the root's repos are.`, 'Fix that line, then rerun.');
|
|
47
|
+
const m = FIELD.exec(line);
|
|
48
|
+
const name = m?.[1] ?? '';
|
|
49
|
+
const value = (m?.[2] ?? '').trim();
|
|
50
|
+
if (!stanza) {
|
|
51
|
+
if (name !== 'repo' && name !== 'owner')
|
|
52
|
+
bad('the first line of a stanza, repo: <host>/<owner>/<repo> or owner: <host>/<owner>');
|
|
53
|
+
const kind = name;
|
|
54
|
+
if (!KEY[kind].test(value) || value.split('/').some((part) => part === '.' || part === '..'))
|
|
55
|
+
bad(`${kind}: and a key, lowercase letters, digits, ., _ and -, one part per /, none . or ..`);
|
|
56
|
+
if (stanzas.some((s) => s.kind === kind && s.key === value))
|
|
57
|
+
bad(`${kind}: ${value} in one stanza only, and an earlier one has it`);
|
|
58
|
+
stanza = { kind, key: value, fields: new Map() };
|
|
59
|
+
stanzas.push(stanza);
|
|
60
|
+
}
|
|
61
|
+
else if (!m)
|
|
62
|
+
bad('a field, <name>: <value>, the name letters, digits, _ and -');
|
|
63
|
+
// owner: is a field of a repo stanza too; only the stanza's own first name is reserved
|
|
64
|
+
else if (name === stanza.kind || stanza.fields.has(name))
|
|
65
|
+
bad(`${name}: once per stanza, and the stanza has it already`);
|
|
66
|
+
else if (name === 'desc' && value === '')
|
|
67
|
+
bad('desc: with a value, never empty');
|
|
68
|
+
else
|
|
69
|
+
stanza.fields.set(name, value);
|
|
70
|
+
}
|
|
71
|
+
return stanzas;
|
|
72
|
+
};
|
|
73
|
+
/** `text`, a `.repos.index`, with `fields` set in the stanza of the repo `key`: each field's
|
|
74
|
+
* line replaced or appended to the stanza, a stanza added at the end when none has `key`.
|
|
75
|
+
* The caller has checked each name and value, one line each. */
|
|
76
|
+
export const setFields = (text, key, fields) => {
|
|
77
|
+
const lines = splitLines(text);
|
|
78
|
+
// the first line of a stanza, never a field such as a repo: inside an owner stanza
|
|
79
|
+
let inStanza = false;
|
|
80
|
+
let start = lines.findIndex((line) => {
|
|
81
|
+
if (line.startsWith('#'))
|
|
82
|
+
return false;
|
|
83
|
+
const first = !inStanza;
|
|
84
|
+
inStanza = line.trim() !== '';
|
|
85
|
+
const m = FIELD.exec(line);
|
|
86
|
+
return first && m?.[1] === 'repo' && m[2]?.trim() === key;
|
|
87
|
+
});
|
|
88
|
+
if (start < 0) {
|
|
89
|
+
if (lines.length && lines.at(-1)?.trim() !== '')
|
|
90
|
+
lines.push('');
|
|
91
|
+
start = lines.push(`repo: ${key}`) - 1;
|
|
92
|
+
}
|
|
93
|
+
let end = lines.findIndex((line, i) => i > start && line.trim() === '');
|
|
94
|
+
if (end < 0)
|
|
95
|
+
end = lines.length;
|
|
96
|
+
for (const [name, value] of fields) {
|
|
97
|
+
const at = lines.findIndex((line, i) => i > start && i < end && !line.startsWith('#') && FIELD.exec(line)?.[1] === name);
|
|
98
|
+
if (at >= 0)
|
|
99
|
+
lines[at] = `${name}: ${value}`;
|
|
100
|
+
else
|
|
101
|
+
lines.splice(end++, 0, `${name}: ${value}`);
|
|
102
|
+
}
|
|
103
|
+
return `${lines.join('\n')}\n`;
|
|
104
|
+
};
|
|
105
|
+
/** The lines of `text`, without the empty one after its last newline. */
|
|
106
|
+
const splitLines = (text) => {
|
|
107
|
+
const lines = text.split('\n');
|
|
108
|
+
if (lines.at(-1) === '')
|
|
109
|
+
lines.pop();
|
|
110
|
+
return lines;
|
|
111
|
+
};
|
|
112
|
+
/** Write `text` to `file` beside it and rename it over, so a reader never sees half of it. */
|
|
113
|
+
export const writeAtomic = (file, text) => {
|
|
114
|
+
const tmp = `${file}.tmp.${process.pid}`;
|
|
115
|
+
try {
|
|
116
|
+
writeFileSync(tmp, text);
|
|
117
|
+
renameSync(tmp, file);
|
|
118
|
+
}
|
|
119
|
+
catch (e) {
|
|
120
|
+
rmSync(tmp, { force: true });
|
|
121
|
+
die(`could not write ${file}: ${e.message}. It is unchanged.`, 'Fix that, then rerun.');
|
|
122
|
+
}
|
|
123
|
+
};
|
package/dist/get.js
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
// `ken get <url|key> [-b <branch> [--from <ref>]]`: the one write into the layout, idempotent,
|
|
2
|
+
// the path the only thing on stdout (docs/prd.md, "The core").
|
|
3
|
+
import { spawnSync } from 'node:child_process';
|
|
4
|
+
import { appendFileSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, rmdirSync, rmSync, statSync, symlinkSync } from 'node:fs';
|
|
5
|
+
import { basename, dirname, join, resolve } from 'node:path';
|
|
6
|
+
import { die, q } from "./die.js";
|
|
7
|
+
import { parseSettings, setFields } from "./files.js";
|
|
8
|
+
import { alive, checkGit, git, sleep } from "./git.js";
|
|
9
|
+
import { branchFolder, keyOf, parseKey, redact } from "./keys.js";
|
|
10
|
+
import { reposOf } from "./layout.js";
|
|
11
|
+
import { editIndex } from "./registry.js";
|
|
12
|
+
import { findRoot, isFile } from "./root.js";
|
|
13
|
+
const say = (...parts) => process.stderr.write(`ken: ${parts.join(' ')}\n`);
|
|
14
|
+
const isDir = (path) => statSync(path, { throwIfNoEntry: false })?.isDirectory() ?? false;
|
|
15
|
+
const absent = (path) => !lstatSync(path, { throwIfNoEntry: false });
|
|
16
|
+
/** Link `CLAUDE.md -> AGENTS.md` in the fresh checkout `dir` when it has AGENTS.md and no
|
|
17
|
+
* CLAUDE.md, listed in its repo's info/exclude: Claude Code reads a checkout's AGENTS.md only
|
|
18
|
+
* while no CLAUDE.md is at or above it, and the root's is above it (PRD 6). */
|
|
19
|
+
const claudeLink = (dir) => {
|
|
20
|
+
if (!isFile(join(dir, 'AGENTS.md')) || !absent(join(dir, 'CLAUDE.md')))
|
|
21
|
+
return;
|
|
22
|
+
try {
|
|
23
|
+
symlinkSync('AGENTS.md', join(dir, 'CLAUDE.md'));
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
const common = git(dir, 'rev-parse', '--path-format=absolute', '--git-common-dir');
|
|
29
|
+
if (common.ok) {
|
|
30
|
+
// one exclude file for the clone and its worktrees, so the line goes in once
|
|
31
|
+
const exclude = join(common.out, 'info/exclude');
|
|
32
|
+
const text = isFile(exclude) ? readFileSync(exclude, 'utf8') : '';
|
|
33
|
+
if (!text.split('\n').includes('/CLAUDE.md')) {
|
|
34
|
+
mkdirSync(dirname(exclude), { recursive: true });
|
|
35
|
+
appendFileSync(exclude, `${text && !text.endsWith('\n') ? '\n' : ''}/CLAUDE.md\n`);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
say(`linked ${dir}/CLAUDE.md -> AGENTS.md, excluded from git: Claude Code reads a checkout's`, "AGENTS.md only while no CLAUDE.md is at or above it, and a root's is above every checkout.");
|
|
39
|
+
};
|
|
40
|
+
/** Stop when the root's git does not ignore `.repos/`, or `key` is the root's own repo (PRD 9). */
|
|
41
|
+
const guardRoot = (root, key, again) => {
|
|
42
|
+
if (!git(root, 'rev-parse', '--show-toplevel').ok)
|
|
43
|
+
return;
|
|
44
|
+
if (spawnSync('git', ['-C', root, 'check-ignore', '-q', '.repos/']).status === 1)
|
|
45
|
+
die(`${root}/.repos is not ignored by the git of ${root}, so every clone ken makes there would`, 'show in its status and could be committed into the knowledge base. Add the line .repos/ to', `${root}/.gitignore, e.g. \`printf '.repos/\\n' >> ${q(`${root}/.gitignore`)}\`, or run`, `\`ken init ${q(root)}\`, which adds it; then run \`${again}\` again.`);
|
|
46
|
+
const origin = git(root, 'config', '--get', 'remote.origin.url');
|
|
47
|
+
if (origin.ok && keyOf(origin.out)?.key === key)
|
|
48
|
+
die(`${key} is the repo of the root ${root} itself, its origin, and its clone in ${root}/.repos`, `would be a root inside itself. Work on the root in place, in ${root}, with git there.`);
|
|
49
|
+
};
|
|
50
|
+
export const get = (args) => {
|
|
51
|
+
let asked;
|
|
52
|
+
let branch;
|
|
53
|
+
let from;
|
|
54
|
+
let opts = '';
|
|
55
|
+
for (let i = 0; i < args.length; i++) {
|
|
56
|
+
const arg = args[i] ?? '';
|
|
57
|
+
if (arg === '-b' || arg === '--from') {
|
|
58
|
+
const value = args[++i];
|
|
59
|
+
if (value === undefined)
|
|
60
|
+
die(`ken get ${arg} needs a value. Run e.g. \`ken get <key> -b feat/login\`.`);
|
|
61
|
+
if (arg === '-b')
|
|
62
|
+
branch = value;
|
|
63
|
+
else
|
|
64
|
+
from = value;
|
|
65
|
+
opts += ` ${arg} ${q(redact(value))}`;
|
|
66
|
+
}
|
|
67
|
+
else if (asked !== undefined || arg.startsWith('-'))
|
|
68
|
+
die('ken get takes one repo key or git URL, then -b <branch> [--from <ref>], not', `${q(redact(arg))} as well. Run e.g. \`ken get github.com/acme/join-web -b feat/login\`.`);
|
|
69
|
+
else
|
|
70
|
+
asked = arg;
|
|
71
|
+
}
|
|
72
|
+
if (from !== undefined && branch === undefined)
|
|
73
|
+
die('ken get --from names what a new branch starts from, so it needs -b <branch>.', 'Run e.g. `ken get <key> -b fix/x --from v1.2`.');
|
|
74
|
+
if (asked === undefined)
|
|
75
|
+
die('ken get needs a repo key or git URL. Run e.g. `ken get github.com/acme/join-web`.');
|
|
76
|
+
const { key, url } = parseKey(asked);
|
|
77
|
+
// a bad branch name is refused before anything is touched
|
|
78
|
+
const folder = branch === undefined ? '' : `.${branchFolder(branch)}`;
|
|
79
|
+
const again = `ken get ${key}${opts}`;
|
|
80
|
+
checkGit(again);
|
|
81
|
+
const root = findRoot();
|
|
82
|
+
guardRoot(root, key, again);
|
|
83
|
+
const blobless = parseSettings(readFileSync(join(root, '.ken'), 'utf8'), join(root, '.ken')).get('clone.blobless');
|
|
84
|
+
if (blobless !== undefined && !['', 'true', 'false'].includes(blobless))
|
|
85
|
+
die(`${root}/.ken sets clone.blobless to neither true nor false, so ken cannot tell how to clone.`, `Fix that line to clone.blobless=false or true, then run \`${again}\` again.`);
|
|
86
|
+
const repos = reposOf(root);
|
|
87
|
+
const clone = join(repos, key);
|
|
88
|
+
const parent = dirname(clone);
|
|
89
|
+
for (const at of [repos, dirname(parent), parent]) {
|
|
90
|
+
if (!lstatSync(at, { throwIfNoEntry: false })?.isSymbolicLink())
|
|
91
|
+
continue;
|
|
92
|
+
const to = resolve(dirname(at), readlinkSync(at));
|
|
93
|
+
die(`${at} is a symlink to ${to}, so a clone under it would be outside ${root}, where a checkout`, "is found by its real path and loads the root's rules from above it. Put the folder in its", `place, \`rm ${q(at)} && mv ${q(to)} ${q(at)}\`, or start an empty one, \`rm ${q(at)}\`; then`, `run \`${again}\` again.`);
|
|
94
|
+
}
|
|
95
|
+
// every get marks itself before the claim, the mkdir of the clone's folder, so one that
|
|
96
|
+
// loses it waits while the winner lives: its clone is whole once the mark is gone
|
|
97
|
+
const repo = basename(clone);
|
|
98
|
+
const mark = join(parent, `.${repo}.ken-get.${process.pid}`);
|
|
99
|
+
try {
|
|
100
|
+
mkdirSync(mark, { recursive: true });
|
|
101
|
+
}
|
|
102
|
+
catch (e) {
|
|
103
|
+
die(`could not make ${parent}: ${e.message}, so ${key} has no folder to be cloned`, `into. Fix that, then run \`${again}\` again.`);
|
|
104
|
+
}
|
|
105
|
+
try {
|
|
106
|
+
let fresh = false;
|
|
107
|
+
try {
|
|
108
|
+
mkdirSync(clone);
|
|
109
|
+
fresh = true;
|
|
110
|
+
}
|
|
111
|
+
catch (e) {
|
|
112
|
+
if (e.code !== 'EEXIST')
|
|
113
|
+
die(`could not make ${clone}: ${e.message}. Fix that, then run \`${again}\` again.`);
|
|
114
|
+
}
|
|
115
|
+
if (fresh)
|
|
116
|
+
cloneInto(clone, url, blobless !== 'false', asked, opts, key);
|
|
117
|
+
else {
|
|
118
|
+
rmdirSync(mark);
|
|
119
|
+
const marks = new RegExp(`^\\.${repo.replaceAll('.', '\\.')}\\.ken-get\\.([0-9]+)$`);
|
|
120
|
+
while (readdirSync(parent).some((name) => alive(Number(marks.exec(name)?.[1] ?? Number.NaN))))
|
|
121
|
+
sleep(200);
|
|
122
|
+
}
|
|
123
|
+
checkClone(clone, key, again);
|
|
124
|
+
// another get of an existing repo may hold git's config lock, setting the same: wait, retry
|
|
125
|
+
// true in the clone's own config, whatever a global one says
|
|
126
|
+
const relative = () => git(clone, 'config', '--local', '--type=bool', '--get', 'worktree.useRelativePaths').out ===
|
|
127
|
+
'true' || git(clone, 'config', '--local', 'worktree.useRelativePaths', 'true').ok;
|
|
128
|
+
if (!relative() && !(sleep(1000) && relative()))
|
|
129
|
+
die(`could not set worktree.useRelativePaths in ${clone}, which lets its <owner>/ folder and`, `the root move. Run \`git -C ${q(clone)} config worktree.useRelativePaths true\`, then`, `\`${again}\` again.`);
|
|
130
|
+
spawnSync('git', ['-C', clone, 'worktree', 'repair'], { stdio: ['ignore', 2, 2] });
|
|
131
|
+
if (fresh)
|
|
132
|
+
claudeLink(clone);
|
|
133
|
+
register(root, key, clone);
|
|
134
|
+
return `${branch === undefined ? clone : worktree(clone, key, branch, from, folder, again)}\n`;
|
|
135
|
+
}
|
|
136
|
+
finally {
|
|
137
|
+
rmSync(mark, { recursive: true, force: true });
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
/** Clone `url` into the empty folder `clone`, removing it again when the clone fails. */
|
|
141
|
+
const cloneInto = (clone, url, blobless, asked, opts, key) => {
|
|
142
|
+
let interrupted = false;
|
|
143
|
+
const stop = () => {
|
|
144
|
+
interrupted = true;
|
|
145
|
+
};
|
|
146
|
+
const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
|
|
147
|
+
for (const s of signals)
|
|
148
|
+
process.on(s, stop);
|
|
149
|
+
const r = spawnSync('git', ['clone', '-q', ...(blobless ? ['--filter=blob:none'] : []), '--', url, clone], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
|
|
150
|
+
for (const s of signals)
|
|
151
|
+
process.off(s, stop);
|
|
152
|
+
if (r.status === 0 && !interrupted)
|
|
153
|
+
return;
|
|
154
|
+
rmSync(clone, { recursive: true, force: true });
|
|
155
|
+
const rerun = `ken get ${q(redact(asked))}${opts}`;
|
|
156
|
+
if (interrupted)
|
|
157
|
+
die(`the clone of ${key} was interrupted, so ${clone} was removed again. Run \`${rerun}\` to clone it.`);
|
|
158
|
+
const hint = asked.includes(':')
|
|
159
|
+
? ''
|
|
160
|
+
: `A key alone clones https://${key}.git; for another remote pass its URL, e.g. \`ken get git@${key.replace('/', ':')}.git\`. `;
|
|
161
|
+
die(`could not clone ${redact(url)} into ${clone}, so it was removed again. git said:`, `${redact((r.stderr ?? '').trim())}\n${hint}Fix the cause, then run \`${rerun}\` again. If the repo`, 'is not pushed yet, or private to an account this machine lacks, nothing here is wrong: go on', 'without it.');
|
|
162
|
+
};
|
|
163
|
+
/** Stop unless `clone` is a clone ken may use as it is: a folder whose own `.git` git takes. */
|
|
164
|
+
const checkClone = (clone, key, again) => {
|
|
165
|
+
const stat = lstatSync(clone, { throwIfNoEntry: false });
|
|
166
|
+
if (!stat)
|
|
167
|
+
die(`${clone} is gone: another \`ken get ${key}\` was cloning into it and failed, saying why in`, `its own output. Run \`${again}\` again to clone it here.`);
|
|
168
|
+
const dotGit = stat.isDirectory()
|
|
169
|
+
? lstatSync(join(clone, '.git'), { throwIfNoEntry: false })
|
|
170
|
+
: undefined;
|
|
171
|
+
const what = stat.isSymbolicLink()
|
|
172
|
+
? `a symlink to ${readlinkSync(clone)}`
|
|
173
|
+
: !stat.isDirectory()
|
|
174
|
+
? 'a file'
|
|
175
|
+
: !dotGit
|
|
176
|
+
? 'a folder with no .git'
|
|
177
|
+
: !dotGit.isDirectory()
|
|
178
|
+
? 'a checkout whose .git is not a folder: a worktree, or a repo kept elsewhere'
|
|
179
|
+
: git(clone, 'rev-parse', '--absolute-git-dir').out !== join(clone, '.git')
|
|
180
|
+
? 'a folder whose .git git does not take as its repo'
|
|
181
|
+
: undefined;
|
|
182
|
+
if (what)
|
|
183
|
+
die(`${clone} is where the clone of ${key} belongs, but it is ${what}, so ken neither uses nor`, `replaces it. Move it aside, e.g. \`mv ${q(clone)} ~/${basename(clone)}.aside\`, then run`, `\`${again}\` again.${what === 'a folder with no .git'
|
|
184
|
+
? ` To make this folder the repo instead, run \`git init ${q(clone)}\` then \`${again}\`.`
|
|
185
|
+
: ''}`);
|
|
186
|
+
};
|
|
187
|
+
/** Write the entry of `key` when the index lists none: a clone holding `.ken` is a root whose
|
|
188
|
+
* front page opens with what it is for, so its first line of prose is the desc. */
|
|
189
|
+
const register = (root, key, clone) => {
|
|
190
|
+
const file = join(root, '.repos.index');
|
|
191
|
+
let note = '';
|
|
192
|
+
editIndex(root, key, (text, listed) => {
|
|
193
|
+
if (listed)
|
|
194
|
+
return undefined;
|
|
195
|
+
const readme = join(clone, 'README.md');
|
|
196
|
+
const desc = isFile(join(clone, '.ken')) && isFile(readme)
|
|
197
|
+
? readFileSync(readme, 'utf8')
|
|
198
|
+
// every line break the index's reader stops on, so the desc is one line
|
|
199
|
+
.split(/\r\n|[\n\r\u2028\u2029]/)
|
|
200
|
+
.find((line) => /^[^#\s<![|`-]/.test(line))
|
|
201
|
+
?.trimEnd()
|
|
202
|
+
: undefined;
|
|
203
|
+
note = desc
|
|
204
|
+
? `registered ${key} in ${file} with the first line of its front page as desc: "${desc}". Change it with \`ken index set ${key} desc="..."\`.`
|
|
205
|
+
: `registered ${key} in ${file} with no desc, and a desc is what lets an agent choose a repo before cloning it. Run \`ken index set ${key} desc="..."\` with what it is, in a line.`;
|
|
206
|
+
return setFields(text, key, desc ? [['desc', desc]] : []);
|
|
207
|
+
});
|
|
208
|
+
if (note)
|
|
209
|
+
say(note);
|
|
210
|
+
};
|
|
211
|
+
/** The worktree of `branch` beside `clone`, made when missing, or the clone for the default
|
|
212
|
+
* branch (PRD 5). */
|
|
213
|
+
const worktree = (clone, key, branch, from, folder, again) => {
|
|
214
|
+
// the full ref, as --short turns main into heads/main when a tag is named main too
|
|
215
|
+
const head = git(clone, 'symbolic-ref', '-q', 'HEAD');
|
|
216
|
+
if (!head.ok) {
|
|
217
|
+
const origin = git(clone, 'symbolic-ref', '-q', '--short', 'refs/remotes/origin/HEAD');
|
|
218
|
+
die(`${clone} has a detached HEAD, so it names no default branch, and the clone holds the`, 'default branch for every worktree to start from. Run', `\`git -C ${q(clone)} switch ${origin.ok ? origin.out.replace(/^origin\//, '') : 'main'}\``, `(or the default branch's name), then \`${again}\` again.`);
|
|
219
|
+
}
|
|
220
|
+
const def = head.out.replace(/^refs\/heads\//, '');
|
|
221
|
+
const exists = branch === def || git(clone, 'show-ref', '-q', '--verify', `refs/heads/${branch}`).ok;
|
|
222
|
+
if (exists && from !== undefined)
|
|
223
|
+
die(`${branch} exists in ${clone} already, so it is not made again from --from ${q(redact(from))}.`, `Run \`ken get ${key} -b ${q(branch)}\` for its worktree, or pick a new branch name.`);
|
|
224
|
+
if (branch === def)
|
|
225
|
+
return clone;
|
|
226
|
+
// the worktree holding the branch, asked of git one ref at a time and only for a branch
|
|
227
|
+
// that exists: refs/heads/feat would match refs/heads/feat/x too
|
|
228
|
+
const held = exists
|
|
229
|
+
? git(clone, 'for-each-ref', '--format=%(worktreepath)', `refs/heads/${branch}`).out
|
|
230
|
+
: '';
|
|
231
|
+
if (held && isDir(held))
|
|
232
|
+
return held;
|
|
233
|
+
if (held)
|
|
234
|
+
die(`${branch} is checked out in the worktree ${held}, whose folder is gone, and git checks a`, `branch out in one worktree at a time. Run \`git -C ${q(clone)} worktree prune\`, then`, `\`${again}\` again.`);
|
|
235
|
+
const wt = `${clone}${folder}`;
|
|
236
|
+
const parent = dirname(clone);
|
|
237
|
+
const name = basename(wt).toLowerCase();
|
|
238
|
+
const hitName = readdirSync(parent).find((n) => n.toLowerCase() === name);
|
|
239
|
+
if (hitName !== undefined) {
|
|
240
|
+
const hit = join(parent, hitName);
|
|
241
|
+
let its = git(hit, 'branch', '--show-current').out;
|
|
242
|
+
if (its &&
|
|
243
|
+
git(clone, 'for-each-ref', '--format=%(worktreepath)', `refs/heads/${its}`).out !== hit)
|
|
244
|
+
its = '';
|
|
245
|
+
let what = `${hit} is in the way`;
|
|
246
|
+
if (hit !== wt)
|
|
247
|
+
what = `${hit} differs only by case from it, one folder on a case-insensitive disk`;
|
|
248
|
+
if (its)
|
|
249
|
+
what += `, a worktree of ${clone} holding the branch ${its}`;
|
|
250
|
+
die(`the worktree of ${branch} belongs at ${wt}, but ${what}, so ken makes nothing. Pick another`, `branch name, or move it aside, e.g. \`mv ${q(hit)} ~/${basename(hit)}.aside\`, then`, `\`${again}\` again.`);
|
|
251
|
+
}
|
|
252
|
+
let madeBranch = false;
|
|
253
|
+
if (!exists) {
|
|
254
|
+
const start = from ?? 'HEAD';
|
|
255
|
+
const base = git(clone, 'rev-parse', '-q', '--verify', '--end-of-options', `${start}^{commit}`);
|
|
256
|
+
if (!base.ok) {
|
|
257
|
+
if (from !== undefined)
|
|
258
|
+
die(`${q(redact(from))} is no commit in ${clone}, so ${branch} cannot start from it. Run`, `\`git -C ${q(clone)} fetch --tags\` if it is on the remote, then \`${again}\` again.`);
|
|
259
|
+
die(`the default branch ${def} of ${clone} has no commit yet, so there is nothing to start`, `${branch} from. Commit to ${def} there first, or run`, `\`ken get ${key} -b ${q(branch)} --from <ref>\`.`);
|
|
260
|
+
}
|
|
261
|
+
// the lock: of two gets of one new branch, one makes it
|
|
262
|
+
const made = git(clone, 'branch', branch, base.out);
|
|
263
|
+
if (!made.ok) {
|
|
264
|
+
if (git(clone, 'show-ref', '-q', '--verify', `refs/heads/${branch}`).ok)
|
|
265
|
+
die(`${branch} was made in ${clone} just now, by another \`ken get\`, so this one made`, `nothing. Run \`ken get ${key} -b ${q(branch)}\`, without --from, for its worktree.`);
|
|
266
|
+
die(`could not make the branch ${branch} in ${clone}. git said: ${made.err.trim()}\n`, `Fix that, then run \`${again}\` again.`);
|
|
267
|
+
}
|
|
268
|
+
madeBranch = true;
|
|
269
|
+
}
|
|
270
|
+
let madeDir = false;
|
|
271
|
+
let err = '';
|
|
272
|
+
try {
|
|
273
|
+
mkdirSync(wt);
|
|
274
|
+
madeDir = true;
|
|
275
|
+
}
|
|
276
|
+
catch (e) {
|
|
277
|
+
err = e.message;
|
|
278
|
+
}
|
|
279
|
+
const added = madeDir ? git(clone, 'worktree', 'add', '-q', '--', wt, branch) : undefined;
|
|
280
|
+
if (!added?.ok) {
|
|
281
|
+
err = added?.err.trim() ?? err;
|
|
282
|
+
let undone = '';
|
|
283
|
+
if (madeDir) {
|
|
284
|
+
try {
|
|
285
|
+
rmdirSync(wt);
|
|
286
|
+
}
|
|
287
|
+
catch { }
|
|
288
|
+
undone = absent(wt)
|
|
289
|
+
? ` Removed the folder ${wt} again.`
|
|
290
|
+
: ` Left ${wt}, which is not empty: look inside.`;
|
|
291
|
+
}
|
|
292
|
+
// a folder made there since the checks is another get's claim, about to check it out
|
|
293
|
+
const wtStat = lstatSync(wt, { throwIfNoEntry: false });
|
|
294
|
+
if (!madeDir && wtStat?.isDirectory())
|
|
295
|
+
die(`${wt} was made just now, by another \`ken get\` adding the worktree of ${branch}, so this`, `one stops and leaves ${branch} to it. Run \`ken get ${key} -b ${q(branch)}\` for its worktree.`);
|
|
296
|
+
if (madeBranch && git(clone, 'branch', '-q', '-D', branch).ok)
|
|
297
|
+
undone += ` Deleted the branch ${branch} again.`;
|
|
298
|
+
else if (madeBranch)
|
|
299
|
+
undone += ` Left the branch ${branch}, which a worktree holds: \`git -C ${q(clone)} worktree list\`.`;
|
|
300
|
+
die(`could not make the worktree of ${branch} at ${wt}: ${err}\nSo ${branch} has no worktree.${undone}`, `Fix that, then run \`${again}\` again.`);
|
|
301
|
+
}
|
|
302
|
+
claudeLink(wt);
|
|
303
|
+
return wt;
|
|
304
|
+
};
|
package/dist/git.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// git, the core's one dependency beyond the runtime (PRD 20).
|
|
2
|
+
import { spawnSync } from 'node:child_process';
|
|
3
|
+
import { die } from "./die.js";
|
|
4
|
+
/** `git -C <cwd> <args>`: whether it succeeded, its stdout without the last newline, its stderr. */
|
|
5
|
+
export const git = (cwd, ...args) => {
|
|
6
|
+
const r = spawnSync('git', ['-C', cwd, ...args], { encoding: 'utf8' });
|
|
7
|
+
return { ok: r.status === 0, out: (r.stdout ?? '').replace(/\n$/, ''), err: r.stderr ?? '' };
|
|
8
|
+
};
|
|
9
|
+
/** Stop unless git 2.48 or newer is on PATH, for worktree.useRelativePaths; `again` is the
|
|
10
|
+
* command to rerun. */
|
|
11
|
+
export const checkGit = (again) => {
|
|
12
|
+
const r = spawnSync('git', ['--version'], { encoding: 'utf8' });
|
|
13
|
+
if (r.status !== 0)
|
|
14
|
+
die('git is not on PATH, and ken get clones with it. Install git 2.48 or newer', `(e.g. \`brew install git\`), then run \`${again}\` again.`);
|
|
15
|
+
const version = r.stdout.trim();
|
|
16
|
+
const [major = 0, minor = 0] = (/(\d+)\.(\d+)/.exec(version) ?? []).slice(1).map(Number);
|
|
17
|
+
if (major < 2 || (major === 2 && minor < 48))
|
|
18
|
+
die(`${version} is too old: ken needs git 2.48 or newer, for worktree.useRelativePaths, which lets`, 'a whole <owner>/ folder, or the root, move. Install it (e.g. `brew install git`), check', `\`git --version\`, then run \`${again}\` again.`);
|
|
19
|
+
};
|
|
20
|
+
/** Block for `ms` milliseconds: ken is synchronous, and a wait on another ken is rare. */
|
|
21
|
+
export const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
22
|
+
/** Whether the process `pid` is running. */
|
|
23
|
+
export const alive = (pid) => {
|
|
24
|
+
try {
|
|
25
|
+
process.kill(pid, 0);
|
|
26
|
+
return true;
|
|
27
|
+
}
|
|
28
|
+
catch (e) {
|
|
29
|
+
return e.code === 'EPERM';
|
|
30
|
+
}
|
|
31
|
+
};
|