@coding-with-hassan/devkit 0.4.0 → 1.0.0-next.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/README.md +69 -0
- package/package.json +6 -2
- package/src/commands/config.js +117 -0
- package/src/commands/docker.js +9 -0
- package/src/commands/init.js +127 -0
- package/src/commands/worktree.js +37 -0
- package/src/core/agents-docs.js +225 -0
- package/src/core/compose.js +69 -0
- package/src/core/config.js +316 -0
- package/src/core/derive.js +130 -0
- package/src/core/env-block.js +76 -0
- package/src/core/exec.js +45 -0
- package/src/core/git.js +77 -0
- package/src/core/locks.js +60 -0
- package/src/core/root.js +30 -0
- package/src/core/scaffold.js +131 -0
- package/src/core/stack.js +63 -0
- package/src/core/tracker/github.js +29 -0
- package/src/core/tracker/index.js +37 -0
- package/src/core/tracker/jira.js +101 -0
- package/src/core/workspace.js +105 -0
- package/src/core/worktrees.js +564 -0
- package/src/index.js +6 -0
package/src/core/git.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { capture, run } from './exec.js';
|
|
2
|
+
|
|
3
|
+
/** Thin git helpers; every call takes the checkout directory explicitly. */
|
|
4
|
+
|
|
5
|
+
export const git = (dir, args, opts = {}) => capture('git', args, { cwd: dir, ...opts });
|
|
6
|
+
|
|
7
|
+
/** The main checkout of the repository `dir` belongs to (first entry of `worktree list`). */
|
|
8
|
+
export function mainRoot(dir) {
|
|
9
|
+
const first = git(dir, ['worktree', 'list', '--porcelain']).split('\n')[0] ?? '';
|
|
10
|
+
return first.replace(/^worktree /, '');
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** All worktrees of the repository as `{ path, head, branch }` (branch `null` when detached). */
|
|
14
|
+
export function listWorktrees(dir) {
|
|
15
|
+
const out = git(dir, ['worktree', 'list', '--porcelain']);
|
|
16
|
+
const entries = [];
|
|
17
|
+
let current = null;
|
|
18
|
+
for (const line of out.split('\n')) {
|
|
19
|
+
if (line.startsWith('worktree ')) {
|
|
20
|
+
current = { path: line.slice(9), head: null, branch: null };
|
|
21
|
+
entries.push(current);
|
|
22
|
+
} else if (current && line.startsWith('HEAD ')) current.head = line.slice(5);
|
|
23
|
+
else if (current && line.startsWith('branch ')) current.branch = line.slice(7).replace(/^refs\/heads\//, '');
|
|
24
|
+
}
|
|
25
|
+
return entries;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function currentBranch(dir) {
|
|
29
|
+
const b = git(dir, ['branch', '--show-current'], { allowFailure: true });
|
|
30
|
+
return b ? b.trim() : null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function hasRemote(dir, name) {
|
|
34
|
+
return git(dir, ['remote', 'get-url', name], { allowFailure: true }) !== null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function remoteUrl(dir, name) {
|
|
38
|
+
return git(dir, ['remote', 'get-url', name], { allowFailure: true });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function branchExists(dir, branch) {
|
|
42
|
+
return git(dir, ['show-ref', '--verify', '--quiet', `refs/heads/${branch}`], { allowFailure: true }) !== null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function isAncestor(dir, ancestor, descendant) {
|
|
46
|
+
return git(dir, ['merge-base', '--is-ancestor', ancestor, descendant], { allowFailure: true }) !== null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function fetch(dir, remote, ref) {
|
|
50
|
+
return run('git', ['-C', dir, 'fetch', remote, ref]);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function worktreeAdd(dir, path, { branch, newBranch, startPoint }) {
|
|
54
|
+
const args = ['-C', dir, 'worktree', 'add'];
|
|
55
|
+
if (newBranch) args.push('--no-track', '-b', newBranch, path, startPoint);
|
|
56
|
+
else args.push(path, branch);
|
|
57
|
+
return run('git', args);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function worktreeRemove(dir, path, { force = false } = {}) {
|
|
61
|
+
return run('git', ['-C', dir, 'worktree', 'remove', ...(force ? ['--force'] : []), path], { allowFailure: true });
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function branchDelete(dir, branch) {
|
|
65
|
+
return run('git', ['-C', dir, 'branch', '-D', branch], { allowFailure: true });
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function toplevel(dir) {
|
|
69
|
+
return git(dir, ['rev-parse', '--show-toplevel']);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** `owner/repo` of a remote URL (https or ssh), or the URL itself when it is not GitHub-shaped. */
|
|
73
|
+
export function repoSlug(url) {
|
|
74
|
+
if (!url) return null;
|
|
75
|
+
const m = /github\.com[:/]([^/]+\/[^/]+?)(?:\.git)?$/.exec(url);
|
|
76
|
+
return m ? m[1] : url;
|
|
77
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { sleep } from './exec.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Cross-checkout locks: `mkdir` is atomic on every platform (macOS has no flock), and
|
|
7
|
+
* the pid file inside lets a crashed holder be reclaimed. Two locks exist, never nested:
|
|
8
|
+
* .slot.lock — slot allocation (scan → write .env), seconds
|
|
9
|
+
* .image-build.lock — pnpm install inside docker build, minutes
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
function pidAlive(pid) {
|
|
13
|
+
try {
|
|
14
|
+
process.kill(pid, 0);
|
|
15
|
+
return true;
|
|
16
|
+
} catch (e) {
|
|
17
|
+
return e.code === 'EPERM';
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Run `fn` while holding `<baseDir>/<name>`; waits up to `maxSeconds`, reclaims stale locks. */
|
|
22
|
+
export async function withLock(baseDir, name, what, maxSeconds, fn, { log = console.log, pollMs = 2000 } = {}) {
|
|
23
|
+
const lock = join(baseDir, name);
|
|
24
|
+
mkdirSync(baseDir, { recursive: true });
|
|
25
|
+
let waited = 0;
|
|
26
|
+
for (;;) {
|
|
27
|
+
try {
|
|
28
|
+
mkdirSync(lock);
|
|
29
|
+
break;
|
|
30
|
+
} catch (e) {
|
|
31
|
+
if (e.code !== 'EEXIST') throw e;
|
|
32
|
+
}
|
|
33
|
+
let holder = null;
|
|
34
|
+
try {
|
|
35
|
+
holder = Number(readFileSync(join(lock, 'pid'), 'utf8').trim()) || null;
|
|
36
|
+
} catch {
|
|
37
|
+
holder = null;
|
|
38
|
+
}
|
|
39
|
+
if (holder && !pidAlive(holder)) {
|
|
40
|
+
log(`reclaiming stale lock ${lock} (pid ${holder} is gone)`);
|
|
41
|
+
rmSync(lock, { recursive: true, force: true });
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
if (waited === 0) log(`another hassan-devkit is ${what} (pid ${holder ?? '?'}) — waiting...`);
|
|
45
|
+
await sleep(pollMs);
|
|
46
|
+
waited += pollMs / 1000;
|
|
47
|
+
if (waited >= maxSeconds) {
|
|
48
|
+
throw new Error(`gave up waiting for ${lock} after ${maxSeconds}s — remove it if no hassan-devkit is running`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
writeFileSync(join(lock, 'pid'), String(process.pid));
|
|
52
|
+
const release = () => rmSync(lock, { recursive: true, force: true });
|
|
53
|
+
process.once('exit', release);
|
|
54
|
+
try {
|
|
55
|
+
return await fn();
|
|
56
|
+
} finally {
|
|
57
|
+
release();
|
|
58
|
+
process.off('exit', release);
|
|
59
|
+
}
|
|
60
|
+
}
|
package/src/core/root.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The repo root the CLI operates on: the git toplevel of `cwd` (a worktree's own
|
|
7
|
+
* directory when run inside one), falling back to the nearest ancestor holding a
|
|
8
|
+
* `pnpm-workspace.yaml` or `package.json`, and finally to `cwd` itself.
|
|
9
|
+
*/
|
|
10
|
+
export function findRepoRoot(cwd = process.cwd()) {
|
|
11
|
+
try {
|
|
12
|
+
return execFileSync('git', ['rev-parse', '--show-toplevel'], {
|
|
13
|
+
cwd,
|
|
14
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
15
|
+
})
|
|
16
|
+
.toString()
|
|
17
|
+
.trim();
|
|
18
|
+
} catch {
|
|
19
|
+
// not a git checkout — fall through to the filesystem walk
|
|
20
|
+
}
|
|
21
|
+
let dir = resolve(cwd);
|
|
22
|
+
for (;;) {
|
|
23
|
+
if (existsSync(join(dir, 'pnpm-workspace.yaml')) || existsSync(join(dir, 'package.json'))) {
|
|
24
|
+
return dir;
|
|
25
|
+
}
|
|
26
|
+
const parent = dirname(dir);
|
|
27
|
+
if (parent === dir) return resolve(cwd);
|
|
28
|
+
dir = parent;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from 'node:fs';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Idempotent file scaffolding shared by `init` (and, later, by the Claude and CI
|
|
6
|
+
* scaffolds). A plan says what WOULD happen; `applyPlan` does it. A file the project has
|
|
7
|
+
* edited is never overwritten without `--force`, and `--force` always prints the diff.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** Deep-merge `patch` into `target` adding only keys that are missing. Returns added paths. */
|
|
11
|
+
export function mergeMissing(target, patch, path = '') {
|
|
12
|
+
const added = [];
|
|
13
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
14
|
+
const here = path ? `${path}.${key}` : key;
|
|
15
|
+
if (!(key in target)) {
|
|
16
|
+
target[key] = value;
|
|
17
|
+
added.push(here);
|
|
18
|
+
} else if (isPlainObject(target[key]) && isPlainObject(value)) {
|
|
19
|
+
added.push(...mergeMissing(target[key], value, here));
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return added;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Replace everything from the first line equal to/starting with `marker` to the end of
|
|
29
|
+
* `text` with `block`; append when the marker is absent. Mirrors the managed-block
|
|
30
|
+
* semantics of the `.env` writer so `.env.dist` and `.env` agree.
|
|
31
|
+
*/
|
|
32
|
+
export function upsertTrailingBlock(text, markerPrefix, block) {
|
|
33
|
+
const lines = (text ?? '').split('\n');
|
|
34
|
+
const idx = lines.findIndex((l) => l.startsWith(markerPrefix));
|
|
35
|
+
const head = (idx === -1 ? lines : lines.slice(0, idx)).join('\n').replace(/\s+$/, '');
|
|
36
|
+
return `${head ? `${head}\n\n` : ''}${block.replace(/\s+$/, '')}\n`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Minimal line diff (LCS) rendered as unified-ish `-`/`+` lines. */
|
|
40
|
+
export function lineDiff(before, after) {
|
|
41
|
+
const a = before.split('\n');
|
|
42
|
+
const b = after.split('\n');
|
|
43
|
+
const n = a.length;
|
|
44
|
+
const m = b.length;
|
|
45
|
+
const dp = Array.from({ length: n + 1 }, () => new Uint16Array(m + 1));
|
|
46
|
+
for (let i = n - 1; i >= 0; i--) {
|
|
47
|
+
for (let j = m - 1; j >= 0; j--) {
|
|
48
|
+
dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const out = [];
|
|
52
|
+
let i = 0;
|
|
53
|
+
let j = 0;
|
|
54
|
+
while (i < n && j < m) {
|
|
55
|
+
if (a[i] === b[j]) {
|
|
56
|
+
i++;
|
|
57
|
+
j++;
|
|
58
|
+
} else if (dp[i + 1][j] >= dp[i][j + 1]) out.push(`-${a[i++]}`);
|
|
59
|
+
else out.push(`+${b[j++]}`);
|
|
60
|
+
}
|
|
61
|
+
while (i < n) out.push(`-${a[i++]}`);
|
|
62
|
+
while (j < m) out.push(`+${b[j++]}`);
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* @typedef {{ path: string, content: string, mode?: number, status: 'create'|'same'|'differs', current: string|null }} FilePlan
|
|
68
|
+
*/
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Plan one file. `path` is relative to `root`. A `managed` plan is one whose content is
|
|
72
|
+
* computed FROM the current file (a merged package.json, a managed `.env.dist` block), so
|
|
73
|
+
* rewriting it can never lose project edits — it is updated without `--force`.
|
|
74
|
+
*/
|
|
75
|
+
export function planFile(root, path, content, { mode, managed = false } = {}) {
|
|
76
|
+
const abs = join(root, path);
|
|
77
|
+
if (!existsSync(abs)) return { path, content, mode, managed, status: 'create', current: null };
|
|
78
|
+
const current = readFileSync(abs, 'utf8');
|
|
79
|
+
return { path, content, mode, managed, status: current === content ? 'same' : 'differs', current };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Apply plans. Returns a summary `{ created, updated, overwritten, skipped, unchanged }`.
|
|
84
|
+
* `differs` files are skipped unless `force` (the diff is logged first) — except managed
|
|
85
|
+
* plans, which are always updated because their content preserves the project's edits.
|
|
86
|
+
*/
|
|
87
|
+
export function applyPlan(root, plans, { force = false, dryRun = false, log = console.log } = {}) {
|
|
88
|
+
const summary = { created: [], updated: [], overwritten: [], skipped: [], unchanged: [] };
|
|
89
|
+
for (const plan of plans) {
|
|
90
|
+
const abs = join(root, plan.path);
|
|
91
|
+
if (plan.status === 'same') {
|
|
92
|
+
summary.unchanged.push(plan.path);
|
|
93
|
+
log(` unchanged ${plan.path}`);
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
if (plan.status === 'differs' && plan.managed) {
|
|
97
|
+
log(` update ${plan.path}`);
|
|
98
|
+
summary.updated.push(plan.path);
|
|
99
|
+
} else if (plan.status === 'differs' && !force) {
|
|
100
|
+
summary.skipped.push(plan.path);
|
|
101
|
+
log(` differs ${plan.path} (kept; re-run with --force to overwrite)`);
|
|
102
|
+
continue;
|
|
103
|
+
} else if (plan.status === 'differs') {
|
|
104
|
+
log(` overwrite ${plan.path}`);
|
|
105
|
+
for (const line of lineDiff(plan.current, plan.content)) log(` ${line}`);
|
|
106
|
+
summary.overwritten.push(plan.path);
|
|
107
|
+
} else {
|
|
108
|
+
log(` create ${plan.path}`);
|
|
109
|
+
summary.created.push(plan.path);
|
|
110
|
+
}
|
|
111
|
+
if (dryRun) continue;
|
|
112
|
+
mkdirSync(dirname(abs), { recursive: true });
|
|
113
|
+
writeFileSync(abs, plan.content);
|
|
114
|
+
if (plan.mode) chmodSync(abs, plan.mode);
|
|
115
|
+
}
|
|
116
|
+
return summary;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Read a JSON file or return `fallback`. */
|
|
120
|
+
export function readJson(path, fallback = null) {
|
|
121
|
+
try {
|
|
122
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
123
|
+
} catch {
|
|
124
|
+
return fallback;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Serialise JSON the way package managers do: 2 spaces, trailing newline. */
|
|
129
|
+
export function formatJson(value) {
|
|
130
|
+
return `${JSON.stringify(value, null, 2)}\n`;
|
|
131
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { COMPOSE_FILE, ENV_FILE } from './config.js';
|
|
4
|
+
import { capture, run, sleep } from './exec.js';
|
|
5
|
+
|
|
6
|
+
/** Docker helpers for one checkout's stack. All compose calls read that checkout's `.env`. */
|
|
7
|
+
|
|
8
|
+
export function hasComposeFile(root) {
|
|
9
|
+
return existsSync(join(root, COMPOSE_FILE));
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function composeArgs(root) {
|
|
13
|
+
const args = ['compose'];
|
|
14
|
+
if (existsSync(join(root, ENV_FILE))) args.push('--env-file', ENV_FILE);
|
|
15
|
+
args.push('-f', COMPOSE_FILE);
|
|
16
|
+
return args;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function compose(root, args, { env, allowFailure = false } = {}) {
|
|
20
|
+
return run('docker', [...composeArgs(root), ...args], { cwd: root, env, allowFailure });
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function imageExists(ref) {
|
|
24
|
+
return capture('docker', ['image', 'inspect', ref], { allowFailure: true }) !== null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function listVolumes() {
|
|
28
|
+
return (capture('docker', ['volume', 'ls', '-q'], { allowFailure: true }) ?? '').split('\n').filter(Boolean);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function removeVolume(name) {
|
|
32
|
+
return capture('docker', ['volume', 'rm', name], { allowFailure: true }) !== null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function listImages() {
|
|
36
|
+
return (capture('docker', ['image', 'ls', '--format', '{{.Repository}}:{{.Tag}}'], { allowFailure: true }) ?? '')
|
|
37
|
+
.split('\n')
|
|
38
|
+
.filter(Boolean);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function imagesInUse() {
|
|
42
|
+
return (capture('docker', ['ps', '-a', '--format', '{{.Image}}'], { allowFailure: true }) ?? '').split('\n').filter(Boolean);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function removeImage(ref) {
|
|
46
|
+
return capture('docker', ['image', 'rm', ref], { allowFailure: true }) !== null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Poll `url` until it answers 2xx/3xx; throws after `timeoutSeconds`. */
|
|
50
|
+
export async function waitForUrl(url, timeoutSeconds, { log = console.log, pollMs = 3000 } = {}) {
|
|
51
|
+
log(`waiting for ${url} (first boot compiles, this takes a while)...`);
|
|
52
|
+
const deadline = Date.now() + timeoutSeconds * 1000;
|
|
53
|
+
while (Date.now() < deadline) {
|
|
54
|
+
try {
|
|
55
|
+
const res = await fetch(url, { signal: AbortSignal.timeout(2000), redirect: 'manual' });
|
|
56
|
+
if (res.status < 400) return;
|
|
57
|
+
} catch {
|
|
58
|
+
// not up yet
|
|
59
|
+
}
|
|
60
|
+
await sleep(pollMs);
|
|
61
|
+
}
|
|
62
|
+
throw new Error(`${url} did not come up within ${timeoutSeconds}s — check pnpm docker:dev:logs`);
|
|
63
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { issueNumberFromKey } from '../derive.js';
|
|
2
|
+
import { capture, commandExists } from '../exec.js';
|
|
3
|
+
import { remoteUrl } from '../git.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* GitHub Issues adapter. On `worktree:create` the issue is assigned to `@me` — nothing
|
|
7
|
+
* else: GitHub has no status field without Projects, and the open PR is the progress
|
|
8
|
+
* signal. Issues live on the base repo (fork model), so `upstream` wins over `origin`.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** Pure: the `gh` argument list for assigning issue `number` (repo optional). */
|
|
12
|
+
export function githubAssignArgs(number, repo) {
|
|
13
|
+
return ['issue', 'edit', String(number), '--add-assignee', '@me', ...(repo ? ['--repo', repo] : [])];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export const githubAdapter = {
|
|
17
|
+
async startTicket({ key, tracker, cwd, log, note }) {
|
|
18
|
+
const number = issueNumberFromKey(key, tracker);
|
|
19
|
+
if (number === null) return;
|
|
20
|
+
if (!commandExists('gh')) {
|
|
21
|
+
note(`gh not installed — assign issue #${number} to yourself on GitHub`);
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
const repo = remoteUrl(cwd, 'upstream') ?? remoteUrl(cwd, 'origin');
|
|
25
|
+
const result = capture('gh', githubAssignArgs(number, repo), { cwd, allowFailure: true });
|
|
26
|
+
if (result === null) note(`assigning #${number} failed (does the issue exist and is gh authenticated?) — assign it to yourself on GitHub`);
|
|
27
|
+
else log(`GitHub: #${number} assigned to you`);
|
|
28
|
+
},
|
|
29
|
+
};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { ticketKeyFromBranch } from '../derive.js';
|
|
2
|
+
import { githubAdapter } from './github.js';
|
|
3
|
+
import { jiraAdapter } from './jira.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Tracker adapters: what `worktree:create` does with the branch's ticket. Every adapter
|
|
7
|
+
* is best effort — a missing token or an unreachable tracker prints a `note:` and never
|
|
8
|
+
* breaks worktree creation (creating the worktree IS the "work started" signal).
|
|
9
|
+
*
|
|
10
|
+
* Adapter contract: `{ startTicket({ key, branch, tracker, cwd, log, note }) }`.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const adapters = {
|
|
14
|
+
none: { startTicket: async () => {} },
|
|
15
|
+
jira: jiraAdapter,
|
|
16
|
+
github: githubAdapter,
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export function registerTracker(kind, adapter) {
|
|
20
|
+
adapters[kind] = adapter;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function startTicket({ branch, tracker, cwd, log = console.log, note = (m) => console.error(`note: ${m}`) }) {
|
|
24
|
+
const key = ticketKeyFromBranch(branch, tracker);
|
|
25
|
+
if (!key) return null;
|
|
26
|
+
const adapter = adapters[tracker.kind];
|
|
27
|
+
if (!adapter) {
|
|
28
|
+
note(`no tracker adapter for "${tracker.kind}" — start ${key} by hand`);
|
|
29
|
+
return key;
|
|
30
|
+
}
|
|
31
|
+
try {
|
|
32
|
+
await adapter.startTicket({ key, branch, tracker, cwd, log, note });
|
|
33
|
+
} catch (e) {
|
|
34
|
+
note(`${tracker.kind}: ${e.message} — start ${key} by hand`);
|
|
35
|
+
}
|
|
36
|
+
return key;
|
|
37
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { parseEnv } from '../env-block.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Jira adapter. On `worktree:create`: whoever starts the work owns the ticket, so the
|
|
8
|
+
* issue is assigned to the current user regardless of status, and a `To Do` issue moves
|
|
9
|
+
* to `In Progress`. Best effort throughout — every failure is a `note:`.
|
|
10
|
+
*
|
|
11
|
+
* Credentials: `JIRA_EMAIL`, `JIRA_API_TOKEN` and optionally `JIRA_URL` (or `JIRA_BASE_URL`)
|
|
12
|
+
* from the environment, else from `~/.config/jira/env` (KEY=value lines).
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export const JIRA_ENV_FILE = join(homedir(), '.config', 'jira', 'env');
|
|
16
|
+
|
|
17
|
+
/** Pure: pick credentials from the process env, falling back to the env file's text. */
|
|
18
|
+
export function resolveJiraCredentials(env, fileText, baseUrlFromConfig) {
|
|
19
|
+
const file = fileText ? unquote(parseEnv(fileText)) : {};
|
|
20
|
+
const pick = (k) => env[k] ?? file[k] ?? null;
|
|
21
|
+
return {
|
|
22
|
+
email: pick('JIRA_EMAIL'),
|
|
23
|
+
token: pick('JIRA_API_TOKEN'),
|
|
24
|
+
baseUrl: (baseUrlFromConfig ?? pick('JIRA_URL') ?? pick('JIRA_BASE_URL') ?? null)?.replace(/\/+$/, '') ?? null,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function unquote(obj) {
|
|
29
|
+
return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, v.replace(/^(['"])(.*)\1$/, '$2')]));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function loadJiraCredentials(tracker) {
|
|
33
|
+
const text = existsSync(JIRA_ENV_FILE) ? readFileSync(JIRA_ENV_FILE, 'utf8') : null;
|
|
34
|
+
return resolveJiraCredentials(process.env, text, tracker.baseUrl);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function api(creds, method, path, body) {
|
|
38
|
+
const res = await fetch(`${creds.baseUrl}/rest/api/3${path}`, {
|
|
39
|
+
method,
|
|
40
|
+
headers: {
|
|
41
|
+
Authorization: `Basic ${Buffer.from(`${creds.email}:${creds.token}`).toString('base64')}`,
|
|
42
|
+
Accept: 'application/json',
|
|
43
|
+
...(body ? { 'Content-Type': 'application/json' } : {}),
|
|
44
|
+
},
|
|
45
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
46
|
+
signal: AbortSignal.timeout(15000),
|
|
47
|
+
});
|
|
48
|
+
if (!res.ok) throw new Error(`${method} ${path} → HTTP ${res.status}`);
|
|
49
|
+
const text = await res.text();
|
|
50
|
+
return text ? JSON.parse(text) : null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export const jiraAdapter = {
|
|
54
|
+
async startTicket({ key, tracker, log, note }) {
|
|
55
|
+
const creds = loadJiraCredentials(tracker);
|
|
56
|
+
if (!creds.email || !creds.token || !creds.baseUrl) {
|
|
57
|
+
note(`Jira credentials unavailable (set JIRA_EMAIL/JIRA_API_TOKEN/JIRA_URL or ${JIRA_ENV_FILE}) — assign ${key} to yourself and move it to In Progress`);
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
let me = null;
|
|
61
|
+
try {
|
|
62
|
+
me = (await api(creds, 'GET', '/myself'))?.accountId ?? null;
|
|
63
|
+
} catch (e) {
|
|
64
|
+
note(`Jira unreachable (${e.message}) — assign ${key} to yourself and move it to In Progress`);
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
try {
|
|
68
|
+
await api(creds, 'PUT', `/issue/${key}/assignee`, { accountId: me });
|
|
69
|
+
log(`Jira: ${key} assigned to you`);
|
|
70
|
+
} catch (e) {
|
|
71
|
+
note(`assigning ${key} failed (${e.message}) — assign it to yourself in Jira`);
|
|
72
|
+
}
|
|
73
|
+
let status = null;
|
|
74
|
+
try {
|
|
75
|
+
status = (await api(creds, 'GET', `/issue/${key}?fields=status`))?.fields?.status?.name ?? null;
|
|
76
|
+
} catch {
|
|
77
|
+
status = null;
|
|
78
|
+
}
|
|
79
|
+
if (status !== 'To Do') {
|
|
80
|
+
log(`Jira: ${key} is '${status ?? 'unreachable'}' — leaving its status alone`);
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
let transitionId = null;
|
|
84
|
+
try {
|
|
85
|
+
const { transitions = [] } = (await api(creds, 'GET', `/issue/${key}/transitions`)) ?? {};
|
|
86
|
+
transitionId = transitions.find((t) => t.to?.name === 'In Progress')?.id ?? null;
|
|
87
|
+
} catch {
|
|
88
|
+
transitionId = null;
|
|
89
|
+
}
|
|
90
|
+
if (!transitionId) {
|
|
91
|
+
note(`${key} has no To Do → In Progress transition — move it yourself`);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
try {
|
|
95
|
+
await api(creds, 'POST', `/issue/${key}/transitions`, { transition: { id: transitionId } });
|
|
96
|
+
log(`Jira: ${key} → In Progress`);
|
|
97
|
+
} catch (e) {
|
|
98
|
+
note(`transitioning ${key} failed (${e.message}) — move it to In Progress yourself`);
|
|
99
|
+
}
|
|
100
|
+
},
|
|
101
|
+
};
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
|
2
|
+
import { basename, join, relative } from 'node:path';
|
|
3
|
+
import { parse as parseYaml } from 'yaml';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Workspace projects are derived from `pnpm-workspace.yaml`, never declared: every
|
|
7
|
+
* directory matched by a `packages:` glob that holds a package.json is a project.
|
|
8
|
+
*
|
|
9
|
+
* name — the directory basename (`apps/web-admin` → `web-admin`); this is what commit
|
|
10
|
+
* scopes, lint-staged targets and Nx project names are keyed on
|
|
11
|
+
* kind — `api` (has nest-cli.json), `spa` (has angular.json), else `lib`
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', '.nx', '.angular', 'www']);
|
|
15
|
+
|
|
16
|
+
export function parseWorkspaceGlobs(yamlText) {
|
|
17
|
+
const doc = parseYaml(yamlText) ?? {};
|
|
18
|
+
const globs = Array.isArray(doc.packages) ? doc.packages : [];
|
|
19
|
+
return globs.filter((g) => typeof g === 'string' && g.trim()).map((g) => g.trim().replace(/\/+$/, ''));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function subdirs(dir) {
|
|
23
|
+
let entries;
|
|
24
|
+
try {
|
|
25
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
26
|
+
} catch {
|
|
27
|
+
return [];
|
|
28
|
+
}
|
|
29
|
+
return entries
|
|
30
|
+
.filter((e) => e.isDirectory() && !SKIP_DIRS.has(e.name) && !e.name.startsWith('.'))
|
|
31
|
+
.map((e) => join(dir, e.name));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function segmentMatcher(segment) {
|
|
35
|
+
const re = new RegExp(`^${segment.split('*').map((s) => s.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('[^/]*')}$`);
|
|
36
|
+
return (name) => re.test(name);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Expand one pnpm-style glob (`apps/*`, `packages/**`, `tools/cli`) to existing dirs. */
|
|
40
|
+
export function expandGlob(root, pattern) {
|
|
41
|
+
const segments = pattern.split('/').filter((s) => s && s !== '.');
|
|
42
|
+
const results = new Set();
|
|
43
|
+
const walk = (dir, segs) => {
|
|
44
|
+
if (segs.length === 0) {
|
|
45
|
+
if (existsSync(dir) && statSync(dir).isDirectory() && dir !== root) results.add(dir);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
const [seg, ...rest] = segs;
|
|
49
|
+
if (seg === '**') {
|
|
50
|
+
walk(dir, rest);
|
|
51
|
+
for (const sub of subdirs(dir)) walk(sub, segs);
|
|
52
|
+
} else if (seg.includes('*')) {
|
|
53
|
+
const matches = segmentMatcher(seg);
|
|
54
|
+
for (const sub of subdirs(dir)) if (matches(basename(sub))) walk(sub, rest);
|
|
55
|
+
} else {
|
|
56
|
+
walk(join(dir, seg), rest);
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
walk(root, segments);
|
|
60
|
+
return [...results];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function detectKind(dir) {
|
|
64
|
+
if (existsSync(join(dir, 'nest-cli.json'))) return 'api';
|
|
65
|
+
if (existsSync(join(dir, 'angular.json'))) return 'spa';
|
|
66
|
+
return 'lib';
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* List the workspace projects of `root`, sorted by relative directory.
|
|
71
|
+
* Negated globs (`!apps/legacy`) remove matches. Directories without a package.json are
|
|
72
|
+
* ignored, like pnpm does.
|
|
73
|
+
*/
|
|
74
|
+
export function listProjects(root) {
|
|
75
|
+
const wsFile = join(root, 'pnpm-workspace.yaml');
|
|
76
|
+
if (!existsSync(wsFile)) return [];
|
|
77
|
+
const globs = parseWorkspaceGlobs(readFileSync(wsFile, 'utf8'));
|
|
78
|
+
const included = new Set();
|
|
79
|
+
const excluded = new Set();
|
|
80
|
+
for (const glob of globs) {
|
|
81
|
+
const negated = glob.startsWith('!');
|
|
82
|
+
const dirs = expandGlob(root, negated ? glob.slice(1) : glob);
|
|
83
|
+
for (const d of dirs) (negated ? excluded : included).add(d);
|
|
84
|
+
}
|
|
85
|
+
const projects = [];
|
|
86
|
+
for (const dir of included) {
|
|
87
|
+
if (excluded.has(dir)) continue;
|
|
88
|
+
const pkgFile = join(dir, 'package.json');
|
|
89
|
+
if (!existsSync(pkgFile)) continue;
|
|
90
|
+
let packageName = null;
|
|
91
|
+
try {
|
|
92
|
+
packageName = JSON.parse(readFileSync(pkgFile, 'utf8')).name ?? null;
|
|
93
|
+
} catch {
|
|
94
|
+
packageName = null;
|
|
95
|
+
}
|
|
96
|
+
projects.push({
|
|
97
|
+
name: basename(dir),
|
|
98
|
+
dir: relative(root, dir).split('\\').join('/'),
|
|
99
|
+
kind: detectKind(dir),
|
|
100
|
+
packageName,
|
|
101
|
+
hasEslint: readdirSync(dir).some((f) => /^eslint\.config\.(c|m)?js$/.test(f)),
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
return projects.sort((a, b) => a.dir.localeCompare(b.dir));
|
|
105
|
+
}
|