@ferronhooi/aihub 0.1.0-next.4 → 0.1.0-next.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/batch.js +19 -0
- package/dist/commands/branch.js +10 -0
- package/dist/commands/cherry-pick.js +25 -0
- package/dist/commands/pipeline.js +35 -0
- package/dist/commands/pr-changes.js +36 -0
- package/dist/commands/pr.js +3 -0
- package/dist/commands/story.js +23 -0
- package/dist/commands/work.js +6 -0
- package/dist/lib/ado.js +8 -1
- package/dist/lib/args.js +18 -0
- package/dist/lib/batch.js +146 -0
- package/dist/lib/branch.js +72 -0
- package/dist/lib/cherryPick.js +182 -0
- package/dist/lib/git.js +32 -0
- package/dist/lib/pipeline.js +249 -0
- package/dist/lib/prChanges.js +85 -0
- package/dist/lib/story.js +248 -0
- package/dist/lib/team.js +13 -0
- package/dist/lib/work.js +67 -0
- package/dist/router.js +12 -0
- package/pack/skills/pipeline-fix/SKILL.md +1 -0
- package/pack/skills/pr-watch/SKILL.md +1 -1
- package/pack/skills/release/SKILL.md +10 -12
- package/package.json +1 -1
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { num, parse } from "../lib/args.js";
|
|
2
|
+
import { batch } from "../lib/batch.js";
|
|
3
|
+
export async function run(argv, ctx) {
|
|
4
|
+
const v = parse(argv, {
|
|
5
|
+
select: { type: "string" },
|
|
6
|
+
run: { type: "string" },
|
|
7
|
+
parallel: { type: "string" },
|
|
8
|
+
"retry-failed": { type: "string" },
|
|
9
|
+
json: { type: "boolean" },
|
|
10
|
+
}).values;
|
|
11
|
+
// In-process runner: every target runs one aihub command with its own captured output.
|
|
12
|
+
const runner = async (args) => {
|
|
13
|
+
const { main } = await import("../router.js");
|
|
14
|
+
const lines = [];
|
|
15
|
+
const code = await main(args, { ...ctx, out: (l) => lines.push(l), err: (l) => lines.push(l) });
|
|
16
|
+
return { code, output: lines.join("\n") };
|
|
17
|
+
};
|
|
18
|
+
await batch(ctx, { select: v.select, run: v.run, parallel: num(v.parallel, "--parallel"), retryFailed: v["retry-failed"], json: v.json }, runner);
|
|
19
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { parse } from "../lib/args.js";
|
|
2
|
+
import { branchUpdate } from "../lib/branch.js";
|
|
3
|
+
import { AihubError } from "../lib/errors.js";
|
|
4
|
+
export async function run(argv, ctx) {
|
|
5
|
+
const [sub, ...rest] = argv;
|
|
6
|
+
if (sub !== "update")
|
|
7
|
+
throw new AihubError("usage: aihub branch update [--branch B] [--target T] [--rebase]");
|
|
8
|
+
const v = parse(rest, { branch: { type: "string" }, target: { type: "string" }, rebase: { type: "boolean" }, json: { type: "boolean" } }).values;
|
|
9
|
+
ctx.out(await branchUpdate(ctx, { branch: v.branch, target: v.target, rebase: v.rebase, json: v.json }));
|
|
10
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { parse } from "../lib/args.js";
|
|
2
|
+
import { cherryPick } from "../lib/cherryPick.js";
|
|
3
|
+
import { AihubError } from "../lib/errors.js";
|
|
4
|
+
export async function run(argv, ctx) {
|
|
5
|
+
const v = parse(argv, {
|
|
6
|
+
from: { type: "string" },
|
|
7
|
+
to: { type: "string", multiple: true },
|
|
8
|
+
"to-group": { type: "string" },
|
|
9
|
+
pr: { type: "boolean" },
|
|
10
|
+
direct: { type: "boolean" },
|
|
11
|
+
"body-file": { type: "string" },
|
|
12
|
+
json: { type: "boolean" },
|
|
13
|
+
}).values;
|
|
14
|
+
if (!v.from)
|
|
15
|
+
throw new AihubError("aihub cherry-pick needs --from <pr N|url|commit sha,...|story id>");
|
|
16
|
+
await cherryPick(ctx, {
|
|
17
|
+
from: v.from,
|
|
18
|
+
to: v.to ?? [],
|
|
19
|
+
toGroup: v["to-group"],
|
|
20
|
+
pr: v.pr,
|
|
21
|
+
direct: v.direct,
|
|
22
|
+
bodyFile: v["body-file"],
|
|
23
|
+
json: v.json,
|
|
24
|
+
});
|
|
25
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { num, parse } from "../lib/args.js";
|
|
2
|
+
import { AihubError } from "../lib/errors.js";
|
|
3
|
+
import { pipelineFollow, pipelineLogs, pipelineRun, pipelineRuns, pipelineStatus } from "../lib/pipeline.js";
|
|
4
|
+
export async function run(argv, ctx) {
|
|
5
|
+
const [sub, ...rest] = argv;
|
|
6
|
+
const v = parse(rest, {
|
|
7
|
+
pr: { type: "string" },
|
|
8
|
+
branch: { type: "string" },
|
|
9
|
+
run: { type: "string" },
|
|
10
|
+
definition: { type: "string" },
|
|
11
|
+
name: { type: "string" },
|
|
12
|
+
top: { type: "string" },
|
|
13
|
+
timeout: { type: "string" },
|
|
14
|
+
step: { type: "string" },
|
|
15
|
+
search: { type: "string" },
|
|
16
|
+
tail: { type: "string" },
|
|
17
|
+
"params-file": { type: "string" },
|
|
18
|
+
json: { type: "boolean" },
|
|
19
|
+
}).values;
|
|
20
|
+
const sel = { pr: v.pr, branch: v.branch, run: num(v.run, "--run"), definition: v.definition, top: num(v.top, "--top") };
|
|
21
|
+
if (sub === "follow")
|
|
22
|
+
return pipelineFollow(ctx, { ...sel, timeout: v.timeout });
|
|
23
|
+
if (sub === "status")
|
|
24
|
+
return void ctx.out(await pipelineStatus(ctx, { ...sel, json: v.json }));
|
|
25
|
+
if (sub === "runs")
|
|
26
|
+
return void ctx.out(await pipelineRuns(ctx, { ...sel, json: v.json }));
|
|
27
|
+
if (sub === "logs") {
|
|
28
|
+
if (!sel.run)
|
|
29
|
+
throw new AihubError("aihub pipeline logs needs --run <id> (see 'aihub pipeline runs')");
|
|
30
|
+
return void ctx.out(await pipelineLogs(ctx, { run: sel.run, step: v.step, search: v.search, tail: num(v.tail, "--tail"), json: v.json }));
|
|
31
|
+
}
|
|
32
|
+
if (sub === "run")
|
|
33
|
+
return void ctx.out(await pipelineRun(ctx, { name: v.name, branch: v.branch, paramsFile: v["params-file"], json: v.json }));
|
|
34
|
+
throw new AihubError("usage: aihub pipeline follow|status|runs|logs|run [flags]");
|
|
35
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { parseArgs } from "node:util";
|
|
2
|
+
import { AihubError } from "../lib/errors.js";
|
|
3
|
+
import { prChanges } from "../lib/prChanges.js";
|
|
4
|
+
function int(v, flag) {
|
|
5
|
+
if (v === undefined)
|
|
6
|
+
return undefined;
|
|
7
|
+
const n = Number(v);
|
|
8
|
+
if (!Number.isInteger(n) || n < 0)
|
|
9
|
+
throw new AihubError(`${flag} must be a number`);
|
|
10
|
+
return n;
|
|
11
|
+
}
|
|
12
|
+
export async function run(argv, ctx) {
|
|
13
|
+
let v;
|
|
14
|
+
try {
|
|
15
|
+
v = parseArgs({
|
|
16
|
+
args: argv,
|
|
17
|
+
options: {
|
|
18
|
+
pr: { type: "string" },
|
|
19
|
+
"since-iteration": { type: "string" },
|
|
20
|
+
paths: { type: "string", multiple: true },
|
|
21
|
+
page: { type: "string" },
|
|
22
|
+
json: { type: "boolean" },
|
|
23
|
+
},
|
|
24
|
+
}).values;
|
|
25
|
+
}
|
|
26
|
+
catch (e) {
|
|
27
|
+
throw new AihubError(e.message);
|
|
28
|
+
}
|
|
29
|
+
ctx.out(await prChanges(ctx, {
|
|
30
|
+
pr: v.pr,
|
|
31
|
+
sinceIteration: int(v["since-iteration"], "--since-iteration"),
|
|
32
|
+
paths: (v.paths ?? []).flatMap((p) => p.split(",")),
|
|
33
|
+
page: int(v.page, "--page"),
|
|
34
|
+
json: v.json,
|
|
35
|
+
}));
|
|
36
|
+
}
|
package/dist/commands/pr.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { parseArgs } from "node:util";
|
|
2
2
|
import { AihubError } from "../lib/errors.js";
|
|
3
3
|
import { createPr, updatePr } from "../lib/pr.js";
|
|
4
|
+
import { run as runChanges } from "./pr-changes.js";
|
|
4
5
|
function parse(argv, options) {
|
|
5
6
|
try {
|
|
6
7
|
return parseArgs({ args: argv, options, allowPositionals: true }).values;
|
|
@@ -19,6 +20,8 @@ function num(v, flag) {
|
|
|
19
20
|
}
|
|
20
21
|
export async function run(argv, ctx) {
|
|
21
22
|
const [sub, ...rest] = argv;
|
|
23
|
+
if (sub === "changes")
|
|
24
|
+
return runChanges(rest, ctx);
|
|
22
25
|
if (sub === "create") {
|
|
23
26
|
const v = parse(rest, {
|
|
24
27
|
title: { type: "string" },
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { num, parse } from "../lib/args.js";
|
|
2
|
+
import { AihubError } from "../lib/errors.js";
|
|
3
|
+
import { storyCreate, storyRefine, storyShow } from "../lib/story.js";
|
|
4
|
+
/** Accepts `--id 123` and the positional form `story show 123` used by the skills. */
|
|
5
|
+
function idOf(v, pos) {
|
|
6
|
+
const id = num(v.id ?? pos[0], "--id");
|
|
7
|
+
if (!id)
|
|
8
|
+
throw new AihubError("pass the story id: --id <number>");
|
|
9
|
+
return id;
|
|
10
|
+
}
|
|
11
|
+
export async function run(argv, ctx) {
|
|
12
|
+
const [sub, ...rest] = argv;
|
|
13
|
+
const p = parse(rest, { id: { type: "string" }, title: { type: "string" }, "body-file": { type: "string" }, parent: { type: "string" }, type: { type: "string" }, json: { type: "boolean" } }, true);
|
|
14
|
+
const v = p.values;
|
|
15
|
+
if (sub === "show")
|
|
16
|
+
return void ctx.out(await storyShow(ctx, { id: idOf(v, p.positionals), json: v.json }));
|
|
17
|
+
if (sub === "create") {
|
|
18
|
+
return void ctx.out(await storyCreate(ctx, { title: v.title, bodyFile: v["body-file"], parent: num(v.parent, "--parent"), type: v.type, json: v.json }));
|
|
19
|
+
}
|
|
20
|
+
if (sub === "refine")
|
|
21
|
+
return void ctx.out(await storyRefine(ctx, { id: idOf(v, p.positionals), bodyFile: v["body-file"], json: v.json }));
|
|
22
|
+
throw new AihubError("usage: aihub story show|create|refine [flags]");
|
|
23
|
+
}
|
package/dist/lib/ado.js
CHANGED
|
@@ -54,7 +54,7 @@ export class AdoClient {
|
|
|
54
54
|
headers: {
|
|
55
55
|
Authorization: await this.auth(),
|
|
56
56
|
Accept: opts.raw ? "text/plain" : "application/json",
|
|
57
|
-
...(opts.body !== undefined ? { "Content-Type": "application/json; charset=utf-8" } : {}),
|
|
57
|
+
...(opts.body !== undefined ? { "Content-Type": opts.contentType ?? "application/json; charset=utf-8" } : {}),
|
|
58
58
|
},
|
|
59
59
|
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
|
|
60
60
|
});
|
|
@@ -94,6 +94,13 @@ export class AdoClient {
|
|
|
94
94
|
patch(path, body, query) {
|
|
95
95
|
return this.request("PATCH", path, { body, query }).then((r) => r.data);
|
|
96
96
|
}
|
|
97
|
+
/** Work item writes need the JSON Patch media type. */
|
|
98
|
+
jsonPatch(method, path, ops, query) {
|
|
99
|
+
return this.request(method, path, { body: ops, query, contentType: "application/json-patch+json" }).then((r) => r.data);
|
|
100
|
+
}
|
|
101
|
+
workItemUrl(id) {
|
|
102
|
+
return `${this.remote.orgUrl}/${encodeURIComponent(this.remote.project)}/_workitems/edit/${id}`;
|
|
103
|
+
}
|
|
97
104
|
getText(path, query) {
|
|
98
105
|
return this.request("GET", path, { query, raw: true }).then((r) => r.data);
|
|
99
106
|
}
|
package/dist/lib/args.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { parseArgs } from "node:util";
|
|
2
|
+
import { AihubError } from "./errors.js";
|
|
3
|
+
export function parse(argv, options, positionals = false) {
|
|
4
|
+
try {
|
|
5
|
+
return parseArgs({ args: argv, options, allowPositionals: positionals });
|
|
6
|
+
}
|
|
7
|
+
catch (e) {
|
|
8
|
+
throw new AihubError(e.message);
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
export function num(v, flag) {
|
|
12
|
+
if (v === undefined)
|
|
13
|
+
return undefined;
|
|
14
|
+
const n = Number(String(v).replace(/^AB#/i, ""));
|
|
15
|
+
if (!Number.isInteger(n) || n <= 0)
|
|
16
|
+
throw new AihubError(`${flag} must be a number`);
|
|
17
|
+
return n;
|
|
18
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { shortBranch } from "./ado.js";
|
|
4
|
+
import { repoClient } from "./context.js";
|
|
5
|
+
import { AihubError } from "./errors.js";
|
|
6
|
+
import { git } from "./git.js";
|
|
7
|
+
import { globMatch } from "./team.js";
|
|
8
|
+
import { listPrs } from "./work.js";
|
|
9
|
+
export const MAX_PARALLEL = 8;
|
|
10
|
+
/** Split a command line into tokens, honouring single and double quotes. */
|
|
11
|
+
export function splitCommand(s) {
|
|
12
|
+
const out = [];
|
|
13
|
+
let cur = "";
|
|
14
|
+
let q = null;
|
|
15
|
+
let has = false;
|
|
16
|
+
for (const ch of s) {
|
|
17
|
+
if (q) {
|
|
18
|
+
if (ch === q)
|
|
19
|
+
q = null;
|
|
20
|
+
else
|
|
21
|
+
cur += ch;
|
|
22
|
+
}
|
|
23
|
+
else if (ch === '"' || ch === "'") {
|
|
24
|
+
q = ch;
|
|
25
|
+
has = true;
|
|
26
|
+
}
|
|
27
|
+
else if (/\s/.test(ch)) {
|
|
28
|
+
if (cur || has)
|
|
29
|
+
out.push(cur);
|
|
30
|
+
cur = "";
|
|
31
|
+
has = false;
|
|
32
|
+
}
|
|
33
|
+
else
|
|
34
|
+
cur += ch;
|
|
35
|
+
}
|
|
36
|
+
if (q)
|
|
37
|
+
throw new AihubError("--run has an unclosed quote");
|
|
38
|
+
if (cur || has)
|
|
39
|
+
out.push(cur);
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
export async function selectTargets(client, query) {
|
|
43
|
+
const i = query.indexOf(":");
|
|
44
|
+
const kind = i < 0 ? query : query.slice(0, i);
|
|
45
|
+
const arg = i < 0 ? "" : query.slice(i + 1);
|
|
46
|
+
if (kind === "prs") {
|
|
47
|
+
if (arg !== "mine" && arg !== "active")
|
|
48
|
+
throw new AihubError("query prs:<mine|active>");
|
|
49
|
+
return (await listPrs(client, { mine: arg === "mine" })).map((p) => String(p.pullRequestId));
|
|
50
|
+
}
|
|
51
|
+
if (kind === "branches") {
|
|
52
|
+
if (!arg)
|
|
53
|
+
throw new AihubError("query branches:<glob>, e.g. branches:release/*");
|
|
54
|
+
const refs = await client.list(`${client.repoPath()}/refs`, { filter: "heads/" });
|
|
55
|
+
return refs.map((r) => shortBranch(r.name)).filter((b) => globMatch(arg, b));
|
|
56
|
+
}
|
|
57
|
+
if (kind === "ids") {
|
|
58
|
+
const ids = arg.split(",").map((x) => x.trim()).filter(Boolean);
|
|
59
|
+
if (!ids.length)
|
|
60
|
+
throw new AihubError("query ids:1,2,3");
|
|
61
|
+
return ids;
|
|
62
|
+
}
|
|
63
|
+
throw new AihubError(`unknown query '${query}'; use prs:mine, prs:active, branches:<glob> or ids:1,2,3`);
|
|
64
|
+
}
|
|
65
|
+
const oneLine = (s) => (s.split("\n").map((l) => l.trim()).find(Boolean) ?? "").slice(0, 110);
|
|
66
|
+
export async function runBatch(targets, template, parallel, runner) {
|
|
67
|
+
const results = new Array(targets.length);
|
|
68
|
+
let next = 0;
|
|
69
|
+
const worker = async () => {
|
|
70
|
+
for (;;) {
|
|
71
|
+
const i = next++;
|
|
72
|
+
if (i >= targets.length)
|
|
73
|
+
return;
|
|
74
|
+
const t = targets[i];
|
|
75
|
+
const argv = template.map((x) => x.split("{target}").join(t));
|
|
76
|
+
try {
|
|
77
|
+
const r = await runner(argv);
|
|
78
|
+
results[i] = { target: t, ok: r.code === 0, summary: oneLine(r.output) };
|
|
79
|
+
}
|
|
80
|
+
catch (e) {
|
|
81
|
+
results[i] = { target: t, ok: false, summary: oneLine(e.message) };
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
await Promise.all(Array.from({ length: Math.min(parallel, targets.length) }, worker));
|
|
86
|
+
return results;
|
|
87
|
+
}
|
|
88
|
+
export async function batch(ctx, o, runner) {
|
|
89
|
+
const { root, client } = repoClient(ctx);
|
|
90
|
+
const dir = join(git(root, ["rev-parse", "--absolute-git-dir"]), "aihub", "batches");
|
|
91
|
+
const parallel = o.parallel ?? 4;
|
|
92
|
+
if (!Number.isInteger(parallel) || parallel < 1 || parallel > MAX_PARALLEL)
|
|
93
|
+
throw new AihubError(`--parallel must be 1..${MAX_PARALLEL}`);
|
|
94
|
+
let run;
|
|
95
|
+
let targets;
|
|
96
|
+
let prior = [];
|
|
97
|
+
if (o.retryFailed) {
|
|
98
|
+
let st;
|
|
99
|
+
try {
|
|
100
|
+
st = JSON.parse(readFileSync(join(dir, `${o.retryFailed}.json`), "utf8"));
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
throw new AihubError(`unknown batch id '${o.retryFailed}'`);
|
|
104
|
+
}
|
|
105
|
+
run = st.run;
|
|
106
|
+
prior = st.results;
|
|
107
|
+
targets = st.results.filter((r) => !r.ok).map((r) => r.target);
|
|
108
|
+
if (!targets.length) {
|
|
109
|
+
ctx.out(`batch ${st.id}: nothing failed, nothing to retry`);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
if (!o.select || !o.run)
|
|
115
|
+
throw new AihubError('usage: aihub batch --select "<query>" --run "<aihub subcommand with {target}>"');
|
|
116
|
+
run = o.run;
|
|
117
|
+
targets = await selectTargets(client, o.select);
|
|
118
|
+
if (!targets.length) {
|
|
119
|
+
ctx.out(`batch: '${o.select}' selected nothing`);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const template = splitCommand(run);
|
|
124
|
+
if (template[0] === "aihub")
|
|
125
|
+
template.shift();
|
|
126
|
+
if (!template.length || template[0] === "batch")
|
|
127
|
+
throw new AihubError("--run needs an aihub subcommand (not batch)");
|
|
128
|
+
if (!run.includes("{target}"))
|
|
129
|
+
throw new AihubError("--run must contain {target}");
|
|
130
|
+
const fresh = await runBatch(targets, template, parallel, runner);
|
|
131
|
+
const merged = o.retryFailed ? prior.map((p) => fresh.find((f) => f.target === p.target) ?? p) : fresh;
|
|
132
|
+
const id = o.retryFailed ?? `b${Date.now().toString(36)}`;
|
|
133
|
+
mkdirSync(dir, { recursive: true });
|
|
134
|
+
writeFileSync(join(dir, `${id}.json`), JSON.stringify({ id, run, results: merged }, null, 1), "utf8");
|
|
135
|
+
const failed = merged.filter((r) => !r.ok);
|
|
136
|
+
if (o.json)
|
|
137
|
+
ctx.out(JSON.stringify({ id, results: merged }));
|
|
138
|
+
else {
|
|
139
|
+
ctx.out(`batch ${id}: ${merged.length - failed.length}/${merged.length} ok`);
|
|
140
|
+
const w = Math.max(...fresh.map((r) => r.target.length));
|
|
141
|
+
for (const r of fresh)
|
|
142
|
+
ctx.out(`${r.target.padEnd(w)} ${r.ok ? "ok " : "FAILED"} ${r.summary}`);
|
|
143
|
+
}
|
|
144
|
+
if (failed.length)
|
|
145
|
+
throw new AihubError(`${failed.length} of ${merged.length} failed; retry with: aihub batch --retry-failed ${id}`);
|
|
146
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { repoDefaultBranch } from "./ado.js";
|
|
2
|
+
import { repoClient } from "./context.js";
|
|
3
|
+
import { AihubError } from "./errors.js";
|
|
4
|
+
import { currentBranch, fetchBranch, git, gitRaw, originDefaultBranch, withTempWorktree } from "./git.js";
|
|
5
|
+
import { defaultTargetFor, isProtected, loadTeam } from "./team.js";
|
|
6
|
+
/** Bring a branch up to date with its target (merge by default, --rebase to rebase); conflicts change nothing. */
|
|
7
|
+
export async function branchUpdate(ctx, o) {
|
|
8
|
+
const { root, client } = repoClient(ctx);
|
|
9
|
+
const team = loadTeam(root);
|
|
10
|
+
const checkedOut = currentBranchOrEmpty(root);
|
|
11
|
+
const branch = o.branch ?? checkedOut;
|
|
12
|
+
if (!branch)
|
|
13
|
+
throw new AihubError("detached HEAD; pass --branch <name>");
|
|
14
|
+
const target = o.target ?? defaultTargetFor(team, client.remote.repo) ?? (originDefaultBranch(root) || undefined) ?? (await repoDefaultBranch(client)) ?? "main";
|
|
15
|
+
if (branch === target)
|
|
16
|
+
throw new AihubError(`'${branch}' is the target itself; nothing to update`);
|
|
17
|
+
if (isProtected(team, branch))
|
|
18
|
+
throw new AihubError(`'${branch}' is a protected branch; the CLI does not change it`);
|
|
19
|
+
if (!fetchBranch(root, target))
|
|
20
|
+
throw new AihubError(`target branch '${target}' not found on origin`);
|
|
21
|
+
const remoteBranchKnown = fetchBranch(root, branch);
|
|
22
|
+
const here = branch === checkedOut;
|
|
23
|
+
let res;
|
|
24
|
+
if (here) {
|
|
25
|
+
if (git(root, ["status", "--porcelain", "--untracked-files=no"]) !== "")
|
|
26
|
+
throw new AihubError("uncommitted changes in this checkout; commit or stash them first");
|
|
27
|
+
res = doUpdate(root, branch, target, !!o.rebase, "HEAD");
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
if (!remoteBranchKnown)
|
|
31
|
+
throw new AihubError(`branch '${branch}' not found on origin`);
|
|
32
|
+
res = await withTempWorktree(root, `origin/${branch}`, (wt) => doUpdate(wt, branch, target, !!o.rebase, "HEAD"));
|
|
33
|
+
}
|
|
34
|
+
if (o.json)
|
|
35
|
+
return JSON.stringify(res);
|
|
36
|
+
return `${res.branch} <- ${res.target}: ${res.result} (${res.detail})`;
|
|
37
|
+
}
|
|
38
|
+
function currentBranchOrEmpty(root) {
|
|
39
|
+
try {
|
|
40
|
+
return currentBranch(root);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return "";
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function doUpdate(dir, branch, target, rebase, pushFrom) {
|
|
47
|
+
const upstream = `origin/${target}`;
|
|
48
|
+
const behind = Number(git(dir, ["rev-list", "--count", `HEAD..${upstream}`]));
|
|
49
|
+
if (behind === 0)
|
|
50
|
+
return { branch, target, result: "up-to-date", detail: "already contains the target" };
|
|
51
|
+
const before = git(dir, ["rev-parse", "HEAD"]);
|
|
52
|
+
const r = rebase ? gitRaw(dir, ["rebase", upstream]) : gitRaw(dir, ["merge", "--no-edit", upstream]);
|
|
53
|
+
if (r.status !== 0) {
|
|
54
|
+
const files = gitRaw(dir, ["diff", "--name-only", "--diff-filter=U"]).stdout.split("\n").filter(Boolean);
|
|
55
|
+
gitRaw(dir, rebase ? ["rebase", "--abort"] : ["merge", "--abort"]);
|
|
56
|
+
if (!files.length)
|
|
57
|
+
throw new AihubError(`${rebase ? "rebase" : "merge"} failed: ${r.stderr.split("\n")[0]}`);
|
|
58
|
+
return { branch, target, result: "conflict", detail: `conflict in ${files.join(", ")}; nothing changed or pushed` };
|
|
59
|
+
}
|
|
60
|
+
const push = gitRaw(dir, [
|
|
61
|
+
"push",
|
|
62
|
+
"--quiet",
|
|
63
|
+
...(rebase ? [`--force-with-lease=refs/heads/${branch}:${git(dir, ["rev-parse", `origin/${branch}`], { allowFail: true }) || before}`] : []),
|
|
64
|
+
"origin",
|
|
65
|
+
`${pushFrom}:refs/heads/${branch}`,
|
|
66
|
+
]);
|
|
67
|
+
if (push.status !== 0) {
|
|
68
|
+
gitRaw(dir, ["reset", "--hard", before]);
|
|
69
|
+
throw new AihubError(`push of '${branch}' rejected (someone pushed meanwhile?); local branch restored: ${push.stderr.split("\n").pop()}`);
|
|
70
|
+
}
|
|
71
|
+
return { branch, target, result: "updated", detail: `${behind} commit(s) from ${target} ${rebase ? "rebased onto" : "merged into"} ${branch}, pushed` };
|
|
72
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { branchRef, getPr, getWorkItemPrIds, getWorkItemTitle, shortBranch } from "./ado.js";
|
|
2
|
+
import { repoClient } from "./context.js";
|
|
3
|
+
import { AihubError } from "./errors.js";
|
|
4
|
+
import { fetchBranch, git, gitRaw, withTempWorktree } from "./git.js";
|
|
5
|
+
import { commitList, parsePrRef } from "./pr.js";
|
|
6
|
+
import { compose, DEFAULT_EMPTY, resolveTemplate } from "./templates.js";
|
|
7
|
+
import { isProtected, loadTeam, readUtf8 } from "./team.js";
|
|
8
|
+
import { showFile } from "./git.js";
|
|
9
|
+
/**
|
|
10
|
+
* `--from` items, comma separated: `42` / `pr:42` / a pullrequest URL = PR; `story:7` / `AB#7` / a _workitems URL = story;
|
|
11
|
+
* a hex string with 7-40 characters = commit. Plain digits up to 6 characters are always a PR number.
|
|
12
|
+
*/
|
|
13
|
+
export function parseSources(from) {
|
|
14
|
+
const out = [];
|
|
15
|
+
for (const raw of from.split(",").map((s) => s.trim()).filter(Boolean)) {
|
|
16
|
+
let m;
|
|
17
|
+
if ((m = /pullrequest\/(\d+)/i.exec(raw)) || (m = /^(?:pr:|!)(\d+)$/i.exec(raw)))
|
|
18
|
+
out.push({ kind: "pr", id: Number(m[1]) });
|
|
19
|
+
else if ((m = /_workitems\/edit\/(\d+)/i.exec(raw)) || (m = /^(?:story:|AB#)(\d+)$/i.exec(raw)))
|
|
20
|
+
out.push({ kind: "story", id: Number(m[1]) });
|
|
21
|
+
else if (/^\d{1,6}$/.test(raw))
|
|
22
|
+
out.push({ kind: "pr", id: parsePrRef(raw) });
|
|
23
|
+
else if (/^[0-9a-f]{7,40}$/i.test(raw))
|
|
24
|
+
out.push({ kind: "commit", sha: raw.toLowerCase() });
|
|
25
|
+
else
|
|
26
|
+
throw new AihubError(`--from '${raw}' is not a PR, story or commit (use 42, pr:42, story:7 or a commit sha)`);
|
|
27
|
+
}
|
|
28
|
+
if (!out.length)
|
|
29
|
+
throw new AihubError("--from is empty");
|
|
30
|
+
return out;
|
|
31
|
+
}
|
|
32
|
+
function commitInfo(root, sha) {
|
|
33
|
+
const line = git(root, ["rev-list", "--parents", "--format=%s", "-n1", sha]).split("\n");
|
|
34
|
+
const parents = (line[0] ?? "").trim().split(/\s+/).length - 2; // "commit <sha> <parents..>"
|
|
35
|
+
return { sha, mainline: parents > 1, subject: line[1] ?? "" };
|
|
36
|
+
}
|
|
37
|
+
async function resolvePrCommits(client, root, id) {
|
|
38
|
+
const pr = (await getPr(client, id));
|
|
39
|
+
const tgt = shortBranch(pr.targetRefName);
|
|
40
|
+
const src = shortBranch(pr.sourceRefName);
|
|
41
|
+
fetchBranch(root, tgt);
|
|
42
|
+
if (pr.status === "completed" && pr.lastMergeCommit?.commitId) {
|
|
43
|
+
if (gitRaw(root, ["cat-file", "-e", pr.lastMergeCommit.commitId]).status !== 0)
|
|
44
|
+
gitRaw(root, ["fetch", "--quiet", "origin", pr.lastMergeCommit.commitId]);
|
|
45
|
+
return [commitInfo(root, pr.lastMergeCommit.commitId)];
|
|
46
|
+
}
|
|
47
|
+
if (!fetchBranch(root, src))
|
|
48
|
+
throw new AihubError(`PR !${id} is not completed and its source branch '${src}' is gone`);
|
|
49
|
+
const base = git(root, ["merge-base", `origin/${tgt}`, `origin/${src}`]);
|
|
50
|
+
const shas = git(root, ["rev-list", "--reverse", "--no-merges", `${base}..origin/${src}`]).split("\n").filter(Boolean);
|
|
51
|
+
return shas.map((s) => commitInfo(root, s));
|
|
52
|
+
}
|
|
53
|
+
export async function resolveSources(client, root, sources) {
|
|
54
|
+
const commits = [];
|
|
55
|
+
const labels = [];
|
|
56
|
+
let story;
|
|
57
|
+
for (const s of sources) {
|
|
58
|
+
if (s.kind === "pr") {
|
|
59
|
+
labels.push(`pr${s.id}`);
|
|
60
|
+
commits.push(...(await resolvePrCommits(client, root, s.id)));
|
|
61
|
+
}
|
|
62
|
+
else if (s.kind === "story") {
|
|
63
|
+
labels.push(`story${s.id}`);
|
|
64
|
+
story = s.id;
|
|
65
|
+
const ids = await getWorkItemPrIds(client, s.id);
|
|
66
|
+
if (!ids.length)
|
|
67
|
+
throw new AihubError(`story ${s.id} has no linked pull requests`);
|
|
68
|
+
for (const id of ids)
|
|
69
|
+
commits.push(...(await resolvePrCommits(client, root, id)));
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
labels.push(s.sha.slice(0, 7));
|
|
73
|
+
gitRaw(root, ["fetch", "--quiet", "origin"]);
|
|
74
|
+
if (gitRaw(root, ["cat-file", "-e", `${s.sha}^{commit}`]).status !== 0)
|
|
75
|
+
throw new AihubError(`commit ${s.sha} not found; fetch it first`);
|
|
76
|
+
commits.push(commitInfo(root, git(root, ["rev-parse", s.sha])));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
// de-duplicate, keep order
|
|
80
|
+
const seen = new Set();
|
|
81
|
+
const uniq = commits.filter((c) => !seen.has(c.sha) && !!seen.add(c.sha));
|
|
82
|
+
return { label: labels.join("+").slice(0, 40), commits: uniq, story };
|
|
83
|
+
}
|
|
84
|
+
export const pickBranchName = (label, target) => `cherry-pick/${label}-to-${target.replace(/[^A-Za-z0-9._-]+/g, "-")}`;
|
|
85
|
+
export async function cherryPick(ctx, o) {
|
|
86
|
+
const { root, client } = repoClient(ctx);
|
|
87
|
+
const team = loadTeam(root);
|
|
88
|
+
const targets = [...o.to];
|
|
89
|
+
if (o.toGroup) {
|
|
90
|
+
const g = team.cherryPick?.groups?.[o.toGroup];
|
|
91
|
+
if (!g?.length)
|
|
92
|
+
throw new AihubError(`cherry-pick group '${o.toGroup}' is not in team.yaml (cherryPick.groups)`);
|
|
93
|
+
targets.push(...g);
|
|
94
|
+
}
|
|
95
|
+
const uniqTargets = [...new Set(targets)];
|
|
96
|
+
if (!uniqTargets.length)
|
|
97
|
+
throw new AihubError("pass --to <branch> (repeatable) or --to-group <name>");
|
|
98
|
+
if (o.direct && o.pr)
|
|
99
|
+
throw new AihubError("--direct and --pr exclude each other");
|
|
100
|
+
const src = await resolveSources(client, root, parseSources(o.from));
|
|
101
|
+
if (!src.commits.length)
|
|
102
|
+
throw new AihubError("nothing to cherry-pick: the source has no commits");
|
|
103
|
+
const results = [];
|
|
104
|
+
for (const t of uniqTargets)
|
|
105
|
+
results.push(await pickOne(client, root, team, src, t, o));
|
|
106
|
+
const failed = results.filter((r) => r.result === "conflict" || r.result === "failed" || r.result === "refused");
|
|
107
|
+
if (o.json) {
|
|
108
|
+
ctx.out(JSON.stringify({ source: src.label, commits: src.commits.map((c) => c.sha), results }));
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
ctx.out(`cherry-pick ${src.label} (${src.commits.length} commit${src.commits.length === 1 ? "" : "s"}) -> ${uniqTargets.length} target(s)`);
|
|
112
|
+
const w = Math.max(...results.map((r) => r.target.length));
|
|
113
|
+
for (const r of results)
|
|
114
|
+
ctx.out(`${r.target.padEnd(w)} ${r.result.padEnd(15)} ${r.detail}${r.pr ? ` PR !${r.pr.id} ${r.pr.url}` : ""}`);
|
|
115
|
+
}
|
|
116
|
+
if (failed.length)
|
|
117
|
+
throw new AihubError(`${failed.length} of ${results.length} target(s) need attention (${failed.map((f) => f.target).join(", ")})`);
|
|
118
|
+
}
|
|
119
|
+
async function pickOne(client, root, team, src, target, o) {
|
|
120
|
+
try {
|
|
121
|
+
if (o.direct && isProtected(team, target))
|
|
122
|
+
return { target, result: "refused", detail: `'${target}' is protected; use --pr` };
|
|
123
|
+
if (!fetchBranch(root, target))
|
|
124
|
+
return { target, result: "failed", detail: `branch '${target}' not found on origin` };
|
|
125
|
+
const branch = pickBranchName(src.label, target);
|
|
126
|
+
return await withTempWorktree(root, `origin/${target}`, async (wt) => {
|
|
127
|
+
const start = git(wt, ["rev-parse", "HEAD"]);
|
|
128
|
+
git(wt, ["checkout", "-q", "-b", branch]);
|
|
129
|
+
for (const c of src.commits) {
|
|
130
|
+
const r = gitRaw(wt, ["cherry-pick", ...(c.mainline ? ["-m", "1"] : []), c.sha]);
|
|
131
|
+
if (r.status === 0)
|
|
132
|
+
continue;
|
|
133
|
+
const files = gitRaw(wt, ["diff", "--name-only", "--diff-filter=U"]).stdout.split("\n").filter(Boolean);
|
|
134
|
+
if (files.length) {
|
|
135
|
+
gitRaw(wt, ["cherry-pick", "--abort"]);
|
|
136
|
+
return { target, result: "conflict", detail: `conflict in ${files.join(", ")} (${c.sha.slice(0, 7)}); nothing pushed` };
|
|
137
|
+
}
|
|
138
|
+
if (/empty|nothing to commit/i.test(r.stdout + r.stderr)) {
|
|
139
|
+
gitRaw(wt, ["cherry-pick", "--skip"]);
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
gitRaw(wt, ["cherry-pick", "--abort"]);
|
|
143
|
+
return { target, result: "failed", detail: r.stderr.split("\n")[0] || "cherry-pick failed" };
|
|
144
|
+
}
|
|
145
|
+
if (git(wt, ["rev-parse", "HEAD"]) === start)
|
|
146
|
+
return { target, result: "already-applied", detail: "target already contains these changes" };
|
|
147
|
+
const dest = o.direct ? target : branch;
|
|
148
|
+
const push = gitRaw(wt, ["push", "--quiet", "origin", `HEAD:refs/heads/${dest}`]);
|
|
149
|
+
if (push.status !== 0)
|
|
150
|
+
return { target, result: "failed", detail: `push of '${dest}' rejected: ${push.stderr.split("\n").pop()}` };
|
|
151
|
+
const res = { target, result: "ok", branch: dest, detail: o.direct ? `pushed to ${dest}` : `pushed ${dest}` };
|
|
152
|
+
if (o.pr)
|
|
153
|
+
res.pr = await createPickPr(client, root, team, src, target, branch, o.bodyFile);
|
|
154
|
+
return res;
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
catch (e) {
|
|
158
|
+
return { target, result: "failed", detail: e.message };
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
async function createPickPr(client, root, team, src, target, branch, bodyFile) {
|
|
162
|
+
const commits = src.commits.map((c) => ({ sha: c.sha.slice(0, 7), subject: c.subject }));
|
|
163
|
+
const wi = src.story;
|
|
164
|
+
const wiTitle = wi ? await getWorkItemTitle(client, wi) : undefined;
|
|
165
|
+
const title = `Cherry-pick ${src.label} to ${target}: ${commits[0].subject}`.slice(0, 200);
|
|
166
|
+
const body = bodyFile ? readUtf8(bodyFile) : "";
|
|
167
|
+
const tpl = resolveTemplate(target, { readRef: (b, p) => showFile(root, b, p), localRoot: root });
|
|
168
|
+
const code = { story: wi ? `AB#${wi}${wiTitle ? ` ${wiTitle}` : ""}` : undefined, commits: commitList(commits) };
|
|
169
|
+
let description;
|
|
170
|
+
if (tpl)
|
|
171
|
+
description = compose({ template: tpl.content, body, code, emptyText: team.pullRequest?.emptySection || DEFAULT_EMPTY }).text;
|
|
172
|
+
else
|
|
173
|
+
description = [body.trim(), `## Commits\n\n${code.commits}`].filter(Boolean).join("\n\n") + "\n";
|
|
174
|
+
const created = await client.post(`${client.repoPath()}/pullrequests`, {
|
|
175
|
+
sourceRefName: branchRef(branch),
|
|
176
|
+
targetRefName: branchRef(target),
|
|
177
|
+
title,
|
|
178
|
+
description,
|
|
179
|
+
...(wi ? { workItemRefs: [{ id: String(wi) }] } : {}),
|
|
180
|
+
});
|
|
181
|
+
return { id: created.pullRequestId, url: client.prUrl(created.pullRequestId) };
|
|
182
|
+
}
|
package/dist/lib/git.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
2
5
|
import { AihubError } from "./errors.js";
|
|
3
6
|
export function git(cwd, args, opts = {}) {
|
|
4
7
|
const r = spawnSync("git", args, { cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
|
|
@@ -77,3 +80,32 @@ export function workItemFromBranch(branch) {
|
|
|
77
80
|
const m = /(?:^|\/)(\d{1,9})(?=[-_/]|$)/.exec(branch);
|
|
78
81
|
return m ? Number(m[1]) : undefined;
|
|
79
82
|
}
|
|
83
|
+
/** Run git and return the exit status instead of throwing. */
|
|
84
|
+
export function gitRaw(cwd, args) {
|
|
85
|
+
const r = spawnSync("git", args, { cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
|
|
86
|
+
if (r.error)
|
|
87
|
+
throw new AihubError(`git is not available: ${r.error.message}`);
|
|
88
|
+
return { status: r.status ?? 1, stdout: r.stdout.split("\r\n").join("\n").trimEnd(), stderr: (r.stderr || "").trim() };
|
|
89
|
+
}
|
|
90
|
+
/** Run `fn` inside a throw-away detached worktree at `ref`; the user's checkout is never touched. */
|
|
91
|
+
export async function withTempWorktree(root, ref, fn) {
|
|
92
|
+
const dir = join(mkdtempSync(join(tmpdir(), "aihub-wt-")), "wt");
|
|
93
|
+
git(root, ["worktree", "add", "--detach", dir, ref]);
|
|
94
|
+
try {
|
|
95
|
+
return await fn(dir);
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
gitRaw(root, ["worktree", "remove", "--force", dir]);
|
|
99
|
+
try {
|
|
100
|
+
rmSync(join(dir, ".."), { recursive: true, force: true });
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
/* best effort */
|
|
104
|
+
}
|
|
105
|
+
gitRaw(root, ["worktree", "prune"]);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/** Fetch one branch of origin into refs/remotes/origin/<branch>. Returns false when origin has no such branch. */
|
|
109
|
+
export function fetchBranch(root, branch) {
|
|
110
|
+
return gitRaw(root, ["fetch", "--quiet", "origin", `+refs/heads/${branch}:refs/remotes/origin/${branch}`]).status === 0;
|
|
111
|
+
}
|