bstack 0.0.0 → 0.2.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 +26 -5
- package/dist/bstack.js +730 -0
- package/package.json +15 -10
- package/src/checkout.ts +0 -67
- package/src/cli.ts +0 -100
- package/src/command.ts +0 -61
- package/src/git.ts +0 -197
- package/src/github.ts +0 -187
- package/src/identity.ts +0 -88
- package/src/model.ts +0 -44
- package/src/reporter.ts +0 -11
- package/src/state.ts +0 -52
- package/src/sync.ts +0 -251
package/dist/bstack.js
ADDED
|
@@ -0,0 +1,730 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { parseArgs } from "node:util";
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { dirname } from "node:path";
|
|
7
|
+
//#region package.json
|
|
8
|
+
var version = "0.2.0";
|
|
9
|
+
//#endregion
|
|
10
|
+
//#region src/command.ts
|
|
11
|
+
var CommandError = class extends Error {
|
|
12
|
+
command;
|
|
13
|
+
result;
|
|
14
|
+
constructor(command, result) {
|
|
15
|
+
const detail = result.stderr.trim() || result.stdout.trim();
|
|
16
|
+
super(`${command.join(" ")} failed with exit code ${result.exitCode}${detail ? `\n${detail}` : ""}`);
|
|
17
|
+
this.command = command;
|
|
18
|
+
this.result = result;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
var NodeCommandRunner = class {
|
|
22
|
+
run(command, options) {
|
|
23
|
+
const [executable, ...args] = command;
|
|
24
|
+
if (!executable) throw new Error("Cannot run an empty command");
|
|
25
|
+
const result = spawnSync(executable, args, {
|
|
26
|
+
cwd: options.cwd,
|
|
27
|
+
input: options.stdin,
|
|
28
|
+
encoding: "utf8",
|
|
29
|
+
env: options.env === void 0 ? process.env : {
|
|
30
|
+
...process.env,
|
|
31
|
+
...options.env
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
const commandResult = {
|
|
35
|
+
stdout: result.stdout ?? "",
|
|
36
|
+
stderr: result.stderr ?? result.error?.message ?? "",
|
|
37
|
+
exitCode: result.status ?? 1
|
|
38
|
+
};
|
|
39
|
+
if (commandResult.exitCode !== 0 && !options.allowFailure) throw new CommandError(command, commandResult);
|
|
40
|
+
return commandResult;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
//#endregion
|
|
44
|
+
//#region src/checkout.ts
|
|
45
|
+
function checkoutStack(repository, github, options) {
|
|
46
|
+
const { reporter } = options;
|
|
47
|
+
reporter.progress("Checking the repository and GitHub prerequisites");
|
|
48
|
+
repository.assertReady();
|
|
49
|
+
github.assertReady();
|
|
50
|
+
const remote = repository.resolveRemote(options.remote);
|
|
51
|
+
reporter.progress(`Looking up pull request ${options.reference}`);
|
|
52
|
+
const headRef = github.pullRequestHead(options.reference);
|
|
53
|
+
if (!headRef.startsWith("bstack/")) {
|
|
54
|
+
reporter.progress("This is not a bstack pull request; delegating to gh pr checkout");
|
|
55
|
+
github.checkoutPullRequest(options.reference);
|
|
56
|
+
return {
|
|
57
|
+
headRef,
|
|
58
|
+
delegated: true
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
let currentBase;
|
|
62
|
+
let remoteBase;
|
|
63
|
+
if (options.sameBase) {
|
|
64
|
+
const base = options.base ?? github.defaultBranch();
|
|
65
|
+
reporter.progress(`Checking that the merge base remains on ${remote}/${base}`);
|
|
66
|
+
remoteBase = repository.fetchBase(remote, base);
|
|
67
|
+
currentBase = repository.mergeBase("HEAD", remoteBase);
|
|
68
|
+
}
|
|
69
|
+
reporter.progress(`Fetching ${remote}/${headRef}`);
|
|
70
|
+
const target = repository.fetchRemoteBranch(remote, headRef);
|
|
71
|
+
if (currentBase && remoteBase) {
|
|
72
|
+
const targetBase = repository.mergeBase(target, remoteBase);
|
|
73
|
+
if (currentBase !== targetBase) throw new Error(`Checkout would change the merge base from ${currentBase.slice(0, 8)} to ${targetBase.slice(0, 8)}`);
|
|
74
|
+
}
|
|
75
|
+
reporter.progress(`Checking out ${remote}/${headRef} in detached HEAD state`);
|
|
76
|
+
repository.checkout(target);
|
|
77
|
+
reporter.progress("Checkout complete; amend the commits and run bstack to publish updates");
|
|
78
|
+
return {
|
|
79
|
+
headRef,
|
|
80
|
+
delegated: false
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
//#endregion
|
|
84
|
+
//#region src/identity.ts
|
|
85
|
+
const trailerPattern = /^Bstack-Id:\s*(\S+)\s*$/gim;
|
|
86
|
+
function readChangeId(message) {
|
|
87
|
+
const matches = [...message.matchAll(trailerPattern)];
|
|
88
|
+
if (matches.length > 1) throw new Error("A commit contains more than one Bstack-Id trailer");
|
|
89
|
+
return matches[0]?.[1];
|
|
90
|
+
}
|
|
91
|
+
function addChangeId(message, changeId) {
|
|
92
|
+
return `${message.trimEnd()}\n\nBstack-Id: ${changeId}\n`;
|
|
93
|
+
}
|
|
94
|
+
function newChangeId() {
|
|
95
|
+
return randomUUID().replaceAll("-", "");
|
|
96
|
+
}
|
|
97
|
+
function parseRawCommit(oid, raw) {
|
|
98
|
+
const boundary = raw.indexOf("\n\n");
|
|
99
|
+
if (boundary === -1) throw new Error(`Commit ${oid} has an invalid object format`);
|
|
100
|
+
const headers = raw.slice(0, boundary).split("\n");
|
|
101
|
+
const treeLine = headers.find((line) => line.startsWith("tree "));
|
|
102
|
+
const parents = headers.filter((line) => line.startsWith("parent "));
|
|
103
|
+
if (!treeLine || parents.length !== 1) throw new Error(`Commit ${oid} must have exactly one parent; merge and root commits are not supported`);
|
|
104
|
+
if (headers.some((line) => line.startsWith("gpgsig "))) throw new Error(`Commit ${oid} is signed. bstack cannot add an identity trailer without replacing its signature`);
|
|
105
|
+
const message = raw.slice(boundary + 2);
|
|
106
|
+
return {
|
|
107
|
+
oid,
|
|
108
|
+
tree: treeLine.slice(5),
|
|
109
|
+
parent: parents[0].slice(7),
|
|
110
|
+
message,
|
|
111
|
+
headers,
|
|
112
|
+
changeId: readChangeId(message)
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
function rewriteCommit(commit, parent, message) {
|
|
116
|
+
const rewrittenHeaders = [];
|
|
117
|
+
let replacedParent = false;
|
|
118
|
+
for (const header of commit.headers) {
|
|
119
|
+
if (header.startsWith("parent ")) {
|
|
120
|
+
if (!replacedParent) {
|
|
121
|
+
rewrittenHeaders.push(`parent ${parent}`);
|
|
122
|
+
replacedParent = true;
|
|
123
|
+
}
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
rewrittenHeaders.push(header);
|
|
127
|
+
}
|
|
128
|
+
return `${rewrittenHeaders.join("\n")}\n\n${message}`;
|
|
129
|
+
}
|
|
130
|
+
function splitCommitMessage(message) {
|
|
131
|
+
const [subject = "Untitled change", ...bodyLines] = message.split("\n").filter((line) => !/^Bstack-Id:\s*\S+\s*$/i.test(line)).join("\n").trim().split("\n");
|
|
132
|
+
return {
|
|
133
|
+
subject,
|
|
134
|
+
body: bodyLines.join("\n").trim()
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
//#endregion
|
|
138
|
+
//#region src/git.ts
|
|
139
|
+
var GitRepository = class {
|
|
140
|
+
cwd;
|
|
141
|
+
runner;
|
|
142
|
+
constructor(cwd, runner) {
|
|
143
|
+
this.cwd = cwd;
|
|
144
|
+
this.runner = runner;
|
|
145
|
+
}
|
|
146
|
+
git(args, options = {}) {
|
|
147
|
+
return this.runner.run(["git", ...args], {
|
|
148
|
+
cwd: this.cwd,
|
|
149
|
+
...options
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
assertReady() {
|
|
153
|
+
this.git(["rev-parse", "--show-toplevel"]);
|
|
154
|
+
if (this.git(["status", "--porcelain"]).stdout.trim()) throw new Error("The working tree must be clean before bstack rewrites or publishes commits");
|
|
155
|
+
}
|
|
156
|
+
currentBranch() {
|
|
157
|
+
return this.git([
|
|
158
|
+
"symbolic-ref",
|
|
159
|
+
"--quiet",
|
|
160
|
+
"--short",
|
|
161
|
+
"HEAD"
|
|
162
|
+
], { allowFailure: true }).stdout.trim();
|
|
163
|
+
}
|
|
164
|
+
remotes() {
|
|
165
|
+
return this.git(["remote"]).stdout.split("\n").filter(Boolean);
|
|
166
|
+
}
|
|
167
|
+
configuredPushRemote() {
|
|
168
|
+
const result = this.git([
|
|
169
|
+
"config",
|
|
170
|
+
"--get",
|
|
171
|
+
"remote.pushDefault"
|
|
172
|
+
], { allowFailure: true });
|
|
173
|
+
return result.exitCode === 0 ? result.stdout.trim() || void 0 : void 0;
|
|
174
|
+
}
|
|
175
|
+
resolveRemote(requested) {
|
|
176
|
+
if (requested) {
|
|
177
|
+
if (!this.remotes().includes(requested)) throw new Error(`Git remote ${requested} does not exist`);
|
|
178
|
+
return requested;
|
|
179
|
+
}
|
|
180
|
+
const configured = this.configuredPushRemote();
|
|
181
|
+
if (configured) return configured;
|
|
182
|
+
const remotes = this.remotes();
|
|
183
|
+
if (remotes.length === 1) return remotes[0];
|
|
184
|
+
if (remotes.includes("origin")) return "origin";
|
|
185
|
+
throw new Error("Cannot choose a Git remote. Pass --remote or configure remote.pushDefault");
|
|
186
|
+
}
|
|
187
|
+
fetchBase(remote, base) {
|
|
188
|
+
const destination = `refs/remotes/${remote}/${base}`;
|
|
189
|
+
this.git([
|
|
190
|
+
"fetch",
|
|
191
|
+
"--no-tags",
|
|
192
|
+
remote,
|
|
193
|
+
`refs/heads/${base}:${destination}`
|
|
194
|
+
]);
|
|
195
|
+
return destination;
|
|
196
|
+
}
|
|
197
|
+
fetchRemoteBranch(remote, branch) {
|
|
198
|
+
const destination = `refs/remotes/${remote}/${branch}`;
|
|
199
|
+
this.git([
|
|
200
|
+
"fetch",
|
|
201
|
+
"--no-tags",
|
|
202
|
+
remote,
|
|
203
|
+
`+refs/heads/${branch}:${destination}`
|
|
204
|
+
]);
|
|
205
|
+
return destination;
|
|
206
|
+
}
|
|
207
|
+
checkout(ref) {
|
|
208
|
+
this.git([
|
|
209
|
+
"checkout",
|
|
210
|
+
"--detach",
|
|
211
|
+
ref
|
|
212
|
+
]);
|
|
213
|
+
}
|
|
214
|
+
mergeBase(left, right) {
|
|
215
|
+
return this.git([
|
|
216
|
+
"merge-base",
|
|
217
|
+
left,
|
|
218
|
+
right
|
|
219
|
+
]).stdout.trim();
|
|
220
|
+
}
|
|
221
|
+
commitsSince(baseOid) {
|
|
222
|
+
return this.git([
|
|
223
|
+
"rev-list",
|
|
224
|
+
"--reverse",
|
|
225
|
+
"--first-parent",
|
|
226
|
+
`${baseOid}..HEAD`
|
|
227
|
+
]).stdout.split("\n").filter(Boolean).map((oid) => parseRawCommit(oid, this.git([
|
|
228
|
+
"cat-file",
|
|
229
|
+
"commit",
|
|
230
|
+
oid
|
|
231
|
+
]).stdout));
|
|
232
|
+
}
|
|
233
|
+
ensureChangeIds(commits, dryRun) {
|
|
234
|
+
const assigned = commits.map((commit) => commit.changeId ?? newChangeId());
|
|
235
|
+
const needsRewrite = commits.some((commit) => commit.changeId === void 0);
|
|
236
|
+
let parent = commits[0]?.parent;
|
|
237
|
+
const rewrittenOids = [];
|
|
238
|
+
if (needsRewrite && !dryRun) {
|
|
239
|
+
for (const [index, commit] of commits.entries()) {
|
|
240
|
+
const changeId = assigned[index];
|
|
241
|
+
const message = commit.changeId ? commit.message : addChangeId(commit.message, changeId);
|
|
242
|
+
const raw = rewriteCommit(commit, parent, message);
|
|
243
|
+
const oid = this.git([
|
|
244
|
+
"hash-object",
|
|
245
|
+
"-t",
|
|
246
|
+
"commit",
|
|
247
|
+
"-w",
|
|
248
|
+
"--stdin"
|
|
249
|
+
], { stdin: raw }).stdout.trim();
|
|
250
|
+
rewrittenOids.push(oid);
|
|
251
|
+
parent = oid;
|
|
252
|
+
}
|
|
253
|
+
const oldHead = commits.at(-1).oid;
|
|
254
|
+
const newHead = rewrittenOids.at(-1);
|
|
255
|
+
this.git([
|
|
256
|
+
"update-ref",
|
|
257
|
+
"HEAD",
|
|
258
|
+
newHead,
|
|
259
|
+
oldHead
|
|
260
|
+
]);
|
|
261
|
+
}
|
|
262
|
+
return commits.map((commit, index) => {
|
|
263
|
+
const id = assigned[index];
|
|
264
|
+
const oid = needsRewrite && !dryRun ? rewrittenOids[index] : commit.oid;
|
|
265
|
+
const { subject, body } = splitCommitMessage(commit.message);
|
|
266
|
+
return {
|
|
267
|
+
id,
|
|
268
|
+
oid,
|
|
269
|
+
subject,
|
|
270
|
+
body,
|
|
271
|
+
remoteBranch: `bstack/${id}`
|
|
272
|
+
};
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
remoteBranchOids(remote, branches) {
|
|
276
|
+
if (branches.length === 0) return /* @__PURE__ */ new Map();
|
|
277
|
+
const result = this.git([
|
|
278
|
+
"ls-remote",
|
|
279
|
+
"--heads",
|
|
280
|
+
remote,
|
|
281
|
+
...branches.map((branch) => `refs/heads/${branch}`)
|
|
282
|
+
]);
|
|
283
|
+
return new Map(result.stdout.split("\n").filter(Boolean).map((line) => {
|
|
284
|
+
const [oid, ref] = line.split(/\s+/, 2);
|
|
285
|
+
return [ref.replace("refs/heads/", ""), oid];
|
|
286
|
+
}));
|
|
287
|
+
}
|
|
288
|
+
pushChanges(remote, changes) {
|
|
289
|
+
const existing = this.remoteBranchOids(remote, changes.map((change) => change.remoteBranch));
|
|
290
|
+
const leases = [];
|
|
291
|
+
const refspecs = [];
|
|
292
|
+
for (const change of changes) {
|
|
293
|
+
const expected = existing.get(change.remoteBranch) ?? "";
|
|
294
|
+
leases.push(`--force-with-lease=refs/heads/${change.remoteBranch}:${expected}`);
|
|
295
|
+
refspecs.push(`${change.oid}:refs/heads/${change.remoteBranch}`);
|
|
296
|
+
}
|
|
297
|
+
this.git([
|
|
298
|
+
"push",
|
|
299
|
+
"--atomic",
|
|
300
|
+
...leases,
|
|
301
|
+
remote,
|
|
302
|
+
...refspecs
|
|
303
|
+
]);
|
|
304
|
+
}
|
|
305
|
+
statePath() {
|
|
306
|
+
return this.git([
|
|
307
|
+
"rev-parse",
|
|
308
|
+
"--path-format=absolute",
|
|
309
|
+
"--git-path",
|
|
310
|
+
"bstack/state.json"
|
|
311
|
+
]).stdout.trim();
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
//#endregion
|
|
315
|
+
//#region src/github.ts
|
|
316
|
+
var GhPlatform = class {
|
|
317
|
+
cwd;
|
|
318
|
+
runner;
|
|
319
|
+
constructor(cwd, runner) {
|
|
320
|
+
this.cwd = cwd;
|
|
321
|
+
this.runner = runner;
|
|
322
|
+
}
|
|
323
|
+
gh(args) {
|
|
324
|
+
return this.runner.run(["gh", ...args], { cwd: this.cwd });
|
|
325
|
+
}
|
|
326
|
+
assertReady() {
|
|
327
|
+
this.gh([
|
|
328
|
+
"auth",
|
|
329
|
+
"status",
|
|
330
|
+
"--active"
|
|
331
|
+
]);
|
|
332
|
+
this.gh(["stack", "--version"]);
|
|
333
|
+
}
|
|
334
|
+
defaultBranch() {
|
|
335
|
+
return this.gh([
|
|
336
|
+
"repo",
|
|
337
|
+
"view",
|
|
338
|
+
"--json",
|
|
339
|
+
"defaultBranchRef",
|
|
340
|
+
"--jq",
|
|
341
|
+
".defaultBranchRef.name"
|
|
342
|
+
]).stdout.trim();
|
|
343
|
+
}
|
|
344
|
+
pullRequestForBranch(branch) {
|
|
345
|
+
const raw = this.gh([
|
|
346
|
+
"pr",
|
|
347
|
+
"list",
|
|
348
|
+
"--head",
|
|
349
|
+
branch,
|
|
350
|
+
"--state",
|
|
351
|
+
"all",
|
|
352
|
+
"--limit",
|
|
353
|
+
"20",
|
|
354
|
+
"--json",
|
|
355
|
+
"number,url,state,title,body,isDraft"
|
|
356
|
+
]).stdout;
|
|
357
|
+
const candidates = JSON.parse(raw);
|
|
358
|
+
const selected = candidates.find((pr) => pr.state === "OPEN") ?? candidates.find((pr) => pr.state === "MERGED");
|
|
359
|
+
return selected ? normalizePullRequest(selected) : void 0;
|
|
360
|
+
}
|
|
361
|
+
pullRequest(number) {
|
|
362
|
+
const raw = this.gh([
|
|
363
|
+
"pr",
|
|
364
|
+
"view",
|
|
365
|
+
String(number),
|
|
366
|
+
"--json",
|
|
367
|
+
"number,url,state,title,body,isDraft"
|
|
368
|
+
]).stdout;
|
|
369
|
+
return normalizePullRequest(JSON.parse(raw));
|
|
370
|
+
}
|
|
371
|
+
createPullRequest(change, base, open) {
|
|
372
|
+
const args = [
|
|
373
|
+
"pr",
|
|
374
|
+
"create",
|
|
375
|
+
"--base",
|
|
376
|
+
base,
|
|
377
|
+
"--head",
|
|
378
|
+
change.remoteBranch,
|
|
379
|
+
"--title",
|
|
380
|
+
change.subject,
|
|
381
|
+
"--body",
|
|
382
|
+
change.body
|
|
383
|
+
];
|
|
384
|
+
if (!open) args.push("--draft");
|
|
385
|
+
this.gh(args);
|
|
386
|
+
const created = this.pullRequestForBranch(change.remoteBranch);
|
|
387
|
+
if (!created) throw new Error(`GitHub did not return the PR created for ${change.remoteBranch}`);
|
|
388
|
+
return created;
|
|
389
|
+
}
|
|
390
|
+
linkStack(branches, base, remote, open) {
|
|
391
|
+
const args = [
|
|
392
|
+
"stack",
|
|
393
|
+
"link",
|
|
394
|
+
"--base",
|
|
395
|
+
base,
|
|
396
|
+
"--remote",
|
|
397
|
+
remote
|
|
398
|
+
];
|
|
399
|
+
if (open) args.push("--open");
|
|
400
|
+
args.push(...branches);
|
|
401
|
+
this.gh(args);
|
|
402
|
+
}
|
|
403
|
+
appendToStack(stackNumber, branches, remote, open) {
|
|
404
|
+
const args = [
|
|
405
|
+
"stack",
|
|
406
|
+
"link",
|
|
407
|
+
"--remote",
|
|
408
|
+
remote
|
|
409
|
+
];
|
|
410
|
+
if (open) args.push("--open");
|
|
411
|
+
args.push(String(stackNumber), ...branches);
|
|
412
|
+
this.gh(args);
|
|
413
|
+
}
|
|
414
|
+
editPullRequest(pr, change) {
|
|
415
|
+
if (pr.title === change.subject && pr.body === change.body) return;
|
|
416
|
+
this.gh([
|
|
417
|
+
"pr",
|
|
418
|
+
"edit",
|
|
419
|
+
String(pr.number),
|
|
420
|
+
"--title",
|
|
421
|
+
change.subject,
|
|
422
|
+
"--body",
|
|
423
|
+
change.body
|
|
424
|
+
]);
|
|
425
|
+
}
|
|
426
|
+
stackNumberForPullRequest(prNumber) {
|
|
427
|
+
const raw = this.gh(["api", `repos/{owner}/{repo}/stacks?pull_request=${prNumber}`]).stdout;
|
|
428
|
+
return JSON.parse(raw)[0]?.number;
|
|
429
|
+
}
|
|
430
|
+
pullRequestHead(reference) {
|
|
431
|
+
return this.gh([
|
|
432
|
+
"pr",
|
|
433
|
+
"view",
|
|
434
|
+
reference,
|
|
435
|
+
"--json",
|
|
436
|
+
"headRefName",
|
|
437
|
+
"--jq",
|
|
438
|
+
".headRefName"
|
|
439
|
+
]).stdout.trim();
|
|
440
|
+
}
|
|
441
|
+
checkoutPullRequest(reference) {
|
|
442
|
+
this.gh([
|
|
443
|
+
"pr",
|
|
444
|
+
"checkout",
|
|
445
|
+
reference
|
|
446
|
+
]);
|
|
447
|
+
}
|
|
448
|
+
};
|
|
449
|
+
function normalizePullRequest(pr) {
|
|
450
|
+
if (pr.state !== "OPEN" && pr.state !== "CLOSED" && pr.state !== "MERGED") throw new Error(`GitHub returned an unknown PR state: ${pr.state}`);
|
|
451
|
+
return {
|
|
452
|
+
...pr,
|
|
453
|
+
state: pr.state
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
//#endregion
|
|
457
|
+
//#region src/reporter.ts
|
|
458
|
+
var ConsoleReporter = class {
|
|
459
|
+
enabled;
|
|
460
|
+
constructor(enabled = true) {
|
|
461
|
+
this.enabled = enabled;
|
|
462
|
+
}
|
|
463
|
+
progress(message) {
|
|
464
|
+
if (this.enabled) process.stderr.write(`[bstack] ${message}\n`);
|
|
465
|
+
}
|
|
466
|
+
};
|
|
467
|
+
//#endregion
|
|
468
|
+
//#region src/state.ts
|
|
469
|
+
const emptyState = () => ({
|
|
470
|
+
schemaVersion: 1,
|
|
471
|
+
stacks: []
|
|
472
|
+
});
|
|
473
|
+
var StateStore = class {
|
|
474
|
+
path;
|
|
475
|
+
constructor(path) {
|
|
476
|
+
this.path = path;
|
|
477
|
+
}
|
|
478
|
+
read() {
|
|
479
|
+
try {
|
|
480
|
+
const parsed = JSON.parse(readFileSync(this.path, "utf8"));
|
|
481
|
+
if (!isState(parsed)) throw new Error(`Unsupported bstack state in ${this.path}`);
|
|
482
|
+
return parsed;
|
|
483
|
+
} catch (error) {
|
|
484
|
+
if (isMissingFile(error)) return emptyState();
|
|
485
|
+
throw error;
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
write(state) {
|
|
489
|
+
mkdirSync(dirname(this.path), { recursive: true });
|
|
490
|
+
const temporary = `${this.path}.tmp`;
|
|
491
|
+
writeFileSync(temporary, `${JSON.stringify(state, null, 2)}\n`);
|
|
492
|
+
renameSync(temporary, this.path);
|
|
493
|
+
}
|
|
494
|
+
findByChangeIds(state, ids) {
|
|
495
|
+
const matches = state.stacks.filter((stack) => stack.changes.some((change) => ids.has(change.id)));
|
|
496
|
+
if (matches.length > 1) throw new Error("The current commits match more than one stored bstack stack");
|
|
497
|
+
return matches[0];
|
|
498
|
+
}
|
|
499
|
+
};
|
|
500
|
+
function isMissingFile(error) {
|
|
501
|
+
return error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
502
|
+
}
|
|
503
|
+
function isState(value) {
|
|
504
|
+
if (typeof value !== "object" || value === null) return false;
|
|
505
|
+
const candidate = value;
|
|
506
|
+
return candidate.schemaVersion === 1 && Array.isArray(candidate.stacks);
|
|
507
|
+
}
|
|
508
|
+
//#endregion
|
|
509
|
+
//#region src/sync.ts
|
|
510
|
+
function syncStack(repository, github, options) {
|
|
511
|
+
const { reporter } = options;
|
|
512
|
+
reporter.progress("Checking the repository and GitHub prerequisites");
|
|
513
|
+
repository.assertReady();
|
|
514
|
+
github.assertReady();
|
|
515
|
+
const remote = repository.resolveRemote(options.remote);
|
|
516
|
+
const base = options.base ?? github.defaultBranch();
|
|
517
|
+
reporter.progress(`Using ${remote} as the remote and ${base} as the stack base`);
|
|
518
|
+
reporter.progress(`Fetching ${remote}/${base}`);
|
|
519
|
+
const remoteBase = repository.fetchBase(remote, base);
|
|
520
|
+
const baseOid = repository.mergeBase("HEAD", remoteBase);
|
|
521
|
+
const commits = repository.commitsSince(baseOid);
|
|
522
|
+
if (commits.length === 0) throw new Error(`No commits found between ${base} and HEAD`);
|
|
523
|
+
reporter.progress(`Found ${commits.length} local change${commits.length === 1 ? "" : "s"}`);
|
|
524
|
+
const rewritten = commits.some((commit) => commit.changeId === void 0);
|
|
525
|
+
if (rewritten) reporter.progress(options.dryRun ? "Stable change IDs would be added to the commits" : "Adding stable change IDs to the commits");
|
|
526
|
+
else reporter.progress("All commits already have stable change IDs");
|
|
527
|
+
const changes = repository.ensureChangeIds(commits, options.dryRun);
|
|
528
|
+
if (options.dryRun) {
|
|
529
|
+
reporter.progress("Dry run complete; no commits or remote branches were changed");
|
|
530
|
+
return {
|
|
531
|
+
base,
|
|
532
|
+
remote,
|
|
533
|
+
rewritten,
|
|
534
|
+
changes
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
reporter.progress("Reading the previous stack state");
|
|
538
|
+
const store = new StateStore(repository.statePath());
|
|
539
|
+
const state = store.read();
|
|
540
|
+
const previous = store.findByChangeIds(state, new Set(changes.map((change) => change.id)));
|
|
541
|
+
const evolution = analyzeEvolution(previous, changes, github);
|
|
542
|
+
reporter.progress(`Publishing ${changes.length} protected remote ref${changes.length === 1 ? "" : "s"}`);
|
|
543
|
+
repository.pushChanges(remote, changes);
|
|
544
|
+
reporter.progress("Looking up existing pull requests");
|
|
545
|
+
const existing = changes.map((change) => github.pullRequestForBranch(change.remoteBranch));
|
|
546
|
+
let pullRequests;
|
|
547
|
+
if (changes.length === 1) {
|
|
548
|
+
if (evolution.kind === "partial") reporter.progress("Updating this down-stack prefix while preserving higher pull requests");
|
|
549
|
+
reporter.progress(existing[0] ? "Using the existing pull request" : "Creating a pull request");
|
|
550
|
+
pullRequests = [existing[0] ?? github.createPullRequest(changes[0], base, options.open)];
|
|
551
|
+
} else {
|
|
552
|
+
if (evolution.kind === "full") {
|
|
553
|
+
reporter.progress(`Linking ${changes.length} pull requests as a native GitHub stack`);
|
|
554
|
+
github.linkStack(changes.map((change) => change.remoteBranch), base, remote, options.open);
|
|
555
|
+
} else if (evolution.kind === "append") {
|
|
556
|
+
reporter.progress(`Appending ${evolution.branches.length} pull request${evolution.branches.length === 1 ? "" : "s"} to stack #${evolution.stackNumber}`);
|
|
557
|
+
github.appendToStack(evolution.stackNumber, evolution.branches, remote, options.open);
|
|
558
|
+
} else if (evolution.kind === "partial") reporter.progress("Updating this down-stack prefix while preserving higher pull requests");
|
|
559
|
+
else reporter.progress("The native GitHub stack already has the correct members");
|
|
560
|
+
pullRequests = changes.map((change, index) => {
|
|
561
|
+
const pr = existing[index] ?? github.pullRequestForBranch(change.remoteBranch);
|
|
562
|
+
if (!pr) throw new Error(`GitHub did not return a PR for ${change.remoteBranch}`);
|
|
563
|
+
return pr;
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
reporter.progress("Synchronizing pull request titles and descriptions");
|
|
567
|
+
for (const [index, pr] of pullRequests.entries()) {
|
|
568
|
+
github.editPullRequest(pr, changes[index]);
|
|
569
|
+
reporter.progress(`PR #${pr.number}: ${changes[index].subject}`);
|
|
570
|
+
}
|
|
571
|
+
const stackNumber = previous?.stackNumber ?? (pullRequests.length > 1 ? github.stackNumberForPullRequest(pullRequests[0].number) : void 0);
|
|
572
|
+
const synchronizedChanges = changes.map((change, index) => ({
|
|
573
|
+
id: change.id,
|
|
574
|
+
remoteBranch: change.remoteBranch,
|
|
575
|
+
pullRequest: pullRequests[index].number,
|
|
576
|
+
url: pullRequests[index].url
|
|
577
|
+
}));
|
|
578
|
+
const storedChanges = evolution.kind === "partial" && previous ? [...synchronizedChanges, ...previous.changes.slice(evolution.previousOffset + changes.length)] : synchronizedChanges;
|
|
579
|
+
writeUpdatedState(store, state, previous, {
|
|
580
|
+
remote,
|
|
581
|
+
base,
|
|
582
|
+
...stackNumber === void 0 ? {} : { stackNumber },
|
|
583
|
+
changes: storedChanges
|
|
584
|
+
});
|
|
585
|
+
reporter.progress("Saved the local stack state");
|
|
586
|
+
return {
|
|
587
|
+
base,
|
|
588
|
+
remote,
|
|
589
|
+
rewritten,
|
|
590
|
+
changes: changes.map((change, index) => ({
|
|
591
|
+
...change,
|
|
592
|
+
pullRequest: pullRequests[index]
|
|
593
|
+
}))
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
function analyzeEvolution(previous, changes, github) {
|
|
597
|
+
if (!previous) return { kind: "full" };
|
|
598
|
+
const previousIds = previous.changes.map((change) => change.id);
|
|
599
|
+
const currentIds = changes.map((change) => change.id);
|
|
600
|
+
const firstCurrentIndex = previousIds.indexOf(currentIds[0]);
|
|
601
|
+
if (firstCurrentIndex === -1) throw new Error("The current commits do not continue the previously submitted stack");
|
|
602
|
+
const removedPrefix = previous.changes.slice(0, firstCurrentIndex);
|
|
603
|
+
for (const removed of removedPrefix) if (github.pullRequest(removed.pullRequest).state !== "MERGED") throw new Error("Submitted commits may only disappear from the bottom after their pull requests are merged");
|
|
604
|
+
const surviving = previousIds.slice(firstCurrentIndex);
|
|
605
|
+
const sharedLength = Math.min(surviving.length, currentIds.length);
|
|
606
|
+
for (let index = 0; index < sharedLength; index++) if (surviving[index] !== currentIds[index]) throw new Error("Reordering or removing submitted commits is not supported yet. Restore the original order before syncing");
|
|
607
|
+
if (currentIds.length < surviving.length) return {
|
|
608
|
+
kind: "partial",
|
|
609
|
+
previousOffset: firstCurrentIndex
|
|
610
|
+
};
|
|
611
|
+
const appended = changes.slice(surviving.length);
|
|
612
|
+
if (removedPrefix.length === 0) return { kind: "full" };
|
|
613
|
+
if (appended.length === 0) return { kind: "skip" };
|
|
614
|
+
if (previous.stackNumber === void 0) throw new Error("Cannot append after a merge because the native GitHub stack number is missing from local state");
|
|
615
|
+
return {
|
|
616
|
+
kind: "append",
|
|
617
|
+
stackNumber: previous.stackNumber,
|
|
618
|
+
branches: appended.map((change) => change.remoteBranch)
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
function writeUpdatedState(store, state, previous, updated) {
|
|
622
|
+
const stacks = previous ? state.stacks.map((stack) => stack === previous ? updated : stack) : [...state.stacks, updated];
|
|
623
|
+
store.write({
|
|
624
|
+
schemaVersion: 1,
|
|
625
|
+
stacks
|
|
626
|
+
});
|
|
627
|
+
}
|
|
628
|
+
//#endregion
|
|
629
|
+
//#region src/cli.ts
|
|
630
|
+
const help = `bstack - turn a linear commit series into native GitHub stacked PRs
|
|
631
|
+
|
|
632
|
+
Usage:
|
|
633
|
+
bstack [sync] [options]
|
|
634
|
+
bstack checkout <PR-number-or-URL> [options]
|
|
635
|
+
|
|
636
|
+
Options:
|
|
637
|
+
--base <branch> Stack trunk; defaults to the GitHub default branch
|
|
638
|
+
--remote <name> Git remote; defaults to remote.pushDefault or origin
|
|
639
|
+
--open Create PRs ready for review instead of drafts
|
|
640
|
+
--dry-run Inspect the stack without rewriting commits or pushing
|
|
641
|
+
--quiet Hide progress logs; the final summary is still printed
|
|
642
|
+
--same-base Refuse checkout if it would change the current merge base
|
|
643
|
+
-v, --version Show the installed version
|
|
644
|
+
-h, --help Show this help
|
|
645
|
+
`;
|
|
646
|
+
function main() {
|
|
647
|
+
const { values, positionals } = parseArgs({
|
|
648
|
+
args: process.argv.slice(2),
|
|
649
|
+
allowPositionals: true,
|
|
650
|
+
options: {
|
|
651
|
+
base: { type: "string" },
|
|
652
|
+
remote: { type: "string" },
|
|
653
|
+
open: {
|
|
654
|
+
type: "boolean",
|
|
655
|
+
default: false
|
|
656
|
+
},
|
|
657
|
+
"dry-run": {
|
|
658
|
+
type: "boolean",
|
|
659
|
+
default: false
|
|
660
|
+
},
|
|
661
|
+
quiet: {
|
|
662
|
+
type: "boolean",
|
|
663
|
+
default: false
|
|
664
|
+
},
|
|
665
|
+
"same-base": {
|
|
666
|
+
type: "boolean",
|
|
667
|
+
default: false
|
|
668
|
+
},
|
|
669
|
+
version: {
|
|
670
|
+
type: "boolean",
|
|
671
|
+
short: "v",
|
|
672
|
+
default: false
|
|
673
|
+
},
|
|
674
|
+
help: {
|
|
675
|
+
type: "boolean",
|
|
676
|
+
short: "h",
|
|
677
|
+
default: false
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
});
|
|
681
|
+
if (values.help) {
|
|
682
|
+
process.stdout.write(help);
|
|
683
|
+
return;
|
|
684
|
+
}
|
|
685
|
+
if (values.version) {
|
|
686
|
+
console.log(version);
|
|
687
|
+
return;
|
|
688
|
+
}
|
|
689
|
+
const runner = new NodeCommandRunner();
|
|
690
|
+
const cwd = process.cwd();
|
|
691
|
+
const repository = new GitRepository(cwd, runner);
|
|
692
|
+
const github = new GhPlatform(cwd, runner);
|
|
693
|
+
const reporter = new ConsoleReporter(!values.quiet);
|
|
694
|
+
const command = positionals[0] ?? "sync";
|
|
695
|
+
if (command === "checkout") {
|
|
696
|
+
const reference = positionals[1];
|
|
697
|
+
if (!reference || positionals.length > 2) throw new Error(`Usage: bstack checkout <PR-number-or-URL> [options]`);
|
|
698
|
+
const result = checkoutStack(repository, github, {
|
|
699
|
+
reference,
|
|
700
|
+
base: values.base,
|
|
701
|
+
remote: values.remote,
|
|
702
|
+
sameBase: values["same-base"],
|
|
703
|
+
reporter
|
|
704
|
+
});
|
|
705
|
+
console.log(result.delegated ? `Checked out pull request ${reference}` : `Checked out ${result.headRef} from pull request ${reference}`);
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
if (command !== "sync" || positionals.length > 1) throw new Error(`Unknown command: ${positionals.join(" ")}\n\n${help}`);
|
|
709
|
+
const result = syncStack(repository, github, {
|
|
710
|
+
base: values.base,
|
|
711
|
+
remote: values.remote,
|
|
712
|
+
open: values.open,
|
|
713
|
+
dryRun: values["dry-run"],
|
|
714
|
+
reporter
|
|
715
|
+
});
|
|
716
|
+
console.log(`${values["dry-run"] ? "Would publish" : "Published"} ${result.changes.length} change${result.changes.length === 1 ? "" : "s"} against ${result.base}:`);
|
|
717
|
+
for (const change of result.changes) {
|
|
718
|
+
const destination = change.pullRequest ? ` ${change.pullRequest.url}` : "";
|
|
719
|
+
console.log(` ${change.oid.slice(0, 8)} ${change.subject}${destination}`);
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
try {
|
|
723
|
+
main();
|
|
724
|
+
} catch (error) {
|
|
725
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
726
|
+
console.error(`bstack: ${message}`);
|
|
727
|
+
process.exitCode = 1;
|
|
728
|
+
}
|
|
729
|
+
//#endregion
|
|
730
|
+
export {};
|