@bridgebrew/project 0.0.1 → 0.0.2
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/branches.ts +1220 -0
- package/browser/branches.tsx +124 -8
- package/browser/overview.tsx +3 -2
- package/package.json +10 -3
- package/server.ts +85 -1
package/branches.ts
ADDED
|
@@ -0,0 +1,1220 @@
|
|
|
1
|
+
// A project's branches (research-083, bridgebrew/bridge#557), in the project plugin: the branches of a git project,
|
|
2
|
+
// each with its git worktree under the project's folder (`<project>/.worktrees/<name>`, kept out of git), where the
|
|
3
|
+
// sessions on that branch work. The Branches screen (./browser/branches.tsx) lists them and acts on them through this
|
|
4
|
+
// plugin's routes (`/branches…`, never an agent's: `agent: false`); Sessions makes a session's branch through the
|
|
5
|
+
// `projectBranches` service. git runs through the host's processes (AD-27); what Bridge loads from the project's
|
|
6
|
+
// folders, and switching it (Activate), stay the host's (`bridgeNodes.codeFrom`, `follow`), as does a branch's install
|
|
7
|
+
// (`bridgeNodes.install`, Bridge's own pnpm). Pull requests go through the optional `github` service: without it, every
|
|
8
|
+
// git action works and Create PR is refused, saying so.
|
|
9
|
+
// - New: a branch from the project's default branch, its worktree, its dependencies.
|
|
10
|
+
// - Its end: commit, push, a draft pull request, each alone too, their texts written by a model (Sessions' `POST
|
|
11
|
+
// /sessions/write`) unless the user wrote them; then it may be deleted, refused while it holds work that is not pushed
|
|
12
|
+
// (or whose push state git cannot tell), a repository of its own in an ignored folder (bridge#523), or while
|
|
13
|
+
// anything uses it in Bridge (`codeFrom`): a plugin of any place, a stage's choice, host-level code, a session.
|
|
14
|
+
// - New, Push, Pull, Create PR and Activate may outlast a route's deadline: each runs as this worker's job, its route
|
|
15
|
+
// waiting for it `waitMs` at most, then answering that it runs on; the listing says what runs and how the last one
|
|
16
|
+
// ended, by branch (owner decision, bridge#557).
|
|
17
|
+
// A branch is known by git (`git worktree list`): its folder's name is only made safe, never read back as its name.
|
|
18
|
+
import { randomUUID } from 'node:crypto';
|
|
19
|
+
import {
|
|
20
|
+
existsSync,
|
|
21
|
+
lstatSync,
|
|
22
|
+
mkdirSync,
|
|
23
|
+
readdirSync,
|
|
24
|
+
readFileSync,
|
|
25
|
+
realpathSync,
|
|
26
|
+
renameSync,
|
|
27
|
+
rmSync,
|
|
28
|
+
writeFileSync,
|
|
29
|
+
} from 'node:fs';
|
|
30
|
+
import { open, readdir } from 'node:fs/promises';
|
|
31
|
+
import { tmpdir } from 'node:os';
|
|
32
|
+
import { basename, dirname, join, relative, resolve, sep } from 'node:path';
|
|
33
|
+
import type { Context } from 'cordis';
|
|
34
|
+
import { isRecord } from '@bridge/kernel/json';
|
|
35
|
+
import { cutText } from '@bridge/kernel/text';
|
|
36
|
+
|
|
37
|
+
/** What a git run gave: its exit code (null when killed), its output, and whether it was cut at its byte cap. */
|
|
38
|
+
export interface Ran {
|
|
39
|
+
code: number | null;
|
|
40
|
+
stdout: string;
|
|
41
|
+
stderr: string;
|
|
42
|
+
cut?: boolean;
|
|
43
|
+
}
|
|
44
|
+
/** Runs git with `args` in `cwd`. `remote`: it reaches the project's remote (ssh in batch mode); `deadlineMs`: killed
|
|
45
|
+
* past it (a failure); `maxBytes`: its output kept up to that many bytes, then killed (`cut`). Never writes stdin: the
|
|
46
|
+
* host's process keeps it open, so git must never read it. */
|
|
47
|
+
export type Git = (
|
|
48
|
+
cwd: string,
|
|
49
|
+
args: string[],
|
|
50
|
+
options?: { remote?: boolean; deadlineMs?: number; maxBytes?: number },
|
|
51
|
+
) => Promise<Ran>;
|
|
52
|
+
|
|
53
|
+
/** No terminal prompt, no credential helper popping a window, git's messages in English (they are read), no index
|
|
54
|
+
* rewritten by a read (`GIT_OPTIONAL_LOCKS`, bridge#522). */
|
|
55
|
+
const QUIET = {
|
|
56
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
57
|
+
GIT_ASKPASS: '',
|
|
58
|
+
SSH_ASKPASS: '',
|
|
59
|
+
LANGUAGE: 'C',
|
|
60
|
+
LC_MESSAGES: 'C',
|
|
61
|
+
GIT_OPTIONAL_LOCKS: '0',
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
/** `Git` through the host's processes, owned by `owner` (killed with it). A remote run appends `-o BatchMode=yes` to
|
|
65
|
+
* the ssh command git would run: the user's `GIT_SSH_COMMAND`, else `core.sshCommand`, else `ssh`; nothing when only
|
|
66
|
+
* `GIT_SSH` names one (bridge#495). */
|
|
67
|
+
export const processGit = (owner: Context): Git => {
|
|
68
|
+
const spawn = async (
|
|
69
|
+
cwd: string,
|
|
70
|
+
args: string[],
|
|
71
|
+
{
|
|
72
|
+
deadlineMs,
|
|
73
|
+
maxBytes,
|
|
74
|
+
env = {},
|
|
75
|
+
}: { deadlineMs?: number | undefined; maxBytes?: number | undefined; env?: Record<string, string> } = {},
|
|
76
|
+
): Promise<Ran> => {
|
|
77
|
+
// Never more than `MAX_OUTPUT` of a git's output in memory, stdout and stderr together (16 MB, as the host's was).
|
|
78
|
+
maxBytes ??= MAX_OUTPUT;
|
|
79
|
+
const child = await owner.processes.spawn(owner, { command: 'git', args, cwd, env: { ...QUIET, ...env } });
|
|
80
|
+
let stdout = '';
|
|
81
|
+
let stderr = '';
|
|
82
|
+
let bytes = 0;
|
|
83
|
+
let cut = false;
|
|
84
|
+
let late = false;
|
|
85
|
+
child.onOutput((stream, chunk) => {
|
|
86
|
+
if (cut) return;
|
|
87
|
+
bytes += Buffer.byteLength(chunk);
|
|
88
|
+
if (bytes > maxBytes) {
|
|
89
|
+
cut = true;
|
|
90
|
+
void child.kill();
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
if (stream === 'stdout') stdout += chunk;
|
|
94
|
+
else stderr += chunk;
|
|
95
|
+
});
|
|
96
|
+
const timer =
|
|
97
|
+
deadlineMs === undefined
|
|
98
|
+
? undefined
|
|
99
|
+
: setTimeout(() => {
|
|
100
|
+
late = true;
|
|
101
|
+
void child.kill();
|
|
102
|
+
}, deadlineMs);
|
|
103
|
+
try {
|
|
104
|
+
const { code } = await child.exited;
|
|
105
|
+
if (late) return { code: null, stdout, stderr: `git ${args[0]} did not end within ${deadlineMs! / 1000} s` };
|
|
106
|
+
return cut ? { code, stdout, stderr, cut } : { code, stdout, stderr };
|
|
107
|
+
} finally {
|
|
108
|
+
clearTimeout(timer);
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
return async (cwd, args, { remote = false, ...options } = {}) => {
|
|
112
|
+
if (!remote) return spawn(cwd, args, options);
|
|
113
|
+
const configured = (await spawn(cwd, ['config', '--get', 'core.sshCommand'])).stdout.trim();
|
|
114
|
+
const own = process.env.GIT_SSH_COMMAND || configured || (process.env.GIT_SSH ? undefined : 'ssh');
|
|
115
|
+
return spawn(cwd, args, { ...options, ...(own ? { env: { GIT_SSH_COMMAND: `${own} -o BatchMode=yes` } } : {}) });
|
|
116
|
+
};
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
/** What the host says Bridge loads from a repository (`bridgeNodes.codeFrom`). */
|
|
120
|
+
export interface CodeFrom {
|
|
121
|
+
checkout: boolean;
|
|
122
|
+
stage: boolean;
|
|
123
|
+
kit?: { path: string } | undefined;
|
|
124
|
+
uiError?: string | undefined;
|
|
125
|
+
plugins: { workspace: string; plugin: string; path: string }[];
|
|
126
|
+
chosen: { stage: string; folder: string }[];
|
|
127
|
+
sessions?: { workspace: string; session: string; folder: string }[] | undefined;
|
|
128
|
+
}
|
|
129
|
+
/** What Activate did (`bridgeNodes.follow`). */
|
|
130
|
+
export interface Activated {
|
|
131
|
+
followed: { workspace?: string | undefined; plugin: string; folder: string }[];
|
|
132
|
+
left: { workspace?: string | undefined; plugin: string; reason: string }[];
|
|
133
|
+
}
|
|
134
|
+
/** A pull request as `github` lists it, the part read here. */
|
|
135
|
+
interface FoundPr {
|
|
136
|
+
url: string;
|
|
137
|
+
state: PrState;
|
|
138
|
+
}
|
|
139
|
+
/** The part of the `github` service used here (bridge-plugins' `@bridgebrew/github`, never imported). */
|
|
140
|
+
export interface GitHubLike {
|
|
141
|
+
repositoryOfFolder(folder: string, signal?: AbortSignal): Promise<string | undefined>;
|
|
142
|
+
pullRequestsForBranch(request: { repository: string; branch: string }): Promise<{ url: string; state: PrState }[]>;
|
|
143
|
+
rest(request: { method?: 'POST'; path: string; body?: unknown }): Promise<{ body?: unknown }>;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** What the branches need from their plugin and the host: one place to fake in a test. */
|
|
147
|
+
export interface BranchesHost {
|
|
148
|
+
/** The workspace this worker runs (`ctx.workspace.slug`). */
|
|
149
|
+
slug: string;
|
|
150
|
+
/** Where this plugin keeps its records (the pull requests it made or found). */
|
|
151
|
+
dataDir: string;
|
|
152
|
+
git: Git;
|
|
153
|
+
/** The workspace's projects as its `bridge.yml` files list them (`bridgeNodes.projects`). */
|
|
154
|
+
projects(): Promise<{ project: string; node?: string | undefined; folder: string; title: string }[]>;
|
|
155
|
+
codeFrom(input: { repository: string; sessions?: boolean }): Promise<CodeFrom>;
|
|
156
|
+
follow(input: { repository: string; target: string }): Promise<Activated>;
|
|
157
|
+
install(folder: string): Promise<void>;
|
|
158
|
+
/** Removes branch folder `folder` of the repository at `repository` (`git worktree remove`, never forced) once the
|
|
159
|
+
* host found nothing in Bridge using it, in one turn with Activate (`bridgeNodes.removeWorktree`); refused, naming
|
|
160
|
+
* what uses it, or with git's refusal. */
|
|
161
|
+
removeWorktree(input: { repository: string; folder: string }): Promise<void>;
|
|
162
|
+
pluginsRepository(plugins: string[]): Promise<string>;
|
|
163
|
+
/** A text a model writes once for project `node` (Sessions' `POST /sessions/write`), the conversations of `sessions`
|
|
164
|
+
* given with `prompt`; throws when it cannot. */
|
|
165
|
+
write(node: string, prompt: string, sessions: string[]): Promise<string>;
|
|
166
|
+
/** The `github` service when the workspace runs it. */
|
|
167
|
+
github(): GitHubLike | undefined;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export type PrState = 'open' | 'draft' | 'merged' | 'closed';
|
|
171
|
+
|
|
172
|
+
/** A branch, as the screen lists it. `main` is the project's own folder. */
|
|
173
|
+
export interface Branch {
|
|
174
|
+
name: string;
|
|
175
|
+
folder: string;
|
|
176
|
+
main: boolean;
|
|
177
|
+
dirty: number;
|
|
178
|
+
diff: Diff;
|
|
179
|
+
ahead: number;
|
|
180
|
+
behindDefault: number;
|
|
181
|
+
unpushed: number;
|
|
182
|
+
behind: number;
|
|
183
|
+
upstream: boolean;
|
|
184
|
+
remote: boolean;
|
|
185
|
+
isDefault: boolean;
|
|
186
|
+
prOpen: boolean;
|
|
187
|
+
prState?: PrState;
|
|
188
|
+
prNumber?: number;
|
|
189
|
+
unknown?: boolean;
|
|
190
|
+
active: boolean;
|
|
191
|
+
pr?: string;
|
|
192
|
+
/** The action its row shows: one running, else the last that ended (`jobs`). */
|
|
193
|
+
job?: Job;
|
|
194
|
+
/** Its recent actions, oldest first, each by its id: the Git button finds its own there. */
|
|
195
|
+
jobs?: Job[];
|
|
196
|
+
}
|
|
197
|
+
/** An action that may outlast its route (New, Push, Pull, Create PR, Activate): running, or ended with its result or
|
|
198
|
+
* its error. */
|
|
199
|
+
export interface Job {
|
|
200
|
+
/** Names this run: the Git button waits for its own (`{ result: { running, job } }`). */
|
|
201
|
+
id: string;
|
|
202
|
+
action: string;
|
|
203
|
+
running: boolean;
|
|
204
|
+
error?: string;
|
|
205
|
+
result?: Record<string, unknown>;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Files changed and their lines added and deleted. */
|
|
209
|
+
export interface Diff {
|
|
210
|
+
files: number;
|
|
211
|
+
additions: number;
|
|
212
|
+
deletions: number;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** `path` itself or a path inside `folder`. */
|
|
216
|
+
const within = (path: string, folder: string) => path === folder || path.startsWith(folder + sep);
|
|
217
|
+
/** `path` as git records it (real), as it is when it does not exist. */
|
|
218
|
+
const real = (path: string) => {
|
|
219
|
+
try {
|
|
220
|
+
return realpathSync(path);
|
|
221
|
+
} catch {
|
|
222
|
+
return path;
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
const reason = (error: unknown) => (error instanceof Error ? error.message : String(error));
|
|
226
|
+
|
|
227
|
+
/** A branch name as a folder name: safe, never read back (`feat/x` and `feat-x` both give `feat-x`, the second one
|
|
228
|
+
* numbered). */
|
|
229
|
+
const folderName = (name: string) => name.replaceAll('/', '-');
|
|
230
|
+
/** A branch name from a title: its letters without their accents (`Café crème` is `cafe-creme`, bridge#552), lowercase,
|
|
231
|
+
* joined by `-`. */
|
|
232
|
+
export const branchName = (title: string) =>
|
|
233
|
+
title
|
|
234
|
+
.toLowerCase()
|
|
235
|
+
.normalize('NFKD')
|
|
236
|
+
.replace(/[\u0300-\u036f]/g, '')
|
|
237
|
+
.replace(/[^a-z0-9/]+/g, '-')
|
|
238
|
+
.replace(/^-+|-+$/g, '')
|
|
239
|
+
.slice(0, 50);
|
|
240
|
+
|
|
241
|
+
/** A log and a diff as git makes them, read by Bridge or a model, whatever the user's config. */
|
|
242
|
+
const plainLog = ['log', '--no-show-signature'];
|
|
243
|
+
const plainDiff = ['diff', '--no-ext-diff', '--no-textconv', '--no-color'];
|
|
244
|
+
/** How much of a diff a model is given, and how much of git's output is read to cut it there (bridge#597). */
|
|
245
|
+
const DIFF_CHARS = 60_000;
|
|
246
|
+
const DIFF_BYTES = 1024 * 1024;
|
|
247
|
+
/** The most of a git's output kept in memory, unless a run asks for less. */
|
|
248
|
+
const MAX_OUTPUT = 16 * 1024 * 1024;
|
|
249
|
+
/** How much of a new file is read to count its lines. */
|
|
250
|
+
const READ_CAP = 1024 * 1024;
|
|
251
|
+
|
|
252
|
+
/** The claim `newBranch` takes on a branch's folder in `.worktrees/` before it makes the branch (created exclusively,
|
|
253
|
+
* so two creators never share a folder), removed once made or undone (bridge#326). Workers are threads of the host's
|
|
254
|
+
* process, so a claim names its worker (`worker`: `<workspace>:<start id>`) beside the host's pid. A claim is
|
|
255
|
+
* unfinished when its own undo kept it, when the host that made it is gone (its pid), when it is an older worker's
|
|
256
|
+
* of this workspace (a worker restarted, or `project` reloaded), or this worker's own no longer being made. Only
|
|
257
|
+
* Delete removes an unfinished one, once its worktree is gone; nobody else rewrites or removes another's claim. */
|
|
258
|
+
interface Making {
|
|
259
|
+
pid: number;
|
|
260
|
+
worker: string;
|
|
261
|
+
name: string;
|
|
262
|
+
folder: string;
|
|
263
|
+
head: string;
|
|
264
|
+
made: boolean;
|
|
265
|
+
added: boolean;
|
|
266
|
+
kept?: true;
|
|
267
|
+
}
|
|
268
|
+
const makingFile = (folder: string) => join(dirname(folder), `.${basename(folder)}.making`);
|
|
269
|
+
const alive = (pid: number) => {
|
|
270
|
+
try {
|
|
271
|
+
process.kill(pid, 0);
|
|
272
|
+
return true;
|
|
273
|
+
} catch (error) {
|
|
274
|
+
return isRecord(error) && error.code === 'EPERM';
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
const claimText = (file: string) => {
|
|
278
|
+
try {
|
|
279
|
+
return readFileSync(file, 'utf8');
|
|
280
|
+
} catch {
|
|
281
|
+
return undefined;
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
const shellQuoted = (text: string) => `'${text.replaceAll("'", `'\\''`)}'`;
|
|
285
|
+
/** Written aside, then renamed in place: never half a file. */
|
|
286
|
+
const writeAtomic = (file: string, text: string) => {
|
|
287
|
+
const aside = `${file}.${process.pid}.${randomUUID()}.tmp`;
|
|
288
|
+
writeFileSync(aside, text);
|
|
289
|
+
renameSync(aside, file);
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
export interface Settings {
|
|
293
|
+
/** How long a route waits for its job before answering that it runs on (below the route's deadline). */
|
|
294
|
+
waitMs?: number;
|
|
295
|
+
/** The listing's fetch deadline. */
|
|
296
|
+
fetchDeadlineMs?: number;
|
|
297
|
+
/** A remote run's deadline (push, pull, a branch's fetch). */
|
|
298
|
+
remoteDeadlineMs?: number;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** The branches of host's workspace's projects. */
|
|
302
|
+
export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
303
|
+
const { waitMs = 100_000, fetchDeadlineMs = 30_000, remoteDeadlineMs = 120_000 } = settings;
|
|
304
|
+
// Its host's process (a worker is a thread of it), its workspace, this start: two Bridges sharing a repository, each
|
|
305
|
+
// with a workspace of that name, never take each other's claims for an older worker's.
|
|
306
|
+
const worker = `${process.pid}:${host.slug}:${randomUUID()}`;
|
|
307
|
+
/** The claims this worker is making now, by file. */
|
|
308
|
+
const making = new Set<string>();
|
|
309
|
+
|
|
310
|
+
/** git's stdout, trimmed; refused with what it said. */
|
|
311
|
+
const git = async (cwd: string, args: string[]) => {
|
|
312
|
+
const ran = await host.git(cwd, args);
|
|
313
|
+
if (ran.cut) throw new Error(`git ${args[0]} printed more than Bridge reads`);
|
|
314
|
+
if (ran.code !== 0) throw new Error(ran.stderr.trim() || `git ${args[0]} failed`);
|
|
315
|
+
return ran.stdout.trim();
|
|
316
|
+
};
|
|
317
|
+
const remoteGit = async (cwd: string, args: string[], deadlineMs = remoteDeadlineMs) => {
|
|
318
|
+
const ran = await host.git(cwd, args, { remote: true, deadlineMs });
|
|
319
|
+
if (ran.code !== 0) throw new Error(ran.stderr.trim() || `git ${args[0]} failed`);
|
|
320
|
+
return ran.stdout.trim();
|
|
321
|
+
};
|
|
322
|
+
const resolves = (folder: string, ref: string) =>
|
|
323
|
+
host.git(folder, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]).then(({ code }) => code === 0);
|
|
324
|
+
|
|
325
|
+
/** The claim `text` when it marks an unfinished branch. */
|
|
326
|
+
const unfinished = (text: string | undefined, file: string) => {
|
|
327
|
+
let read: unknown;
|
|
328
|
+
try {
|
|
329
|
+
read = JSON.parse(text ?? '');
|
|
330
|
+
} catch {
|
|
331
|
+
return undefined;
|
|
332
|
+
}
|
|
333
|
+
if (
|
|
334
|
+
!isRecord(read) ||
|
|
335
|
+
typeof read.pid !== 'number' ||
|
|
336
|
+
typeof read.name !== 'string' ||
|
|
337
|
+
typeof read.folder !== 'string'
|
|
338
|
+
)
|
|
339
|
+
return undefined;
|
|
340
|
+
const owner = typeof read.worker === 'string' ? read.worker : undefined;
|
|
341
|
+
const gone =
|
|
342
|
+
read.kept === true ||
|
|
343
|
+
!alive(read.pid) ||
|
|
344
|
+
(owner === worker && !making.has(file)) ||
|
|
345
|
+
(owner !== undefined && owner !== worker && owner.startsWith(`${process.pid}:${host.slug}:`));
|
|
346
|
+
if (!gone) return undefined;
|
|
347
|
+
return {
|
|
348
|
+
name: read.name,
|
|
349
|
+
folder: read.folder,
|
|
350
|
+
head: typeof read.head === 'string' ? read.head : '',
|
|
351
|
+
made: read.made === true,
|
|
352
|
+
};
|
|
353
|
+
};
|
|
354
|
+
|
|
355
|
+
/** The repository's branches that have a folder (`git worktree list`): its own checkout first (main), then each
|
|
356
|
+
* worktree under `.worktrees/`; a detached one named `(detached)`, marked. Read only. */
|
|
357
|
+
const worktreesOf = async (folder: string) => {
|
|
358
|
+
const porcelain = await git(folder, ['worktree', 'list', '--porcelain']);
|
|
359
|
+
const all = porcelain.split('\n\n').flatMap((block) => {
|
|
360
|
+
const path = /^worktree (.+)$/m.exec(block)?.[1];
|
|
361
|
+
const named = /^branch refs\/heads\/(.+)$/m.exec(block)?.[1];
|
|
362
|
+
return path
|
|
363
|
+
? [{ name: named ?? '(detached)', folder: path, ...(named === undefined && { detached: true as const }) }]
|
|
364
|
+
: [];
|
|
365
|
+
});
|
|
366
|
+
const main = all[0]?.folder ?? real(folder);
|
|
367
|
+
return all
|
|
368
|
+
.filter((each) => each.folder === main || within(each.folder, join(main, '.worktrees')))
|
|
369
|
+
.map((each) => ({ ...each, main: each.folder === main }));
|
|
370
|
+
};
|
|
371
|
+
type Worktree = Awaited<ReturnType<typeof worktreesOf>>[number];
|
|
372
|
+
const holder = <T extends { folder: string }>(branches: T[], path: string) =>
|
|
373
|
+
branches.filter((each) => within(path, each.folder)).sort((a, b) => b.folder.length - a.folder.length)[0];
|
|
374
|
+
|
|
375
|
+
/** The remote git works with from `folder` (bridge#522): its branch's upstream's, else the only one, else `origin`;
|
|
376
|
+
* `undefined` when that remote does not exist. */
|
|
377
|
+
const remoteOf = async (folder: string) => {
|
|
378
|
+
const branch = await git(folder, ['symbolic-ref', '--quiet', '--short', 'HEAD']).catch(() => '');
|
|
379
|
+
const tracked = branch && (await git(folder, ['config', '--get', `branch.${branch}.remote`]).catch(() => ''));
|
|
380
|
+
const names = (await git(folder, ['remote']).catch(() => '')).split('\n').filter(Boolean);
|
|
381
|
+
const name = tracked && names.includes(tracked) ? tracked : names.length === 1 ? names[0] : 'origin';
|
|
382
|
+
return name !== undefined && names.includes(name) ? name : undefined;
|
|
383
|
+
};
|
|
384
|
+
/** The project's default branch on `remote` (`<remote>/HEAD`) when the branch it names exists (bridge#540), read as a
|
|
385
|
+
* full ref so a local branch or a tag of the same name never shadows it (bridge#595), else the branch its own
|
|
386
|
+
* checkout is on, else `main`. */
|
|
387
|
+
const defaultBranch = async (folder: string, remote: string | undefined) => {
|
|
388
|
+
const head = `refs/remotes/${remote}/HEAD`;
|
|
389
|
+
const named =
|
|
390
|
+
remote && (await resolves(folder, head)) ? await git(folder, ['symbolic-ref', head]).catch(() => '') : '';
|
|
391
|
+
const prefix = `refs/remotes/${remote}/`;
|
|
392
|
+
const current = await git(folder, ['symbolic-ref', '--quiet', 'HEAD']).catch(() => '');
|
|
393
|
+
return (
|
|
394
|
+
(named.startsWith(prefix) ? named.slice(prefix.length) : '') ||
|
|
395
|
+
(current.startsWith('refs/heads/') ? current.slice('refs/heads/'.length) : '') ||
|
|
396
|
+
'main'
|
|
397
|
+
);
|
|
398
|
+
};
|
|
399
|
+
/** What a branch's commits are compared with: the default branch on the remote, or its local one without one. */
|
|
400
|
+
const baseOf = async (folder: string) => {
|
|
401
|
+
const remote = await remoteOf(folder);
|
|
402
|
+
const name = await defaultBranch(folder, remote);
|
|
403
|
+
return { remote, name, ref: remote ? `refs/remotes/${remote}/${name}` : `refs/heads/${name}` };
|
|
404
|
+
};
|
|
405
|
+
type Base = Awaited<ReturnType<typeof baseOf>>;
|
|
406
|
+
const count = async (path: string, range: string) => Number(await git(path, ['rev-list', '--count', range]));
|
|
407
|
+
|
|
408
|
+
/** When each project's remote was last fetched. */
|
|
409
|
+
const fetched = new Map<string, number>();
|
|
410
|
+
/** Fetches the project's remote at most once a minute, without git's automatic maintenance in the user's
|
|
411
|
+
* repository (bridge#596); a failure is ignored. */
|
|
412
|
+
/** The remote reads under way (a fetch, a GitHub lookup), by what they read: a listing never waits for them, it says
|
|
413
|
+
* they run (`refreshing`) and the next one shows what they read. */
|
|
414
|
+
const reading = new Map<string, Set<string>>();
|
|
415
|
+
/** How many background reads ended, by project (its own folder): a listing they ended during says so too. */
|
|
416
|
+
const ended = new Map<string, number>();
|
|
417
|
+
/** Runs `read` in the background for project `main` as `key`, once at a time. */
|
|
418
|
+
const behind = (main: string, key: string, read: () => Promise<unknown>) => {
|
|
419
|
+
const own = reading.get(main) ?? new Set<string>();
|
|
420
|
+
if (own.has(key)) return;
|
|
421
|
+
own.add(key);
|
|
422
|
+
reading.set(main, own);
|
|
423
|
+
void read()
|
|
424
|
+
.catch(() => undefined)
|
|
425
|
+
.finally(() => {
|
|
426
|
+
own.delete(key);
|
|
427
|
+
ended.set(main, (ended.get(main) ?? 0) + 1);
|
|
428
|
+
});
|
|
429
|
+
};
|
|
430
|
+
const fetchRemote = (main: string, folder: string, remote: string) => {
|
|
431
|
+
// ponytail: one fetch a minute per project, a background poll if a fresher Pull matters.
|
|
432
|
+
if (Date.now() - (fetched.get(folder) ?? 0) < 60_000) return;
|
|
433
|
+
fetched.set(folder, Date.now());
|
|
434
|
+
behind(main, `fetch`, () =>
|
|
435
|
+
remoteGit(
|
|
436
|
+
folder,
|
|
437
|
+
['-c', 'maintenance.auto=false', '-c', 'gc.auto=0', 'fetch', '--quiet', '--no-auto-maintenance', remote],
|
|
438
|
+
fetchDeadlineMs,
|
|
439
|
+
),
|
|
440
|
+
);
|
|
441
|
+
};
|
|
442
|
+
|
|
443
|
+
// --- Pull requests: the ones Bridge made or found, by worktree folder (a renamed or detached branch keeps its own)
|
|
444
|
+
const recordsFile = join(host.dataDir, 'pull-requests.json');
|
|
445
|
+
const readRecords = (): Record<string, { url: string; state: PrState }> => {
|
|
446
|
+
try {
|
|
447
|
+
const value: unknown = JSON.parse(readFileSync(recordsFile, 'utf8'));
|
|
448
|
+
if (!isRecord(value)) return {};
|
|
449
|
+
return Object.fromEntries(
|
|
450
|
+
Object.entries(value).flatMap(([folder, each]) =>
|
|
451
|
+
isRecord(each) && typeof each.url === 'string' && typeof each.state === 'string'
|
|
452
|
+
? [[folder, { url: each.url, state: each.state as PrState }]]
|
|
453
|
+
: [],
|
|
454
|
+
),
|
|
455
|
+
);
|
|
456
|
+
} catch {
|
|
457
|
+
return {};
|
|
458
|
+
}
|
|
459
|
+
};
|
|
460
|
+
/** Records branch folder `folder`'s pull request and its state as last read (none: forgotten). */
|
|
461
|
+
const record = (folder: string, pr: { url: string; state: PrState } | undefined) => {
|
|
462
|
+
const records = readRecords();
|
|
463
|
+
if (records[folder]?.url === pr?.url && records[folder]?.state === pr?.state) return;
|
|
464
|
+
if (pr === undefined) delete records[folder];
|
|
465
|
+
else records[folder] = pr;
|
|
466
|
+
mkdirSync(host.dataDir, { recursive: true });
|
|
467
|
+
writeAtomic(recordsFile, JSON.stringify(records, null, 2));
|
|
468
|
+
};
|
|
469
|
+
/** Each project's GitHub repository (gh resolves its remotes), asked at most every 5 minutes. */
|
|
470
|
+
const repositories = new Map<string, { at: number; repository: string | undefined }>();
|
|
471
|
+
/** The project's GitHub repository as last read, a read started when it is older than 5 minutes. */
|
|
472
|
+
const repositoryOf = (github: GitHubLike, main: string) => {
|
|
473
|
+
const known = repositories.get(main);
|
|
474
|
+
if (!known || Date.now() - known.at >= 300_000)
|
|
475
|
+
behind(main, 'repository', async () => {
|
|
476
|
+
const started = Date.now();
|
|
477
|
+
// A read that failed counts as made: the next one waits its turn, never at each listing.
|
|
478
|
+
const repository = await github.repositoryOfFolder(main).catch(() => known?.repository);
|
|
479
|
+
// Never over what was read since it started (Create PR's own read).
|
|
480
|
+
if ((repositories.get(main)?.at ?? 0) <= started) repositories.set(main, { at: Date.now(), repository });
|
|
481
|
+
});
|
|
482
|
+
return known?.repository;
|
|
483
|
+
};
|
|
484
|
+
|
|
485
|
+
/** Each branch's pull requests by repository and name, asked at most every 30 s. */
|
|
486
|
+
const found = new Map<string, { at: number; prs: FoundPr[] }>();
|
|
487
|
+
/** A branch's pull requests as last read, a read started when they are older than 30 s. */
|
|
488
|
+
const prsOf = (github: GitHubLike, main: string, repository: string, branch: string) => {
|
|
489
|
+
const key = `${repository}\0${branch}`;
|
|
490
|
+
const known = found.get(key);
|
|
491
|
+
if (!known || Date.now() - known.at >= 30_000)
|
|
492
|
+
behind(main, `prs\0${branch}`, async () => {
|
|
493
|
+
const started = Date.now();
|
|
494
|
+
const prs = await github.pullRequestsForBranch({ repository, branch }).catch(() => known?.prs ?? []);
|
|
495
|
+
// Never over what was read since it started: Create PR's pull request stays, an older answer is dropped.
|
|
496
|
+
if ((found.get(key)?.at ?? 0) <= started) found.set(key, { at: Date.now(), prs });
|
|
497
|
+
});
|
|
498
|
+
return known?.prs ?? [];
|
|
499
|
+
};
|
|
500
|
+
|
|
501
|
+
const prNumberOf = (url: string) => {
|
|
502
|
+
const number = /\/pull\/(\d+)/.exec(url)?.[1];
|
|
503
|
+
return number ? Number(number) : undefined;
|
|
504
|
+
};
|
|
505
|
+
|
|
506
|
+
/** What a branch's folder changed and did not commit, as GitHub's diffstat counts it (bridge.yml aside); `git
|
|
507
|
+
* diff-index`, which writes no index (bridge#522). */
|
|
508
|
+
const diffOf = async (folder: string): Promise<Diff> => {
|
|
509
|
+
const diff = { files: 0, additions: 0, deletions: 0 };
|
|
510
|
+
const tracked = await git(folder, ['diff-index', '--numstat', '--no-renames', 'HEAD', '--', '.', ':!bridge.yml']);
|
|
511
|
+
for (const line of tracked ? tracked.split('\n') : []) {
|
|
512
|
+
const [added = '', deleted = ''] = line.split('\t');
|
|
513
|
+
diff.files++;
|
|
514
|
+
diff.additions += Number(added) || 0;
|
|
515
|
+
diff.deletions += Number(deleted) || 0;
|
|
516
|
+
}
|
|
517
|
+
const untracked = await git(folder, [
|
|
518
|
+
'ls-files',
|
|
519
|
+
'--others',
|
|
520
|
+
'--exclude-standard',
|
|
521
|
+
'-z',
|
|
522
|
+
'--',
|
|
523
|
+
'.',
|
|
524
|
+
':!bridge.yml',
|
|
525
|
+
]);
|
|
526
|
+
for (const path of untracked.split('\0').filter(Boolean)) {
|
|
527
|
+
diff.files++;
|
|
528
|
+
diff.additions += await newLines(join(folder, path));
|
|
529
|
+
}
|
|
530
|
+
return diff;
|
|
531
|
+
};
|
|
532
|
+
/** Whether the branch in `path` is in the middle of a merge: its `MERGE_HEAD`, read where git keeps it. */
|
|
533
|
+
const merging = (path: string) => resolves(path, 'MERGE_HEAD');
|
|
534
|
+
/** The upstream of branch `name`, else `''`; the default branch's remote ref is no upstream of another branch. */
|
|
535
|
+
const upstreamOf = async (path: string, name: string, base: Base) => {
|
|
536
|
+
const upstream = await git(path, ['rev-parse', '--symbolic-full-name', '@{upstream}']).catch(() => '');
|
|
537
|
+
return upstream === base.ref && name !== base.name ? '' : upstream;
|
|
538
|
+
};
|
|
539
|
+
/** The commits no remote has; throws when git cannot tell. */
|
|
540
|
+
const unpushedOf = async (path: string, name: string, base: Base) => {
|
|
541
|
+
if (!base.remote) return count(path, `${base.ref}..HEAD`);
|
|
542
|
+
const upstream = await upstreamOf(path, name, base);
|
|
543
|
+
return count(path, upstream ? '@{upstream}..HEAD' : `${base.ref}..HEAD`);
|
|
544
|
+
};
|
|
545
|
+
|
|
546
|
+
/** The recent jobs of each project (by its own folder), by branch name (a new one by its title), oldest first. */
|
|
547
|
+
const jobs = new Map<string, Map<string, Job[]>>();
|
|
548
|
+
const jobsOf = (main: string) => {
|
|
549
|
+
let each = jobs.get(main);
|
|
550
|
+
if (!each) jobs.set(main, (each = new Map<string, Job[]>()));
|
|
551
|
+
return each;
|
|
552
|
+
};
|
|
553
|
+
/** What a row shows of `recent`: one running, else the last that ended. */
|
|
554
|
+
const shown = (recent: Job[] | undefined) => recent?.find((each) => each.running) ?? recent?.at(-1);
|
|
555
|
+
/** How many ended jobs a branch keeps for the Git button to find its own. */
|
|
556
|
+
const KEPT_JOBS = 10;
|
|
557
|
+
|
|
558
|
+
/** What host-level code and this place load from the repository, and who uses it, as `codeFrom` says. */
|
|
559
|
+
const activeFolders = (worktrees: Worktree[], code: CodeFrom) => {
|
|
560
|
+
const folders = new Set<string>();
|
|
561
|
+
const add = (path: string) => {
|
|
562
|
+
const branch = holder(worktrees, path);
|
|
563
|
+
if (branch) folders.add(branch.folder);
|
|
564
|
+
};
|
|
565
|
+
for (const each of code.plugins)
|
|
566
|
+
if (each.workspace === host.slug || (!code.stage && each.workspace === '_host')) add(each.path);
|
|
567
|
+
if (!code.stage && code.kit) add(code.kit.path);
|
|
568
|
+
for (const each of code.chosen) if (each.stage === host.slug) add(each.folder);
|
|
569
|
+
if (folders.size === 0 && worktrees[0]) folders.add(worktrees[0].folder);
|
|
570
|
+
return folders;
|
|
571
|
+
};
|
|
572
|
+
const hostLevelOf = (worktrees: Worktree[], code: CodeFrom) => {
|
|
573
|
+
if (code.stage) return undefined;
|
|
574
|
+
const hostPlugins = code.plugins.filter((each) => each.workspace === '_host' && holder(worktrees, each.path));
|
|
575
|
+
const kit = code.kit && holder(worktrees, code.kit.path) ? code.kit : undefined;
|
|
576
|
+
if (!kit && hostPlugins.length === 0) return undefined;
|
|
577
|
+
const what = [
|
|
578
|
+
...(kit ? [`its UI kit (${kit.path})`] : []),
|
|
579
|
+
...hostPlugins.map(({ plugin, path }) => `the host plugin ${plugin} (${path})`),
|
|
580
|
+
];
|
|
581
|
+
return {
|
|
582
|
+
...(!code.checkout && {
|
|
583
|
+
refusal: `Bridge runs host-level code from this project, ${what.join(', ')}: only a Bridge running from its source checkout switches it to a branch`,
|
|
584
|
+
}),
|
|
585
|
+
...(code.uiError && { error: code.uiError }),
|
|
586
|
+
};
|
|
587
|
+
};
|
|
588
|
+
|
|
589
|
+
/** The project's branches. */
|
|
590
|
+
const listBranches = async (
|
|
591
|
+
folder: string,
|
|
592
|
+
): Promise<{ branches: Branch[]; worktrees: Worktree[]; code: CodeFrom; refreshing: () => boolean }> => {
|
|
593
|
+
const base = await baseOf(folder);
|
|
594
|
+
const worktrees = await worktreesOf(folder);
|
|
595
|
+
const main = worktrees[0]?.folder ?? real(folder);
|
|
596
|
+
// The reads of the remote and GitHub run behind it: this listing tells what they read last, and says whether one
|
|
597
|
+
// runs, or ended while it was made (its counts may be older than what git holds now).
|
|
598
|
+
const before = ended.get(main) ?? 0;
|
|
599
|
+
if (base.remote) fetchRemote(main, folder, base.remote);
|
|
600
|
+
const code = await host.codeFrom({ repository: main });
|
|
601
|
+
const active = activeFolders(worktrees, code);
|
|
602
|
+
const github = host.github();
|
|
603
|
+
const repository = github && base.remote ? repositoryOf(github, main) : undefined;
|
|
604
|
+
const records = readRecords();
|
|
605
|
+
const running = jobsOf(main);
|
|
606
|
+
const branches = await Promise.all(
|
|
607
|
+
worktrees.map(async ({ name, folder: path, main: isMain }): Promise<Branch> => {
|
|
608
|
+
// Its pull request: an open one found by its name (a new one after a merged one), else the one recorded (made
|
|
609
|
+
// or found before: a renamed or detached branch keeps it), else the latest found; never the default branch's.
|
|
610
|
+
let pr = records[path]?.url;
|
|
611
|
+
// As recorded when nothing finds it again (a detached or renamed branch): merged stays merged.
|
|
612
|
+
let state: PrState | undefined = records[path]?.state;
|
|
613
|
+
if (github && repository && !isMain && name !== base.name && name !== '(detached)') {
|
|
614
|
+
const prs = prsOf(github, main, repository, name);
|
|
615
|
+
const chosen =
|
|
616
|
+
prs.find(({ state: each }) => each === 'open' || each === 'draft') ??
|
|
617
|
+
(pr ? prs.find(({ url }) => url === pr) : undefined) ??
|
|
618
|
+
prs[0];
|
|
619
|
+
if (chosen) {
|
|
620
|
+
pr = chosen.url;
|
|
621
|
+
state = chosen.state;
|
|
622
|
+
record(path, { url: chosen.url, state: chosen.state });
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
if (pr && !state) state = 'open';
|
|
626
|
+
const recent = running.get(name);
|
|
627
|
+
const job = shown(recent);
|
|
628
|
+
const known = {
|
|
629
|
+
name,
|
|
630
|
+
folder: path,
|
|
631
|
+
main: isMain,
|
|
632
|
+
remote: !!base.remote,
|
|
633
|
+
isDefault: name === base.name,
|
|
634
|
+
active: active.has(path),
|
|
635
|
+
prOpen: state === 'open' || state === 'draft',
|
|
636
|
+
...(pr && { pr, prState: state! }),
|
|
637
|
+
...(pr && prNumberOf(pr) !== undefined && { prNumber: prNumberOf(pr)! }),
|
|
638
|
+
...(job && { job, jobs: recent! }),
|
|
639
|
+
};
|
|
640
|
+
try {
|
|
641
|
+
const [status, ahead, behindDefault, upstream, diff, merge] = await Promise.all([
|
|
642
|
+
git(path, ['status', '--porcelain']),
|
|
643
|
+
count(path, `${base.ref}..HEAD`).catch(() => 0),
|
|
644
|
+
count(path, `HEAD..${base.ref}`).catch(() => 0),
|
|
645
|
+
upstreamOf(path, name, base),
|
|
646
|
+
diffOf(path),
|
|
647
|
+
merging(path),
|
|
648
|
+
]);
|
|
649
|
+
const changed = status ? status.split('\n').filter((line) => !/ bridge\.yml$/.test(line)).length : 0;
|
|
650
|
+
return {
|
|
651
|
+
...known,
|
|
652
|
+
// A merge resolved to HEAD's own tree changes no file, yet waits for its commit (bridge#522): one change.
|
|
653
|
+
dirty: changed || (merge ? 1 : 0),
|
|
654
|
+
diff,
|
|
655
|
+
ahead,
|
|
656
|
+
behindDefault,
|
|
657
|
+
// Shown only: Delete checks it again and refuses when git cannot tell.
|
|
658
|
+
unpushed: await unpushedOf(path, name, base).catch(() => Math.max(ahead, 1)),
|
|
659
|
+
behind: upstream ? await count(path, 'HEAD..@{upstream}').catch(() => 0) : 0,
|
|
660
|
+
upstream: !!upstream,
|
|
661
|
+
};
|
|
662
|
+
} catch {
|
|
663
|
+
return {
|
|
664
|
+
...known,
|
|
665
|
+
dirty: 0,
|
|
666
|
+
diff: { files: 0, additions: 0, deletions: 0 },
|
|
667
|
+
ahead: 0,
|
|
668
|
+
behindDefault: 0,
|
|
669
|
+
unpushed: 0,
|
|
670
|
+
behind: 0,
|
|
671
|
+
upstream: false,
|
|
672
|
+
unknown: true,
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
}),
|
|
676
|
+
);
|
|
677
|
+
return {
|
|
678
|
+
branches,
|
|
679
|
+
worktrees,
|
|
680
|
+
code,
|
|
681
|
+
refreshing: () => (reading.get(main)?.size ?? 0) > 0 || (ended.get(main) ?? 0) !== before,
|
|
682
|
+
};
|
|
683
|
+
};
|
|
684
|
+
|
|
685
|
+
/** Undoes a branch `newBranch` began, as its claim says, only when nothing in it is the person's; anything else keeps
|
|
686
|
+
* it all, its claim rewritten `kept`. */
|
|
687
|
+
const undoMaking = async (main: string, file: string, claim: Making) => {
|
|
688
|
+
const keep = () => writeAtomic(file, JSON.stringify({ ...claim, kept: true }));
|
|
689
|
+
if (!claim.added) return existsSync(claim.folder) ? keep() : rmSync(file, { force: true });
|
|
690
|
+
const worktree = (await worktreesOf(main)).find((each) => each.folder === claim.folder);
|
|
691
|
+
if (!worktree || worktree.name !== claim.name) return keep();
|
|
692
|
+
const head = await git(claim.folder, ['rev-parse', 'HEAD']).catch(() => '');
|
|
693
|
+
const status = await git(claim.folder, ['status', '--porcelain']).catch(() => undefined);
|
|
694
|
+
if (head !== claim.head || status !== '') return keep();
|
|
695
|
+
if ((await host.git(main, ['worktree', 'remove', claim.folder])).code !== 0) return keep();
|
|
696
|
+
if (claim.made) await host.git(main, ['update-ref', '-d', `refs/heads/${claim.name}`, claim.head]);
|
|
697
|
+
rmSync(file, { force: true });
|
|
698
|
+
};
|
|
699
|
+
|
|
700
|
+
/** Makes branch `title` of the repository at `folder`: its worktree under `.worktrees/`, installed. A new branch's
|
|
701
|
+
* name is made safe from `title`; `existing`: the folder of branch `title` as git names it, refused when git has no
|
|
702
|
+
* such branch. */
|
|
703
|
+
const newBranch = async (folder: string, title: string, existing = false) => {
|
|
704
|
+
const name = existing ? title : branchName(title);
|
|
705
|
+
if (!name) throw new Error('name the branch');
|
|
706
|
+
if (existing && !(await git(folder, ['branch', '--list', name])))
|
|
707
|
+
throw new Error(`no branch ${name} in this project`);
|
|
708
|
+
const worktrees = await worktreesOf(folder);
|
|
709
|
+
const main = worktrees[0]?.folder ?? folder;
|
|
710
|
+
const claims = existsSync(join(main, '.worktrees'))
|
|
711
|
+
? readdirSync(join(main, '.worktrees')).filter((each) => /^\..*\.making$/.test(each))
|
|
712
|
+
: [];
|
|
713
|
+
// A branch whose creation stopped: refused with what removes it (bridge#391).
|
|
714
|
+
for (const each of claims) {
|
|
715
|
+
const file = join(main, '.worktrees', each);
|
|
716
|
+
const left = unfinished(claimText(file), file);
|
|
717
|
+
if (left?.name !== name) continue;
|
|
718
|
+
const listed = worktrees.some((tree) => tree.folder === left.folder);
|
|
719
|
+
const ref = `refs/heads/${name}`;
|
|
720
|
+
const ours =
|
|
721
|
+
left.made &&
|
|
722
|
+
left.head !== '' &&
|
|
723
|
+
(await git(main, ['rev-parse', '--verify', '--quiet', ref]).catch(() => '')) === left.head &&
|
|
724
|
+
!(await git(main, ['worktree', 'list', '--porcelain']))
|
|
725
|
+
.split('\n\n')
|
|
726
|
+
.map((block) => block.split('\n'))
|
|
727
|
+
.some((lines) => lines.includes(`branch ${ref}`) && !lines.includes(`worktree ${left.folder}`));
|
|
728
|
+
const commands = [
|
|
729
|
+
`cd ${shellQuoted(main)}`,
|
|
730
|
+
...(listed ? [`git worktree remove ${shellQuoted(left.folder)}`] : []),
|
|
731
|
+
...(ours ? [`git update-ref -d ${shellQuoted(ref)} ${left.head}`] : []),
|
|
732
|
+
`rm ${shellQuoted(file)}`,
|
|
733
|
+
].join(' && ');
|
|
734
|
+
throw new Error(
|
|
735
|
+
listed
|
|
736
|
+
? `branch ${name} was left unfinished in ${left.folder} (its creation stopped before it was installed): delete it from the project's Branches screen (its git branch stays, taken back when made again), or run \`${commands}\`, and make it again`
|
|
737
|
+
: `branch ${name} was left unfinished before its folder was made (its creation stopped): run \`${commands}\`, and make it again`,
|
|
738
|
+
);
|
|
739
|
+
}
|
|
740
|
+
if (worktrees.some((each) => each.name === name)) throw new Error(`a branch ${name} exists already`);
|
|
741
|
+
// The worktrees and the `bridge.yml` Bridge writes are Bridge's, never the repository's, where git reads its
|
|
742
|
+
// exclude (a project that is itself a worktree has its own in the main repository's).
|
|
743
|
+
const exclude = resolve(folder, await git(folder, ['rev-parse', '--git-path', 'info/exclude']));
|
|
744
|
+
mkdirSync(dirname(exclude), { recursive: true });
|
|
745
|
+
if (!existsSync(exclude) || !readFileSync(exclude, 'utf8').includes('/.worktrees/'))
|
|
746
|
+
writeFileSync(exclude, `${existsSync(exclude) ? readFileSync(exclude, 'utf8') : ''}\n/.worktrees/\nbridge.yml\n`);
|
|
747
|
+
const base = await baseOf(folder);
|
|
748
|
+
// From the remote's default branch, fetched now, else as fetched last (offline: bridge#540); its local one only
|
|
749
|
+
// without a remote.
|
|
750
|
+
if (base.remote)
|
|
751
|
+
await remoteGit(folder, ['fetch', '--quiet', '--no-auto-maintenance', base.remote, base.name]).catch(
|
|
752
|
+
() => undefined,
|
|
753
|
+
);
|
|
754
|
+
const from = base.remote && (await resolves(folder, base.ref)) ? base.ref : `refs/heads/${base.name}`;
|
|
755
|
+
const kept = await git(folder, ['branch', '--list', name]);
|
|
756
|
+
const head = await git(folder, ['rev-parse', `${kept ? `refs/heads/${name}` : from}^{commit}`]);
|
|
757
|
+
mkdirSync(join(main, '.worktrees'), { recursive: true });
|
|
758
|
+
let worktree = '';
|
|
759
|
+
let file = '';
|
|
760
|
+
const claim = (added: boolean): Making => ({
|
|
761
|
+
pid: process.pid,
|
|
762
|
+
worker,
|
|
763
|
+
name,
|
|
764
|
+
folder: worktree,
|
|
765
|
+
head,
|
|
766
|
+
made: !kept,
|
|
767
|
+
added,
|
|
768
|
+
});
|
|
769
|
+
for (let n = 1; !file; n++) {
|
|
770
|
+
worktree = join(main, '.worktrees', n === 1 ? folderName(name) : `${folderName(name)}-${n}`);
|
|
771
|
+
if (existsSync(worktree)) continue;
|
|
772
|
+
const candidate = makingFile(worktree);
|
|
773
|
+
try {
|
|
774
|
+
making.add(candidate);
|
|
775
|
+
writeFileSync(candidate, JSON.stringify(claim(false)), { flag: 'wx' });
|
|
776
|
+
file = candidate;
|
|
777
|
+
} catch (error) {
|
|
778
|
+
making.delete(candidate);
|
|
779
|
+
if (!isRecord(error) || error.code !== 'EEXIST') throw error;
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
try {
|
|
783
|
+
const added = await host.git(
|
|
784
|
+
folder,
|
|
785
|
+
// `--no-track`: its upstream is its own remote branch, set by its first push.
|
|
786
|
+
kept ? ['worktree', 'add', worktree, name] : ['worktree', 'add', '--no-track', '-b', name, worktree, head],
|
|
787
|
+
);
|
|
788
|
+
if (added.code !== 0) {
|
|
789
|
+
rmSync(file, { force: true });
|
|
790
|
+
throw new Error(added.stderr.trim() || 'git worktree add failed');
|
|
791
|
+
}
|
|
792
|
+
writeAtomic(file, JSON.stringify(claim(true)));
|
|
793
|
+
try {
|
|
794
|
+
await host.install(worktree);
|
|
795
|
+
} catch (error) {
|
|
796
|
+
await undoMaking(main, file, claim(true));
|
|
797
|
+
throw error;
|
|
798
|
+
}
|
|
799
|
+
rmSync(file, { force: true });
|
|
800
|
+
return { name, folder: worktree };
|
|
801
|
+
} finally {
|
|
802
|
+
making.delete(file);
|
|
803
|
+
}
|
|
804
|
+
};
|
|
805
|
+
|
|
806
|
+
/** Project `node` of this workspace, with whether it is a git repository of its own. */
|
|
807
|
+
const listedProject = async (node: string) => {
|
|
808
|
+
const project = (await host.projects()).find((each) => each.node === node);
|
|
809
|
+
return project && { ...project, repository: existsSync(join(project.folder, '.git')) };
|
|
810
|
+
};
|
|
811
|
+
const projectOf = async (node: string) => {
|
|
812
|
+
const project = await listedProject(node);
|
|
813
|
+
if (!project) throw new Error(`node ${node} is not a project of ${host.slug}`);
|
|
814
|
+
if (!project.repository) throw new Error(`project ${project.title} is not a git repository`);
|
|
815
|
+
return project;
|
|
816
|
+
};
|
|
817
|
+
|
|
818
|
+
/** At most `max` characters of `text`, saying how much was cut. */
|
|
819
|
+
/** At most `max` characters of `text`, never half an emoji (a lone surrogate a model's API refuses, bridge#542), saying
|
|
820
|
+
* how much was cut; `more`: git's output was cut before already. */
|
|
821
|
+
const clip = (text: string, max: number, more = false) => {
|
|
822
|
+
const kept = cutText(text, max);
|
|
823
|
+
return kept === text && !more ? text : `${kept}\n… (${more ? 'more' : text.length - kept.length} characters cut)`;
|
|
824
|
+
};
|
|
825
|
+
const unfenced = (text: string) =>
|
|
826
|
+
text
|
|
827
|
+
.trim()
|
|
828
|
+
.replace(/^```[^\n]*\n([\s\S]*?)\n?```$/, '$1')
|
|
829
|
+
.trim();
|
|
830
|
+
/** A diff for a model: its first `DIFF_BYTES` bytes read from git, cut to `DIFF_CHARS` (a 20 MB file never fills
|
|
831
|
+
* memory, bridge#597). */
|
|
832
|
+
const diffForModel = async (folder: string, args: string[]) => {
|
|
833
|
+
const ran = await host.git(folder, [...plainDiff, ...args], { maxBytes: DIFF_BYTES });
|
|
834
|
+
if (ran.code !== 0 && !ran.cut) throw new Error(ran.stderr.trim() || 'git diff failed');
|
|
835
|
+
return clip(ran.stdout, DIFF_CHARS, ran.cut === true);
|
|
836
|
+
};
|
|
837
|
+
/** Runs git with a message from a file: the host's process never closes stdin. */
|
|
838
|
+
const withFile = async <T>(text: string, work: (file: string) => Promise<T>) => {
|
|
839
|
+
const dir = join(tmpdir(), `bridge-git-${randomUUID()}`);
|
|
840
|
+
mkdirSync(dir, { recursive: true });
|
|
841
|
+
const file = join(dir, 'message.txt');
|
|
842
|
+
writeFileSync(file, text);
|
|
843
|
+
try {
|
|
844
|
+
return await work(file);
|
|
845
|
+
} finally {
|
|
846
|
+
rmSync(dir, { recursive: true, force: true });
|
|
847
|
+
}
|
|
848
|
+
};
|
|
849
|
+
|
|
850
|
+
/** Commits every change in the branch's folder (bridge.yml aside): the message written, else, finishing a merge,
|
|
851
|
+
* git's own, else one a model writes from the staged diff, else the branch's name (`fellBack` says why). Refused
|
|
852
|
+
* while a merge leaves conflicts (bridge#552): their markers would be committed. */
|
|
853
|
+
const commitBranch = async (branch: Branch, node: string, message?: string) => {
|
|
854
|
+
if (!branch.dirty) throw new Error(`${branch.name} has nothing to commit`);
|
|
855
|
+
const conflicted = await git(branch.folder, ['diff', '--name-only', '--diff-filter=U']);
|
|
856
|
+
if (conflicted)
|
|
857
|
+
throw new Error(`${branch.name} has conflicts to resolve first: ${conflicted.split('\n').join(', ')}`);
|
|
858
|
+
await git(branch.folder, ['add', '-A', '--', '.', ':!bridge.yml']);
|
|
859
|
+
let text = message?.trim() ?? '';
|
|
860
|
+
if (!text && (await merging(branch.folder))) {
|
|
861
|
+
const file = await git(branch.folder, ['rev-parse', '--git-path', 'MERGE_MSG']);
|
|
862
|
+
text = readFileSync(resolve(branch.folder, file), 'utf8')
|
|
863
|
+
.split('\n')
|
|
864
|
+
.filter((line) => !line.startsWith('#'))
|
|
865
|
+
.join('\n')
|
|
866
|
+
.trim();
|
|
867
|
+
}
|
|
868
|
+
let fellBack: string | undefined;
|
|
869
|
+
if (!text)
|
|
870
|
+
try {
|
|
871
|
+
const recent = await git(branch.folder, [...plainLog, '-n', '10', '--format=%s%n%b']).catch(() => '');
|
|
872
|
+
const stat = await git(branch.folder, [...plainDiff, '--cached', '--stat']);
|
|
873
|
+
const prompt = [
|
|
874
|
+
'Write the git commit message for the staged changes below.',
|
|
875
|
+
'Answer with the message only: a subject line (under 72 characters), a blank line, then a short body saying what changed and why, wrapped at 100 columns. No code fence, no preamble.',
|
|
876
|
+
recent
|
|
877
|
+
? `Follow the style of this repository's recent commits (prefix, tense, length):\n${recent}`
|
|
878
|
+
: 'Use the imperative mood.',
|
|
879
|
+
`Files:\n${stat}`,
|
|
880
|
+
`Diff:\n${await diffForModel(branch.folder, ['--cached'])}`,
|
|
881
|
+
].join('\n\n');
|
|
882
|
+
text = unfenced(await host.write(node, prompt, []));
|
|
883
|
+
if (!text) throw new Error('the model wrote nothing');
|
|
884
|
+
} catch (error) {
|
|
885
|
+
fellBack = `the message could not be written (${reason(error)})`;
|
|
886
|
+
text = branch.name.replace(/[-/]/g, ' ');
|
|
887
|
+
}
|
|
888
|
+
await withFile(text, (file) => git(branch.folder, ['commit', '-F', file]));
|
|
889
|
+
return { message: text, ...(fellBack && { fellBack }) };
|
|
890
|
+
};
|
|
891
|
+
const pushBranch = async (branch: Branch, confirmed = false) => {
|
|
892
|
+
if (branch.isDefault && !confirmed)
|
|
893
|
+
throw new Error(`pushing ${branch.name}, the default branch, needs a confirmation`);
|
|
894
|
+
const remote = (await remoteOf(branch.folder)) ?? 'origin';
|
|
895
|
+
await remoteGit(branch.folder, ['push', '-u', remote, branch.name]).catch((error: unknown) => {
|
|
896
|
+
throw new Error(`${branch.name} is not pushed, git refused: ${reason(error)}`);
|
|
897
|
+
});
|
|
898
|
+
};
|
|
899
|
+
const pullBranch = async (branch: Branch) => {
|
|
900
|
+
if (!branch.upstream) throw new Error(`${branch.name} has no upstream to pull from`);
|
|
901
|
+
await remoteGit(branch.folder, ['pull', '--ff-only']).catch((error: unknown) => {
|
|
902
|
+
throw new Error(`${branch.name} is not pulled, git refused: ${reason(error)}`);
|
|
903
|
+
});
|
|
904
|
+
};
|
|
905
|
+
|
|
906
|
+
/** The repository's pull request template, where GitHub looks for one. */
|
|
907
|
+
const pullRequestTemplate = (folder: string) => {
|
|
908
|
+
for (const dir of ['.github', '', 'docs'])
|
|
909
|
+
for (const name of ['pull_request_template.md', 'PULL_REQUEST_TEMPLATE.md']) {
|
|
910
|
+
const file = join(folder, dir, name);
|
|
911
|
+
if (existsSync(file)) return readFileSync(file, 'utf8');
|
|
912
|
+
}
|
|
913
|
+
const many = join(folder, '.github', 'PULL_REQUEST_TEMPLATE');
|
|
914
|
+
const first = existsSync(many)
|
|
915
|
+
? readdirSync(many)
|
|
916
|
+
.filter((name) => name.endsWith('.md'))
|
|
917
|
+
.sort()[0]
|
|
918
|
+
: undefined;
|
|
919
|
+
return first ? readFileSync(join(many, first), 'utf8') : undefined;
|
|
920
|
+
};
|
|
921
|
+
|
|
922
|
+
/** Its pull request, made once (a draft, through `github`), its texts written by a model from its commits, its diff,
|
|
923
|
+
* the template and the conversations of `sessions`; its changes committed and pushed first. */
|
|
924
|
+
const pullRequest = async (branch: Branch, main: string, node: string, sessions: string[]) => {
|
|
925
|
+
if (branch.main || branch.isDefault) throw new Error('the default branch has no pull request: start a branch');
|
|
926
|
+
const github = host.github();
|
|
927
|
+
if (!github)
|
|
928
|
+
throw new Error('Pull requests need the GitHub plugin: install GitHub (@bridgebrew/github) in this workspace');
|
|
929
|
+
// Read now, not as last listed (a listing never waits for GitHub): its repository, then its open pull request.
|
|
930
|
+
const repository = await github.repositoryOfFolder(main);
|
|
931
|
+
repositories.set(main, { at: Date.now(), repository });
|
|
932
|
+
if (!repository)
|
|
933
|
+
throw new Error(`${branch.name} has no GitHub repository gh knows: its remote is not one on github.com`);
|
|
934
|
+
const committed = branch.dirty ? await commitBranch(branch, node) : undefined;
|
|
935
|
+
await pushBranch(branch);
|
|
936
|
+
const open = (await github.pullRequestsForBranch({ repository, branch: branch.name })).find(
|
|
937
|
+
({ state }) => state === 'open' || state === 'draft',
|
|
938
|
+
);
|
|
939
|
+
if (open) {
|
|
940
|
+
record(branch.folder, { url: open.url, state: open.state });
|
|
941
|
+
found.set(`${repository}\0${branch.name}`, { at: Date.now(), prs: [{ url: open.url, state: open.state }] });
|
|
942
|
+
return { url: open.url, ...(committed && { committed }) };
|
|
943
|
+
}
|
|
944
|
+
const base = await baseOf(branch.folder);
|
|
945
|
+
const log = await git(branch.folder, [...plainLog, '--reverse', '--format=%s%n%n%b', `${base.ref}..HEAD`]);
|
|
946
|
+
const subjects = await git(branch.folder, [...plainLog, '--reverse', '--format=%s', `${base.ref}..HEAD`]);
|
|
947
|
+
const template = pullRequestTemplate(branch.folder);
|
|
948
|
+
let title = '';
|
|
949
|
+
let body = '';
|
|
950
|
+
let fellBack: string | undefined;
|
|
951
|
+
try {
|
|
952
|
+
const prompt = [
|
|
953
|
+
'Write the title and the description of the GitHub pull request for this branch.',
|
|
954
|
+
'Answer with the title on the first line (under 72 characters, in the style of the commits), a blank line, then the description in Markdown. No code fence, no preamble.',
|
|
955
|
+
'Say what changed and why, from what the user asked and the agent did in the conversation given above, and from the commits and the diff. Never invent a test or a check that is not in them.',
|
|
956
|
+
template
|
|
957
|
+
? `The description follows this template of the repository, each of its sections filled (an HTML comment of the template is an instruction: follow it and leave it out):\n${template}`
|
|
958
|
+
: 'The description: a short summary, then what changed.',
|
|
959
|
+
`Commits (oldest first):\n${log}`,
|
|
960
|
+
`Diff against ${base.name}:\n${await diffForModel(branch.folder, [`${base.ref}...HEAD`])}`,
|
|
961
|
+
].join('\n\n');
|
|
962
|
+
const [first = '', ...rest] = unfenced(await host.write(node, prompt, sessions)).split('\n');
|
|
963
|
+
title = first.replace(/^#+\s*|^title:\s*/i, '').trim();
|
|
964
|
+
body = rest.join('\n').trim();
|
|
965
|
+
if (!title || !body) throw new Error('the model wrote no title or no description');
|
|
966
|
+
} catch (error) {
|
|
967
|
+
fellBack = `the title and description could not be written (${reason(error)})`;
|
|
968
|
+
const lines = subjects ? subjects.split('\n') : [];
|
|
969
|
+
title = lines.length === 1 ? lines[0]! : branch.name.replace(/[-/]/g, ' ');
|
|
970
|
+
body = template ?? lines.map((line) => `- ${line}`).join('\n');
|
|
971
|
+
}
|
|
972
|
+
const made = await github.rest({
|
|
973
|
+
method: 'POST',
|
|
974
|
+
path: `repos/${repository}/pulls`,
|
|
975
|
+
body: { title, body, head: branch.name, base: base.name, draft: true },
|
|
976
|
+
});
|
|
977
|
+
const url = isRecord(made.body) && typeof made.body.html_url === 'string' ? made.body.html_url : undefined;
|
|
978
|
+
if (!url) throw new Error('GitHub made no pull request');
|
|
979
|
+
record(branch.folder, { url, state: 'draft' });
|
|
980
|
+
// The listing given with the answer shows it, never an older one of the branch.
|
|
981
|
+
found.set(`${repository}\0${branch.name}`, { at: Date.now(), prs: [{ url, state: 'draft' }] });
|
|
982
|
+
return { url, title, ...(committed && { committed }), ...(fellBack && { fellBack }) };
|
|
983
|
+
};
|
|
984
|
+
|
|
985
|
+
/** The repositories of their own (a `.git`) inside the folders git ignores in `folder` (bridge#523): deleting the
|
|
986
|
+
* folder would delete them, with their commits. */
|
|
987
|
+
const nestedRepositories = async (folder: string) => {
|
|
988
|
+
const ignored = (
|
|
989
|
+
await git(folder, ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory', '-z'])
|
|
990
|
+
)
|
|
991
|
+
.split('\0')
|
|
992
|
+
.filter(Boolean);
|
|
993
|
+
const nested: string[] = [];
|
|
994
|
+
// Every level down each ignored folder (a repository nine levels under node_modules is one too), read without
|
|
995
|
+
// blocking the worker: a large ignored tree takes its time, never the other routes'.
|
|
996
|
+
const walk = async (path: string): Promise<void> => {
|
|
997
|
+
if (existsSync(join(path, '.git'))) return void nested.push(relative(folder, path));
|
|
998
|
+
let entries;
|
|
999
|
+
try {
|
|
1000
|
+
entries = await readdir(path, { withFileTypes: true });
|
|
1001
|
+
} catch {
|
|
1002
|
+
return;
|
|
1003
|
+
}
|
|
1004
|
+
for (const entry of entries) if (entry.isDirectory() && entry.name !== '.git') await walk(join(path, entry.name));
|
|
1005
|
+
};
|
|
1006
|
+
for (const each of ignored) {
|
|
1007
|
+
const path = join(folder, each);
|
|
1008
|
+
if (lstatSync(path, { throwIfNoEntry: false })?.isDirectory()) await walk(path);
|
|
1009
|
+
}
|
|
1010
|
+
return nested;
|
|
1011
|
+
};
|
|
1012
|
+
|
|
1013
|
+
/** Deletes a branch's folder, refused while anything uses it or holds work. */
|
|
1014
|
+
const removeBranch = async (folder: string, branch: Branch, worktrees: Worktree[]) => {
|
|
1015
|
+
if (branch.main) throw new Error('the project’s own folder is never deleted');
|
|
1016
|
+
const claim = makingFile(branch.folder);
|
|
1017
|
+
const claimed = claimText(claim);
|
|
1018
|
+
const dead = unfinished(claimed, claim);
|
|
1019
|
+
if (claimed !== undefined && !dead)
|
|
1020
|
+
throw new Error(`${branch.name} is still being made: delete it once its creation is done`);
|
|
1021
|
+
const unpushed = await unpushedOf(branch.folder, branch.name, await baseOf(folder)).catch((error: unknown) => {
|
|
1022
|
+
throw new Error(
|
|
1023
|
+
`${branch.name} is not deleted: git cannot tell whether its commits are pushed (${reason(error)})`,
|
|
1024
|
+
);
|
|
1025
|
+
});
|
|
1026
|
+
if (branch.dirty || unpushed)
|
|
1027
|
+
throw new Error(`${branch.name} holds work that is not pushed: open its pull request first`);
|
|
1028
|
+
const nested = await nestedRepositories(branch.folder);
|
|
1029
|
+
if (nested.length > 0)
|
|
1030
|
+
throw new Error(
|
|
1031
|
+
`${branch.name} is not deleted: its folder holds a repository of its own git does not track (${nested.join(', ')}); move it out first`,
|
|
1032
|
+
);
|
|
1033
|
+
// Who uses it, then its removal, by the host in one turn with Activate's (`bridgeNodes.removeWorktree`): nothing
|
|
1034
|
+
// starts using it in between, in any workspace or stage.
|
|
1035
|
+
await host.removeWorktree({ repository: worktrees[0]?.folder ?? folder, folder: branch.folder });
|
|
1036
|
+
if (dead && claimText(claim) === claimed) rmSync(claim, { force: true });
|
|
1037
|
+
record(branch.folder, undefined);
|
|
1038
|
+
};
|
|
1039
|
+
|
|
1040
|
+
/** The Branches screen's view of project `node`. */
|
|
1041
|
+
const view = async (node: string) => {
|
|
1042
|
+
const project = await listedProject(node);
|
|
1043
|
+
if (!project) return { project: null, branches: [] };
|
|
1044
|
+
if (!project.repository) return { project: { title: project.title, folder: project.folder }, repository: false };
|
|
1045
|
+
const { branches, worktrees, code, refreshing } = await listBranches(project.folder);
|
|
1046
|
+
const hostLevel = hostLevelOf(worktrees, code);
|
|
1047
|
+
const main = worktrees[0]?.folder ?? project.folder;
|
|
1048
|
+
// A new branch's job is by its title: shown beside the list until it ends.
|
|
1049
|
+
const making = [...jobsOf(main).entries()]
|
|
1050
|
+
.filter(([name]) => !branches.some((branch) => branch.name === name))
|
|
1051
|
+
.flatMap(([name, recent]) => {
|
|
1052
|
+
const job = shown(recent);
|
|
1053
|
+
return job ? [{ name, ...job }] : [];
|
|
1054
|
+
});
|
|
1055
|
+
return {
|
|
1056
|
+
project: { title: project.title, folder: project.folder },
|
|
1057
|
+
github: host.github() ? 'ready' : 'missing',
|
|
1058
|
+
...(hostLevel && { hostLevel }),
|
|
1059
|
+
branches,
|
|
1060
|
+
...(making.length > 0 && { jobs: making }),
|
|
1061
|
+
// A fetch or a GitHub read of this project runs, or ended meanwhile: the next listing shows what it read.
|
|
1062
|
+
...(refreshing() && { refreshing: true }),
|
|
1063
|
+
};
|
|
1064
|
+
};
|
|
1065
|
+
|
|
1066
|
+
/** One action at a time per worker, as the host's route was. */
|
|
1067
|
+
let busy: Promise<unknown> = Promise.resolve();
|
|
1068
|
+
const queued = <T>(work: () => Promise<T>) => {
|
|
1069
|
+
const done = busy.then(work);
|
|
1070
|
+
busy = done.catch(() => {});
|
|
1071
|
+
return done;
|
|
1072
|
+
};
|
|
1073
|
+
/** Runs `work` as branch `name`'s job of the project at `main`: its route waits `waitMs` at most, then answers that
|
|
1074
|
+
* it runs on; its end is kept for the listing. */
|
|
1075
|
+
const job = async (
|
|
1076
|
+
main: string,
|
|
1077
|
+
name: string,
|
|
1078
|
+
action: string,
|
|
1079
|
+
work: () => Promise<Record<string, unknown>>,
|
|
1080
|
+
started = Date.now(),
|
|
1081
|
+
) => {
|
|
1082
|
+
const running = jobsOf(main);
|
|
1083
|
+
const id = randomUUID();
|
|
1084
|
+
// An action asked while another runs waits for it (the Git button's Push then Create PR): each keeps its own end,
|
|
1085
|
+
// by its id, the last few of the branch.
|
|
1086
|
+
running.set(name, [...(running.get(name) ?? []), { id, action, running: true }].slice(-KEPT_JOBS));
|
|
1087
|
+
const end = (job: Omit<Job, 'id'>) =>
|
|
1088
|
+
running.set(
|
|
1089
|
+
name,
|
|
1090
|
+
(running.get(name) ?? []).map((each) => (each.id === id ? { id, ...job } : each)),
|
|
1091
|
+
);
|
|
1092
|
+
const done = queued(work).then(
|
|
1093
|
+
(result) => (end({ action, running: false, result }), result),
|
|
1094
|
+
(error: unknown) => {
|
|
1095
|
+
end({ action, running: false, error: reason(error) });
|
|
1096
|
+
throw error;
|
|
1097
|
+
},
|
|
1098
|
+
);
|
|
1099
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
1100
|
+
// `waitMs` counted from the request's start: its answer leaves before the route's deadline.
|
|
1101
|
+
const later = new Promise<'later'>(
|
|
1102
|
+
(done) => (timer = setTimeout(() => done('later'), Math.max(0, waitMs - (Date.now() - started)))),
|
|
1103
|
+
);
|
|
1104
|
+
try {
|
|
1105
|
+
const first = await Promise.race([done, later]);
|
|
1106
|
+
return first === 'later' ? { running: action, job: id } : first;
|
|
1107
|
+
} finally {
|
|
1108
|
+
clearTimeout(timer);
|
|
1109
|
+
done.catch(() => {});
|
|
1110
|
+
}
|
|
1111
|
+
};
|
|
1112
|
+
|
|
1113
|
+
/** Action `action` on project `node` with `input`; the view after it, and what it did. */
|
|
1114
|
+
const act = async (node: string, action: string, input: Record<string, unknown>) => {
|
|
1115
|
+
const started = Date.now();
|
|
1116
|
+
const project = await projectOf(node);
|
|
1117
|
+
const worktrees = await worktreesOf(project.folder);
|
|
1118
|
+
const main = worktrees[0]?.folder ?? project.folder;
|
|
1119
|
+
const run = (name: string, what: string, work: () => Promise<Record<string, unknown>>) =>
|
|
1120
|
+
job(main, name, what, work, started);
|
|
1121
|
+
let result: unknown;
|
|
1122
|
+
if (action === 'new') {
|
|
1123
|
+
if (typeof input.title !== 'string') throw new Error('the body is { title }');
|
|
1124
|
+
const title = input.title;
|
|
1125
|
+
result = await run(branchName(title) || title, 'new', async () => ({
|
|
1126
|
+
name: (await newBranch(project.folder, title)).name,
|
|
1127
|
+
}));
|
|
1128
|
+
} else {
|
|
1129
|
+
const name = String(input.name);
|
|
1130
|
+
/** The branch as it is now: read again when an action's turn comes, after the ones queued before it (a Push
|
|
1131
|
+
* before Create PR leaves it with an upstream). */
|
|
1132
|
+
const now = async () => {
|
|
1133
|
+
const found = (await listBranches(project.folder)).branches.find((each) => each.name === name);
|
|
1134
|
+
if (!found) throw new Error(`no branch ${name} in ${project.title}`);
|
|
1135
|
+
return found;
|
|
1136
|
+
};
|
|
1137
|
+
const branch = await now();
|
|
1138
|
+
const sessionsOf = async () =>
|
|
1139
|
+
typeof input.session === 'string'
|
|
1140
|
+
? [input.session]
|
|
1141
|
+
: ((await host.codeFrom({ repository: main, sessions: true }).catch(() => undefined))?.sessions ?? [])
|
|
1142
|
+
.filter((each) => each.workspace === host.slug && within(each.folder, branch.folder))
|
|
1143
|
+
.map((each) => each.session);
|
|
1144
|
+
if (action === 'activate')
|
|
1145
|
+
result = await run(name, 'activate', async () => ({
|
|
1146
|
+
activated: name,
|
|
1147
|
+
...(await host.follow({ repository: main, target: (await now()).folder })),
|
|
1148
|
+
}));
|
|
1149
|
+
else if (action === 'commit') {
|
|
1150
|
+
const message = typeof input.message === 'string' ? input.message : undefined;
|
|
1151
|
+
result = await queued(async () => ({ committed: name, ...(await commitBranch(await now(), node, message)) }));
|
|
1152
|
+
} else if (action === 'push')
|
|
1153
|
+
result = await run(name, 'push', async () => {
|
|
1154
|
+
await pushBranch(await now(), input.confirmed === true);
|
|
1155
|
+
return { pushed: name };
|
|
1156
|
+
});
|
|
1157
|
+
else if (action === 'pull')
|
|
1158
|
+
result = await run(name, 'pull', async () => (await pullBranch(await now()), { pulled: name }));
|
|
1159
|
+
else if (action === 'pr')
|
|
1160
|
+
result = await run(name, 'pr', async () => {
|
|
1161
|
+
const { url, ...made } = await pullRequest(await now(), main, node, await sessionsOf());
|
|
1162
|
+
return { pr: url, ...made };
|
|
1163
|
+
});
|
|
1164
|
+
else if (action === 'remove') {
|
|
1165
|
+
await queued(async () => removeBranch(project.folder, await now(), await worktreesOf(project.folder)));
|
|
1166
|
+
jobsOf(main).delete(name);
|
|
1167
|
+
result = { removed: name };
|
|
1168
|
+
} else throw new Error(`no action ${action}`);
|
|
1169
|
+
}
|
|
1170
|
+
return { ...(await view(node)), result };
|
|
1171
|
+
};
|
|
1172
|
+
|
|
1173
|
+
return {
|
|
1174
|
+
view,
|
|
1175
|
+
act,
|
|
1176
|
+
/** A session's new branch in project `node` (Sessions, research-083): made as New makes one; `existing`: the folder
|
|
1177
|
+
* of that branch, its name kept. */
|
|
1178
|
+
newBranch: async ({
|
|
1179
|
+
node,
|
|
1180
|
+
name,
|
|
1181
|
+
existing = false,
|
|
1182
|
+
}: {
|
|
1183
|
+
node: string;
|
|
1184
|
+
name: string;
|
|
1185
|
+
existing?: boolean | undefined;
|
|
1186
|
+
}) => {
|
|
1187
|
+
const project = await projectOf(node);
|
|
1188
|
+
return queued(() => newBranch(project.folder, name, existing));
|
|
1189
|
+
},
|
|
1190
|
+
/** A child session's branch (bridge#212 S7): the new branch `name` of the checkout this workspace runs `plugins`
|
|
1191
|
+
* from, for a stage to choose (`bridgeMcp.addWorktree` with `existing`). */
|
|
1192
|
+
branchForPlugins: async ({ plugins, name }: { plugins: string[]; name: string }) => {
|
|
1193
|
+
const repository = await host.pluginsRepository(plugins);
|
|
1194
|
+
const made = await queued(() => newBranch(repository, name));
|
|
1195
|
+
return { repository, ...made };
|
|
1196
|
+
},
|
|
1197
|
+
worktreesOf,
|
|
1198
|
+
};
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
/** A new file's lines (a last one without a newline counts), its first `READ_CAP` bytes only; a binary has none. */
|
|
1202
|
+
const newLines = async (path: string) => {
|
|
1203
|
+
try {
|
|
1204
|
+
const file = await open(path);
|
|
1205
|
+
try {
|
|
1206
|
+
const { buffer, bytesRead } = await file.read(Buffer.alloc(READ_CAP), 0, READ_CAP, 0);
|
|
1207
|
+
const text = buffer.subarray(0, bytesRead);
|
|
1208
|
+
if (text.includes(0)) return 0;
|
|
1209
|
+
let lines = 0;
|
|
1210
|
+
for (const byte of text) if (byte === 10) lines++;
|
|
1211
|
+
return bytesRead > 0 && text[bytesRead - 1] !== 10 ? lines + 1 : lines;
|
|
1212
|
+
} finally {
|
|
1213
|
+
await file.close();
|
|
1214
|
+
}
|
|
1215
|
+
} catch {
|
|
1216
|
+
return 0;
|
|
1217
|
+
}
|
|
1218
|
+
};
|
|
1219
|
+
|
|
1220
|
+
export type Branches = ReturnType<typeof createBranches>;
|