worktree-bay 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/dist/cli.js +60 -0
- package/dist/commands/add.js +24 -0
- package/dist/commands/claim.js +11 -0
- package/dist/commands/completion.js +25 -0
- package/dist/commands/gc.js +46 -0
- package/dist/commands/ls.js +16 -0
- package/dist/commands/passthrough.js +26 -0
- package/dist/commands/rm.js +36 -0
- package/dist/config.js +56 -0
- package/dist/engine.js +76 -0
- package/dist/git.js +30 -0
- package/dist/lock.js +24 -0
- package/dist/naming.js +8 -0
- package/dist/ports.js +11 -0
- package/dist/slots.js +49 -0
- package/dist/util/exec.js +10 -0
- package/dist/util/log.js +3 -0
- package/package.json +54 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 hughcube
|
|
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/dist/cli.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { Command } from 'commander';
|
|
3
|
+
import { loadConfig } from './config.js';
|
|
4
|
+
import { claimCommand } from './commands/claim.js';
|
|
5
|
+
import { lsCommand } from './commands/ls.js';
|
|
6
|
+
import { addCommand } from './commands/add.js';
|
|
7
|
+
import { runCommand, shCommand } from './commands/passthrough.js';
|
|
8
|
+
import { rmCommand } from './commands/rm.js';
|
|
9
|
+
import { gcCommand } from './commands/gc.js';
|
|
10
|
+
import { complete, completionCommand } from './commands/completion.js';
|
|
11
|
+
import { die } from './util/log.js';
|
|
12
|
+
const program = new Command();
|
|
13
|
+
program.name('worktree-bay').description('worktree 槽位+端口编排器').version('0.1.0');
|
|
14
|
+
const sync = (fn) => { try {
|
|
15
|
+
fn(loadConfig(process.cwd()));
|
|
16
|
+
}
|
|
17
|
+
catch (e) {
|
|
18
|
+
die(e.message);
|
|
19
|
+
} };
|
|
20
|
+
program.command('claim <feature>').action(async (f) => { try {
|
|
21
|
+
await claimCommand(loadConfig(process.cwd()), f);
|
|
22
|
+
}
|
|
23
|
+
catch (e) {
|
|
24
|
+
die(e.message);
|
|
25
|
+
} });
|
|
26
|
+
program.command('ls').action(() => sync(lsCommand));
|
|
27
|
+
program.command('add <feature> <service> <branch> [base]').action(async (f, s, b, base) => { try {
|
|
28
|
+
await addCommand(loadConfig(process.cwd()), f, s, b, base);
|
|
29
|
+
}
|
|
30
|
+
catch (e) {
|
|
31
|
+
die(e.message);
|
|
32
|
+
} });
|
|
33
|
+
program.command('run <feature> <service> <name> [args...]').action((f, s, n, args) => sync((c) => runCommand(c, f, s, n, args ?? [])));
|
|
34
|
+
program.command('sh <feature> <service>').action((f, s) => sync((c) => shCommand(c, f, s)));
|
|
35
|
+
program.command('rm <feature> [service]').option('-f, --force').action(async (f, s, o) => { try {
|
|
36
|
+
await rmCommand(loadConfig(process.cwd()), f, s, !!o.force);
|
|
37
|
+
}
|
|
38
|
+
catch (e) {
|
|
39
|
+
die(e.message);
|
|
40
|
+
} });
|
|
41
|
+
program.command('gc').option('--apply').action(async (o) => { try {
|
|
42
|
+
await gcCommand(loadConfig(process.cwd()), !!o.apply);
|
|
43
|
+
}
|
|
44
|
+
catch (e) {
|
|
45
|
+
die(e.message);
|
|
46
|
+
} });
|
|
47
|
+
program.command('completion <shell>').action((sh) => { try {
|
|
48
|
+
completionCommand(sh);
|
|
49
|
+
}
|
|
50
|
+
catch (e) {
|
|
51
|
+
die(e.message);
|
|
52
|
+
} });
|
|
53
|
+
program.command('__complete', { hidden: true }).allowUnknownOption().action(() => {
|
|
54
|
+
const words = process.argv.slice(process.argv.indexOf('--') + 1);
|
|
55
|
+
try {
|
|
56
|
+
console.log(complete(loadConfig(process.cwd()), words).join('\n'));
|
|
57
|
+
}
|
|
58
|
+
catch { /* 静默 */ }
|
|
59
|
+
});
|
|
60
|
+
program.parseAsync(process.argv);
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { repoPath } from '../config.js';
|
|
3
|
+
import { withLock } from '../lock.js';
|
|
4
|
+
import { claim } from '../slots.js';
|
|
5
|
+
import { slugify, worktreeDirName } from '../naming.js';
|
|
6
|
+
import { buildVars, bringUp } from '../engine.js';
|
|
7
|
+
import { log } from '../util/log.js';
|
|
8
|
+
export function resolveAdd(cfg, feature, service, branch) {
|
|
9
|
+
if (!cfg.services[service])
|
|
10
|
+
throw new Error('unknown service: ' + service);
|
|
11
|
+
const slot = claim(cfg, feature);
|
|
12
|
+
const slug = worktreeDirName(slot, slugify(branch));
|
|
13
|
+
return { service, slot, slug, dir: path.join(repoPath(cfg, service), '.worktrees', slug), repo: repoPath(cfg, service) };
|
|
14
|
+
}
|
|
15
|
+
export async function addCommand(cfg, feature, service, branch, base) {
|
|
16
|
+
await withLock(cfg.workspaceRoot, async () => {
|
|
17
|
+
const p = resolveAdd(cfg, feature, service, branch);
|
|
18
|
+
const sp = cfg.services[service];
|
|
19
|
+
const ctxBase = { cfg, service, sp, slot: p.slot, slug: p.slug, dir: p.dir, repo: p.repo };
|
|
20
|
+
const ctx = { ...ctxBase, vars: buildVars(cfg, ctxBase) };
|
|
21
|
+
await bringUp(ctx, base ?? 'origin/HEAD', branch);
|
|
22
|
+
log(`✓ ${service} 挂入 "${feature}"(槽 ${p.slot},端口 ${ctx.vars.port})`);
|
|
23
|
+
});
|
|
24
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { withLock } from '../lock.js';
|
|
2
|
+
import { claim } from '../slots.js';
|
|
3
|
+
import { blockBase } from '../ports.js';
|
|
4
|
+
import { log } from '../util/log.js';
|
|
5
|
+
export async function claimCommand(cfg, feature) {
|
|
6
|
+
const slot = await withLock(cfg.workspaceRoot, async () => claim(cfg, feature));
|
|
7
|
+
const base = blockBase(cfg.portBase, cfg.slotSpan, slot);
|
|
8
|
+
log(`功能 "${feature}" → 槽 ${slot}(块 ${base})`);
|
|
9
|
+
for (const [n, sp] of Object.entries(cfg.services))
|
|
10
|
+
log(` ${n.padEnd(8)} ${base + sp.offset}`);
|
|
11
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { readLabels } from '../slots.js';
|
|
2
|
+
import { log } from '../util/log.js';
|
|
3
|
+
const SUBCMDS = ['claim', 'add', 'ls', 'gc', 'rm', 'run', 'sh', 'completion'];
|
|
4
|
+
export function complete(cfg, words) {
|
|
5
|
+
const args = words.slice(1);
|
|
6
|
+
if (args.length === 0)
|
|
7
|
+
return SUBCMDS;
|
|
8
|
+
const sub = args[0];
|
|
9
|
+
const pos = args.length;
|
|
10
|
+
if (['add', 'rm', 'run', 'sh'].includes(sub) && pos === 1)
|
|
11
|
+
return Object.values(readLabels(cfg));
|
|
12
|
+
if (['add', 'run', 'sh'].includes(sub) && pos === 2)
|
|
13
|
+
return Object.keys(cfg.services);
|
|
14
|
+
return [];
|
|
15
|
+
}
|
|
16
|
+
export function completionScript(shell) {
|
|
17
|
+
if (shell === 'bash')
|
|
18
|
+
return `_worktree_bay(){ COMPREPLY=( $(worktree-bay __complete -- "\${COMP_WORDS[@]}") ); }\ncomplete -F _worktree_bay worktree-bay`;
|
|
19
|
+
if (shell === 'zsh')
|
|
20
|
+
return `#compdef worktree-bay\n_worktree_bay(){ compadd -- $(worktree-bay __complete -- "\${words[@]}") }\ncompdef _worktree_bay worktree-bay`;
|
|
21
|
+
if (shell === 'fish')
|
|
22
|
+
return `complete -c worktree-bay -a '(worktree-bay __complete -- (commandline -opc))'`;
|
|
23
|
+
throw new Error('unsupported shell: ' + shell);
|
|
24
|
+
}
|
|
25
|
+
export function completionCommand(shell) { log(completionScript(shell)); }
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { repoPath, renderTemplate } from '../config.js';
|
|
2
|
+
import { withLock } from '../lock.js';
|
|
3
|
+
import { scanOccupancy, pruneEmptyLabels, removeLabel } from '../slots.js';
|
|
4
|
+
import { buildVars } from '../engine.js';
|
|
5
|
+
import { currentBranch, isDirty, hasUnpushed, isMergedToMain, remoteBranchGone, removeWorktree } from '../git.js';
|
|
6
|
+
import { runShell } from '../util/exec.js';
|
|
7
|
+
import { log, warn } from '../util/log.js';
|
|
8
|
+
export function classifyForGc(s) {
|
|
9
|
+
if (s.merged && !s.dirty && !s.unpushed)
|
|
10
|
+
return 'auto-remove';
|
|
11
|
+
if (s.merged)
|
|
12
|
+
return 'flag';
|
|
13
|
+
return 'keep';
|
|
14
|
+
}
|
|
15
|
+
export async function gcCommand(cfg, apply) {
|
|
16
|
+
await withLock(cfg.workspaceRoot, async () => {
|
|
17
|
+
for (const [slot, occupants] of scanOccupancy(cfg))
|
|
18
|
+
for (const o of occupants) {
|
|
19
|
+
const repo = repoPath(cfg, o.service);
|
|
20
|
+
const branch = currentBranch(o.dir);
|
|
21
|
+
const v = classifyForGc({ merged: isMergedToMain(repo, branch), dirty: isDirty(o.dir), unpushed: hasUnpushed(repo, branch) });
|
|
22
|
+
if (v === 'auto-remove') {
|
|
23
|
+
log(`[gc] ${o.service} (slot ${slot}) 已合并且干净 → 移除`);
|
|
24
|
+
if (apply) {
|
|
25
|
+
const sp = cfg.services[o.service];
|
|
26
|
+
if (sp.teardown) {
|
|
27
|
+
const vars = buildVars(cfg, { cfg, service: o.service, sp, slot, slug: o.slug, dir: o.dir, repo });
|
|
28
|
+
runShell(renderTemplate(sp.teardown, vars), { cwd: repo });
|
|
29
|
+
}
|
|
30
|
+
removeWorktree(repo, o.dir, false);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
else if (v === 'flag')
|
|
34
|
+
warn(`[gc] ${o.service} (slot ${slot}) 已合并但脏/未推 → 跳过,确认后手动删`);
|
|
35
|
+
else if (remoteBranchGone(repo, branch))
|
|
36
|
+
warn(`[gc] ${o.service} (slot ${slot}) 远端分支已删(疑似 squash)→ 确认后 bay rm`);
|
|
37
|
+
}
|
|
38
|
+
for (const { slot, feature } of pruneEmptyLabels(cfg)) {
|
|
39
|
+
log(`[gc] 槽 ${slot}(${feature})空预约(无 worktree)`);
|
|
40
|
+
if (apply)
|
|
41
|
+
removeLabel(cfg, slot);
|
|
42
|
+
}
|
|
43
|
+
if (!apply)
|
|
44
|
+
log('(dry-run;加 --apply 执行 auto-remove 与空预约清理)');
|
|
45
|
+
});
|
|
46
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { scanOccupancy, readLabels } from '../slots.js';
|
|
2
|
+
import { blockBase } from '../ports.js';
|
|
3
|
+
import { log } from '../util/log.js';
|
|
4
|
+
export function renderSlots(cfg) {
|
|
5
|
+
const occ = scanOccupancy(cfg);
|
|
6
|
+
const labels = readLabels(cfg);
|
|
7
|
+
const slots = new Set([...occ.keys(), ...Object.keys(labels).map(Number)]);
|
|
8
|
+
const lines = [];
|
|
9
|
+
for (const n of [...slots].sort((a, b) => a - b)) {
|
|
10
|
+
const base = blockBase(cfg.portBase, cfg.slotSpan, n);
|
|
11
|
+
const svc = (occ.get(n) ?? []).map((o) => `${o.service}@${base + cfg.services[o.service].offset}`);
|
|
12
|
+
lines.push(`slot ${n} ${labels[String(n)] ?? '(unnamed)'} api=${base + 1} [${svc.join(', ') || 'no worktree'}]`);
|
|
13
|
+
}
|
|
14
|
+
return lines.join('\n') || '(no slots in use)';
|
|
15
|
+
}
|
|
16
|
+
export function lsCommand(cfg) { log(renderSlots(cfg)); }
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { repoPath } from '../config.js';
|
|
2
|
+
import { scanOccupancy, slotOfFeature } from '../slots.js';
|
|
3
|
+
import { buildVars, execArgv, run } from '../engine.js';
|
|
4
|
+
function ctxOf(cfg, feature, service) {
|
|
5
|
+
const slot = slotOfFeature(cfg, feature);
|
|
6
|
+
if (slot === undefined)
|
|
7
|
+
throw new Error('unknown feature: ' + feature);
|
|
8
|
+
const occ = (scanOccupancy(cfg).get(slot) ?? []).find((o) => o.service === service);
|
|
9
|
+
if (!occ)
|
|
10
|
+
throw new Error(`${service} not in ${feature}`);
|
|
11
|
+
const sp = cfg.services[service];
|
|
12
|
+
return { sp, vars: buildVars(cfg, { cfg, service, sp, slot, slug: occ.slug, dir: occ.dir, repo: repoPath(cfg, service) }) };
|
|
13
|
+
}
|
|
14
|
+
export function runCommand(cfg, feature, service, name, args) {
|
|
15
|
+
const ctx = ctxOf(cfg, feature, service);
|
|
16
|
+
const named = ctx.sp.run?.[name];
|
|
17
|
+
if (!named)
|
|
18
|
+
throw new Error(`run.${name} 未定义于 ${service}`);
|
|
19
|
+
const argv = execArgv(ctx, [...named, ...args]);
|
|
20
|
+
process.exit(run(argv[0], argv.slice(1)).code);
|
|
21
|
+
}
|
|
22
|
+
export function shCommand(cfg, feature, service) {
|
|
23
|
+
const ctx = ctxOf(cfg, feature, service);
|
|
24
|
+
const argv = execArgv(ctx, ['sh']);
|
|
25
|
+
process.exit(run(argv[0], argv.slice(1)).code);
|
|
26
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { repoPath, renderTemplate } from '../config.js';
|
|
2
|
+
import { withLock } from '../lock.js';
|
|
3
|
+
import { scanOccupancy, slotOfFeature, removeLabel } from '../slots.js';
|
|
4
|
+
import { buildVars } from '../engine.js';
|
|
5
|
+
import { isDirty, hasUnpushed, currentBranch, removeWorktree } from '../git.js';
|
|
6
|
+
import { runShell } from '../util/exec.js';
|
|
7
|
+
import { log, warn } from '../util/log.js';
|
|
8
|
+
export function resolveRm(cfg, feature, service) {
|
|
9
|
+
const slot = slotOfFeature(cfg, feature);
|
|
10
|
+
if (slot === undefined)
|
|
11
|
+
throw new Error('unknown feature: ' + feature);
|
|
12
|
+
const all = scanOccupancy(cfg).get(slot) ?? [];
|
|
13
|
+
return service ? all.filter((o) => o.service === service) : all;
|
|
14
|
+
}
|
|
15
|
+
export async function rmCommand(cfg, feature, service, force) {
|
|
16
|
+
await withLock(cfg.workspaceRoot, async () => {
|
|
17
|
+
for (const o of resolveRm(cfg, feature, service)) {
|
|
18
|
+
const repo = repoPath(cfg, o.service);
|
|
19
|
+
const branch = currentBranch(o.dir);
|
|
20
|
+
if (!force && (isDirty(o.dir) || hasUnpushed(repo, branch))) {
|
|
21
|
+
warn(`跳过 ${o.service}:有未提交/未推改动(-f 强删)`);
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
const sp = cfg.services[o.service];
|
|
25
|
+
if (sp.teardown) {
|
|
26
|
+
const vars = buildVars(cfg, { cfg, service: o.service, sp, slot: o.slot, slug: o.slug, dir: o.dir, repo });
|
|
27
|
+
runShell(renderTemplate(sp.teardown, vars), { cwd: repo });
|
|
28
|
+
}
|
|
29
|
+
removeWorktree(repo, o.dir, force);
|
|
30
|
+
log(`✓ 移除 ${o.service}`);
|
|
31
|
+
}
|
|
32
|
+
const slot = slotOfFeature(cfg, feature);
|
|
33
|
+
if (!service && (scanOccupancy(cfg).get(slot) ?? []).length === 0)
|
|
34
|
+
removeLabel(cfg, slot);
|
|
35
|
+
});
|
|
36
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
function refs(tpl) { return [...tpl.matchAll(/\{(\w+)\}/g)].map((m) => m[1]); }
|
|
4
|
+
export function parseConfig(configPath) {
|
|
5
|
+
const raw = JSON.parse(fs.readFileSync(configPath, 'utf8'));
|
|
6
|
+
for (const k of ['workspaceRoot', 'portBase', 'slotSpan', 'maxSlots'])
|
|
7
|
+
if (raw[k] === undefined)
|
|
8
|
+
throw new Error(`config: ${k} required`);
|
|
9
|
+
const services = raw.services ?? {};
|
|
10
|
+
const offsets = new Set();
|
|
11
|
+
for (const [name, sp] of Object.entries(services)) {
|
|
12
|
+
if (typeof sp.offset !== 'number')
|
|
13
|
+
throw new Error(`config: ${name}.offset required`);
|
|
14
|
+
if (sp.offset < 1 || sp.offset >= raw.slotSpan)
|
|
15
|
+
throw new Error(`config: ${name}.offset must be 1..${raw.slotSpan - 1}`); // V2
|
|
16
|
+
if (offsets.has(sp.offset))
|
|
17
|
+
throw new Error(`config: duplicate offset ${sp.offset} (${name})`); // V1
|
|
18
|
+
offsets.add(sp.offset);
|
|
19
|
+
const repoDir = path.join(raw.workspaceRoot, sp.repo ?? name);
|
|
20
|
+
if (!fs.existsSync(repoDir))
|
|
21
|
+
throw new Error(`config: ${name}.repo dir missing: ${repoDir}`); // V5
|
|
22
|
+
}
|
|
23
|
+
for (const [name, sp] of Object.entries(services))
|
|
24
|
+
if (sp.upstream && !services[sp.upstream.service])
|
|
25
|
+
throw new Error(`config: ${name}.upstream.service '${sp.upstream.service}' not found`); // V3
|
|
26
|
+
const known = new Set(['slot', 'blockBase', 'port', 'slug', 'worktree', 'repo', 'upstreamBase', 'cmd']); // V4
|
|
27
|
+
for (const sp of Object.values(services))
|
|
28
|
+
for (const v of Object.values(sp.vars ?? {}))
|
|
29
|
+
for (const ref of refs(v))
|
|
30
|
+
if (!known.has(ref) && !(sp.vars && ref in sp.vars))
|
|
31
|
+
throw new Error(`config: unknown template var {${ref}}`);
|
|
32
|
+
return { workspaceRoot: raw.workspaceRoot, portBase: raw.portBase, slotSpan: raw.slotSpan, maxSlots: raw.maxSlots, services, configDir: path.dirname(configPath) };
|
|
33
|
+
}
|
|
34
|
+
export function loadConfig(startDir) {
|
|
35
|
+
if (process.env.WORKTREE_BAY_CONFIG)
|
|
36
|
+
return parseConfig(process.env.WORKTREE_BAY_CONFIG);
|
|
37
|
+
let dir = path.resolve(startDir);
|
|
38
|
+
for (;;) {
|
|
39
|
+
const p = path.join(dir, 'worktree-bay.config.json');
|
|
40
|
+
if (fs.existsSync(p))
|
|
41
|
+
return parseConfig(p);
|
|
42
|
+
const parent = path.dirname(dir);
|
|
43
|
+
if (parent === dir)
|
|
44
|
+
throw new Error('worktree-bay.config.json not found');
|
|
45
|
+
dir = parent;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
export function repoPath(cfg, service) {
|
|
49
|
+
const sp = cfg.services[service];
|
|
50
|
+
if (!sp)
|
|
51
|
+
throw new Error('unknown service: ' + service);
|
|
52
|
+
return path.join(cfg.workspaceRoot, sp.repo ?? service);
|
|
53
|
+
}
|
|
54
|
+
export function renderTemplate(tpl, vars) {
|
|
55
|
+
return tpl.replace(/\{(\w+)\}/g, (_, k) => (vars[k] !== undefined ? String(vars[k]) : `{${k}}`));
|
|
56
|
+
}
|
package/dist/engine.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { renderTemplate } from './config.js';
|
|
4
|
+
import { blockBase, portOf, isPortFree } from './ports.js';
|
|
5
|
+
import { scanOccupancy } from './slots.js';
|
|
6
|
+
import { addWorktree } from './git.js';
|
|
7
|
+
import { runShell, run, spliceArgv, isTTY } from './util/exec.js';
|
|
8
|
+
import { warn, log } from './util/log.js';
|
|
9
|
+
export function mergeEnvText(text, kv) {
|
|
10
|
+
const lines = text.split('\n');
|
|
11
|
+
const seen = new Set();
|
|
12
|
+
const out = lines.map((line) => { const m = /^([A-Za-z_][A-Za-z0-9_]*)=/.exec(line); if (m && kv[m[1]] !== undefined) {
|
|
13
|
+
seen.add(m[1]);
|
|
14
|
+
return `${m[1]}=${kv[m[1]]}`;
|
|
15
|
+
} return line; });
|
|
16
|
+
for (const [k, v] of Object.entries(kv))
|
|
17
|
+
if (!seen.has(k)) {
|
|
18
|
+
if (out.length && out[out.length - 1] === '')
|
|
19
|
+
out.splice(out.length - 1, 0, `${k}=${v}`);
|
|
20
|
+
else
|
|
21
|
+
out.push(`${k}=${v}`);
|
|
22
|
+
}
|
|
23
|
+
return out.join('\n');
|
|
24
|
+
}
|
|
25
|
+
export function resolveUpstreamBase(cfg, slot, up, materialized) {
|
|
26
|
+
return materialized ? `http://localhost:${portOf(cfg.portBase, cfg.slotSpan, slot, cfg.services[up.service].offset)}` : up.fallback;
|
|
27
|
+
}
|
|
28
|
+
function upstreamMaterialized(cfg, slot, service) {
|
|
29
|
+
return (scanOccupancy(cfg).get(slot) ?? []).some((o) => o.service === service);
|
|
30
|
+
}
|
|
31
|
+
export function buildVars(cfg, ctx) {
|
|
32
|
+
const base = { slot: ctx.slot, blockBase: blockBase(cfg.portBase, cfg.slotSpan, ctx.slot), port: portOf(cfg.portBase, cfg.slotSpan, ctx.slot, ctx.sp.offset), slug: ctx.slug, worktree: ctx.dir, repo: ctx.repo };
|
|
33
|
+
if (ctx.sp.upstream)
|
|
34
|
+
base.upstreamBase = resolveUpstreamBase(cfg, ctx.slot, ctx.sp.upstream, upstreamMaterialized(cfg, ctx.slot, ctx.sp.upstream.service));
|
|
35
|
+
for (const [k, v] of Object.entries(ctx.sp.vars ?? {}))
|
|
36
|
+
base[k] = renderTemplate(v, base);
|
|
37
|
+
return base;
|
|
38
|
+
}
|
|
39
|
+
export async function bringUp(ctx, base, branch) {
|
|
40
|
+
const { sp, dir, repo, vars } = ctx;
|
|
41
|
+
if (!(await isPortFree(Number(vars.port))))
|
|
42
|
+
throw new Error(`port ${vars.port} 被占用(Codex#11)`);
|
|
43
|
+
addWorktree(repo, dir, branch, base);
|
|
44
|
+
for (const rel of sp.copy ?? []) {
|
|
45
|
+
// dereference: vendor/node_modules 含符号链接,Windows 下原样复制符号链接会失败,跟随并拷目标内容
|
|
46
|
+
fs.cpSync(path.join(repo, rel), path.join(dir, rel), { recursive: true, dereference: true });
|
|
47
|
+
for (const lock of ['composer.lock', 'pnpm-lock.yaml', 'package-lock.json']) {
|
|
48
|
+
const a = path.join(repo, lock), b = path.join(dir, lock);
|
|
49
|
+
if (fs.existsSync(a) && fs.existsSync(b) && fs.readFileSync(a, 'utf8') !== fs.readFileSync(b, 'utf8'))
|
|
50
|
+
warn(`⚠ ${lock} 与主 checkout 不一致,拷来依赖可能版本错位,建议改跑安装(Codex#18)`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
for (const [file, kv] of Object.entries(sp.env ?? {})) {
|
|
54
|
+
const fp = path.join(dir, file);
|
|
55
|
+
const cur = fs.existsSync(fp) ? fs.readFileSync(fp, 'utf8') : '';
|
|
56
|
+
const rendered = {};
|
|
57
|
+
for (const [k, v] of Object.entries(kv))
|
|
58
|
+
rendered[k] = renderTemplate(v, vars);
|
|
59
|
+
fs.writeFileSync(fp, mergeEnvText(cur, rendered));
|
|
60
|
+
}
|
|
61
|
+
if (sp.setup) {
|
|
62
|
+
const r = runShell(renderTemplate(sp.setup, vars), { cwd: dir });
|
|
63
|
+
if (r.code !== 0)
|
|
64
|
+
throw new Error('setup 失败');
|
|
65
|
+
}
|
|
66
|
+
if (sp.start)
|
|
67
|
+
log(` 启动: (cd ${dir} && ${renderTemplate(sp.start, vars)})`);
|
|
68
|
+
}
|
|
69
|
+
export function execArgv(ctx, cmd) {
|
|
70
|
+
const tpl = (ctx.sp.exec ?? ['sh', '-c', '{cmd...}']).map((el) => el === '{cmd...}' ? el : renderTemplate(el, ctx.vars));
|
|
71
|
+
const spliced = spliceArgv(tpl, cmd);
|
|
72
|
+
if (isTTY() && cmd[0] === 'sh' && spliced.includes('exec'))
|
|
73
|
+
spliced.splice(spliced.indexOf('exec') + 1, 0, '-it');
|
|
74
|
+
return spliced;
|
|
75
|
+
}
|
|
76
|
+
export { run };
|
package/dist/git.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
function git(repo, ...a) { return spawnSync('git', ['-C', repo, ...a], { encoding: 'utf8' }); }
|
|
3
|
+
function ok(repo, ...a) { const r = git(repo, ...a); if (r.status !== 0)
|
|
4
|
+
throw new Error(`git ${a.join(' ')}: ${r.stderr || r.stdout}`); return r.stdout; }
|
|
5
|
+
export function addWorktree(repo, dir, branch, base) { ok(repo, 'worktree', 'add', '-b', branch, dir, base); }
|
|
6
|
+
export function removeWorktree(repo, dir, force) { const a = ['worktree', 'remove', dir]; if (force)
|
|
7
|
+
a.push('--force'); const r = git(repo, ...a); if (r.status !== 0)
|
|
8
|
+
throw new Error('worktree remove: ' + (r.stderr || r.stdout)); git(repo, 'worktree', 'prune'); }
|
|
9
|
+
export function isDirty(dir) { return ok(dir, 'status', '--porcelain').trim().length > 0; }
|
|
10
|
+
export function currentBranch(dir) { return ok(dir, 'rev-parse', '--abbrev-ref', 'HEAD').trim(); }
|
|
11
|
+
export function mainBranch(repo) {
|
|
12
|
+
const r = git(repo, 'symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD');
|
|
13
|
+
if (r.status === 0 && r.stdout.trim())
|
|
14
|
+
return r.stdout.trim().replace(/^origin\//, '');
|
|
15
|
+
for (const b of ['master', 'main'])
|
|
16
|
+
if (git(repo, 'rev-parse', '--verify', `origin/${b}`).status === 0)
|
|
17
|
+
return b;
|
|
18
|
+
return 'master';
|
|
19
|
+
}
|
|
20
|
+
export function isMergedToMain(repo, branch) { git(repo, 'fetch', '-q', 'origin'); return git(repo, 'merge-base', '--is-ancestor', branch, `origin/${mainBranch(repo)}`).status === 0; }
|
|
21
|
+
export function remoteBranchGone(repo, branch) { return git(repo, 'rev-parse', '--verify', `origin/${branch}`).status !== 0; }
|
|
22
|
+
export function hasUnpushed(repo, branch) {
|
|
23
|
+
const main = mainBranch(repo);
|
|
24
|
+
const r = git(repo, 'log', '--oneline', `origin/${main}..${branch}`);
|
|
25
|
+
if (r.status !== 0)
|
|
26
|
+
return true;
|
|
27
|
+
if (!r.stdout.trim())
|
|
28
|
+
return false;
|
|
29
|
+
return remoteBranchGone(repo, branch) ? true : git(repo, 'log', '--oneline', `origin/${branch}..${branch}`).stdout.trim().length > 0;
|
|
30
|
+
}
|
package/dist/lock.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
export async function withLock(ws, fn) {
|
|
4
|
+
const lockDir = path.join(ws, '.worktree-bay', 'lock');
|
|
5
|
+
fs.mkdirSync(path.join(ws, '.worktree-bay'), { recursive: true });
|
|
6
|
+
const start = Date.now();
|
|
7
|
+
for (;;) {
|
|
8
|
+
try {
|
|
9
|
+
fs.mkdirSync(lockDir);
|
|
10
|
+
break;
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
if (Date.now() - start > 30000)
|
|
14
|
+
throw new Error('worktree-bay: lock timeout (另一个 worktree-bay 在运行?)');
|
|
15
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
try {
|
|
19
|
+
return await fn();
|
|
20
|
+
}
|
|
21
|
+
finally {
|
|
22
|
+
fs.rmdirSync(lockDir);
|
|
23
|
+
}
|
|
24
|
+
}
|
package/dist/naming.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export function slugify(branch) {
|
|
2
|
+
return branch.replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-+|-+$/g, '').toLowerCase().slice(0, 40).replace(/-+$/g, '');
|
|
3
|
+
}
|
|
4
|
+
export function worktreeDirName(slot, slug) { return `s${slot}-${slug}`; }
|
|
5
|
+
export function parseWorktreeDir(name) {
|
|
6
|
+
const m = /^s(\d+)-(.+)$/.exec(name);
|
|
7
|
+
return m ? { slot: Number(m[1]), slug: m[2] } : null;
|
|
8
|
+
}
|
package/dist/ports.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import net from 'node:net';
|
|
2
|
+
export function blockBase(portBase, slotSpan, slot) { return portBase + slot * slotSpan; }
|
|
3
|
+
export function portOf(portBase, slotSpan, slot, offset) { return blockBase(portBase, slotSpan, slot) + offset; }
|
|
4
|
+
export function isPortFree(port) {
|
|
5
|
+
return new Promise((resolve) => {
|
|
6
|
+
const srv = net.createServer();
|
|
7
|
+
srv.once('error', () => resolve(false));
|
|
8
|
+
srv.once('listening', () => srv.close(() => resolve(true)));
|
|
9
|
+
srv.listen(port, '127.0.0.1');
|
|
10
|
+
});
|
|
11
|
+
}
|
package/dist/slots.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { repoPath } from './config.js';
|
|
4
|
+
import { parseWorktreeDir } from './naming.js';
|
|
5
|
+
export function scanOccupancy(cfg) {
|
|
6
|
+
const map = new Map();
|
|
7
|
+
for (const service of Object.keys(cfg.services)) {
|
|
8
|
+
const root = path.join(repoPath(cfg, service), '.worktrees');
|
|
9
|
+
if (!fs.existsSync(root))
|
|
10
|
+
continue;
|
|
11
|
+
for (const e of fs.readdirSync(root, { withFileTypes: true })) {
|
|
12
|
+
if (!e.isDirectory())
|
|
13
|
+
continue;
|
|
14
|
+
const p = parseWorktreeDir(e.name);
|
|
15
|
+
if (!p)
|
|
16
|
+
continue;
|
|
17
|
+
const list = map.get(p.slot) ?? [];
|
|
18
|
+
list.push({ service, slot: p.slot, slug: e.name, dir: path.join(root, e.name) });
|
|
19
|
+
map.set(p.slot, list);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return map;
|
|
23
|
+
}
|
|
24
|
+
function labelPath(cfg) { return path.join(cfg.workspaceRoot, '.worktree-bay-slots.json'); }
|
|
25
|
+
export function readLabels(cfg) { const p = labelPath(cfg); return fs.existsSync(p) ? JSON.parse(fs.readFileSync(p, 'utf8')) : {}; }
|
|
26
|
+
function save(cfg, l) { fs.writeFileSync(labelPath(cfg), JSON.stringify(l, null, 2) + '\n'); }
|
|
27
|
+
export function writeLabel(cfg, slot, f) { const l = readLabels(cfg); l[String(slot)] = f; save(cfg, l); }
|
|
28
|
+
export function removeLabel(cfg, slot) { const l = readLabels(cfg); delete l[String(slot)]; save(cfg, l); }
|
|
29
|
+
export function slotOfFeature(cfg, f) { for (const [k, v] of Object.entries(readLabels(cfg)))
|
|
30
|
+
if (v === f)
|
|
31
|
+
return Number(k); return undefined; }
|
|
32
|
+
export function freeSlot(cfg) {
|
|
33
|
+
const occ = scanOccupancy(cfg);
|
|
34
|
+
const l = readLabels(cfg);
|
|
35
|
+
for (let n = 1; n <= cfg.maxSlots; n++)
|
|
36
|
+
if (!occ.has(n) && l[String(n)] === undefined)
|
|
37
|
+
return n;
|
|
38
|
+
throw new Error(`no free slot (1..${cfg.maxSlots} all taken)`);
|
|
39
|
+
}
|
|
40
|
+
export function claim(cfg, f) { const e = slotOfFeature(cfg, f); if (e !== undefined)
|
|
41
|
+
return e; const n = freeSlot(cfg); writeLabel(cfg, n, f); return n; }
|
|
42
|
+
export function pruneEmptyLabels(cfg) {
|
|
43
|
+
const occ = scanOccupancy(cfg);
|
|
44
|
+
const removed = [];
|
|
45
|
+
for (const [k, v] of Object.entries(readLabels(cfg)))
|
|
46
|
+
if (!occ.has(Number(k)))
|
|
47
|
+
removed.push({ slot: Number(k), feature: v });
|
|
48
|
+
return removed;
|
|
49
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
export function run(cmd, args, opts = {}) { const r = spawnSync(cmd, args, { cwd: opts.cwd, stdio: 'inherit', shell: false }); return { code: r.status ?? 1 }; }
|
|
3
|
+
export function runShell(line, opts = {}) { const r = spawnSync(line, { cwd: opts.cwd, stdio: 'inherit', shell: true }); return { code: r.status ?? 1 }; }
|
|
4
|
+
export function spliceArgv(template, cmd) { const out = []; for (const el of template) {
|
|
5
|
+
if (el === '{cmd...}')
|
|
6
|
+
out.push(...cmd);
|
|
7
|
+
else
|
|
8
|
+
out.push(el);
|
|
9
|
+
} return out; }
|
|
10
|
+
export function isTTY() { return Boolean(process.stdout.isTTY && process.stdin.isTTY); }
|
package/dist/util/log.js
ADDED
package/package.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "worktree-bay",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Config-driven git worktree slot + port orchestrator for parallel multi-service development",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"git",
|
|
7
|
+
"worktree",
|
|
8
|
+
"monorepo",
|
|
9
|
+
"cli",
|
|
10
|
+
"ports",
|
|
11
|
+
"orchestration",
|
|
12
|
+
"parallel",
|
|
13
|
+
"dev"
|
|
14
|
+
],
|
|
15
|
+
"type": "module",
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"author": "hughcube",
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/hughcube/worktree-bay.git"
|
|
21
|
+
},
|
|
22
|
+
"bugs": {
|
|
23
|
+
"url": "https://github.com/hughcube/worktree-bay/issues"
|
|
24
|
+
},
|
|
25
|
+
"homepage": "https://github.com/hughcube/worktree-bay#readme",
|
|
26
|
+
"bin": {
|
|
27
|
+
"worktree-bay": "dist/cli.js"
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"dist"
|
|
31
|
+
],
|
|
32
|
+
"engines": {
|
|
33
|
+
"node": ">=20"
|
|
34
|
+
},
|
|
35
|
+
"scripts": {
|
|
36
|
+
"build": "tsc -p tsconfig.json",
|
|
37
|
+
"dev": "tsx src/cli.ts",
|
|
38
|
+
"test": "vitest run",
|
|
39
|
+
"prepublishOnly": "npm run build"
|
|
40
|
+
},
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public",
|
|
43
|
+
"registry": "https://registry.npmjs.org"
|
|
44
|
+
},
|
|
45
|
+
"dependencies": {
|
|
46
|
+
"commander": "^12.1.0"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@types/node": "^22.0.0",
|
|
50
|
+
"tsx": "^4.19.0",
|
|
51
|
+
"typescript": "^5.6.0",
|
|
52
|
+
"vitest": "^2.1.0"
|
|
53
|
+
}
|
|
54
|
+
}
|