@bridgebrew/project 0.0.6 → 0.0.12
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 +179 -401
- package/browser/branches.tsx +108 -29
- package/browser/browser.tsx +27 -7
- package/names.ts +15 -4
- package/package.json +37 -6
- package/server.ts +60 -3
package/branches.ts
CHANGED
|
@@ -2,119 +2,28 @@
|
|
|
2
2
|
// each with its git worktree under the project's folder (`<project>/.worktrees/<name>`, kept out of git), where the
|
|
3
3
|
// sessions on that branch work. The Branches screen (./browser/branches.tsx) lists them and acts on them through this
|
|
4
4
|
// plugin's routes (`/branches…`, never an agent's: `agent: false`); Sessions makes a session's branch through the
|
|
5
|
-
// `projectBranches` service. git
|
|
6
|
-
//
|
|
7
|
-
// (`bridgeNodes.
|
|
5
|
+
// `projectBranches` service. git is the `git` plugin's service (`@bridgebrew/git`, bridge-plugins#256): without it the
|
|
6
|
+
// screen offers to install it, and no action runs. What Bridge loads from the project's folders, and switching it
|
|
7
|
+
// (Activate), stay the host's (`bridgeNodes.codeFrom`, `follow`), as does a branch's install (`bridgeNodes.install`,
|
|
8
|
+
// Bridge's own pnpm). Pull requests go through the optional `github` service: without it, every
|
|
8
9
|
// git action works and Create PR is refused, saying so.
|
|
9
10
|
// - New: a branch from the project's default branch, its worktree, its dependencies.
|
|
10
11
|
// - Its end: commit, push, a draft pull request, each alone too, their texts written by a model (Sessions' `POST
|
|
11
12
|
// /sessions/write`) unless the user wrote them; then it may be deleted, refused while it holds work that is not pushed
|
|
12
13
|
// (or whose push state git cannot tell), a repository of its own in an ignored folder (bridge#523), or while
|
|
13
14
|
// anything uses it in Bridge (`codeFrom`): a plugin of any place, a stage's choice, host-level code, a session.
|
|
15
|
+
// - The Commit changes dialog of a branch (the `git` plugin's, filling `project.branch-actions`) reads its changes
|
|
16
|
+
// (`/branches/changes`, `/branches/lines`) and commits through `/branches/commit`.
|
|
14
17
|
// - New, Push, Pull, Create PR and Activate may outlast a route's deadline: each runs as this worker's job, its route
|
|
15
18
|
// waiting for it `waitMs` at most, then answering that it runs on; the listing says what runs and how the last one
|
|
16
19
|
// ended, by branch (owner decision, bridge#557).
|
|
17
20
|
// A branch is known by git (`git worktree list`): its folder's name is only made safe, never read back as its name.
|
|
18
21
|
import { randomUUID } from 'node:crypto';
|
|
19
|
-
import {
|
|
20
|
-
|
|
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';
|
|
22
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
23
|
+
import { basename, dirname, join, sep } from 'node:path';
|
|
34
24
|
import { isRecord } from '@bridge/kernel/json';
|
|
35
|
-
import {
|
|
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
|
-
};
|
|
25
|
+
import type { GitService } from '@bridgebrew/git/contract.ts';
|
|
26
|
+
import { foldLetters } from './names.ts';
|
|
118
27
|
|
|
119
28
|
/** What the host says Bridge loads from a repository (`bridgeNodes.codeFrom`). */
|
|
120
29
|
export interface CodeFrom {
|
|
@@ -149,7 +58,8 @@ export interface BranchesHost {
|
|
|
149
58
|
slug: string;
|
|
150
59
|
/** Where this plugin keeps its records (the pull requests it made or found). */
|
|
151
60
|
dataDir: string;
|
|
152
|
-
git
|
|
61
|
+
/** The `git` service, when the workspace has the `git` plugin. */
|
|
62
|
+
git(): GitService | undefined;
|
|
153
63
|
/** The workspace's projects as its `bridge.yml` files list them (`bridgeNodes.projects`). */
|
|
154
64
|
projects(): Promise<{ project: string; node?: string | undefined; folder: string; title: string }[]>;
|
|
155
65
|
codeFrom(input: { repository: string; sessions?: boolean }): Promise<CodeFrom>;
|
|
@@ -230,24 +140,19 @@ const folderName = (name: string) => name.replaceAll('/', '-');
|
|
|
230
140
|
/** A branch name from a title: its letters without their accents (`Café crème` is `cafe-creme`, bridge#552), lowercase,
|
|
231
141
|
* joined by `-`. */
|
|
232
142
|
export const branchName = (title: string) =>
|
|
233
|
-
title
|
|
234
|
-
.toLowerCase()
|
|
235
|
-
.normalize('NFKD')
|
|
236
|
-
.replace(/[\u0300-\u036f]/g, '')
|
|
143
|
+
foldLetters(title)
|
|
237
144
|
.replace(/[^a-z0-9/]+/g, '-')
|
|
238
145
|
.replace(/^-+|-+$/g, '')
|
|
239
146
|
.slice(0, 50);
|
|
240
147
|
|
|
241
|
-
/**
|
|
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). */
|
|
148
|
+
/** How much of a diff a model is given (bridge#597). */
|
|
245
149
|
const DIFF_CHARS = 60_000;
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
150
|
+
/** Bridge's own file in a project's folder: never committed, never counted as a change. */
|
|
151
|
+
const BRIDGE_YML = 'bridge.yml';
|
|
152
|
+
/** How many files' diff the Commit changes dialog gets whole: past them, each file is read by its path. */
|
|
153
|
+
const DIFF_FILES_MAX = 50;
|
|
154
|
+
/** The most characters of the dialog's whole diff. */
|
|
155
|
+
const DIFF_MAX = 24 * 1024;
|
|
251
156
|
|
|
252
157
|
/** The claim `newBranch` takes on a branch's folder in `.worktrees/` before it makes the branch (created exclusively,
|
|
253
158
|
* so two creators never share a folder), removed once made or undone (bridge#326). Workers are threads of the host's
|
|
@@ -294,33 +199,23 @@ export interface Settings {
|
|
|
294
199
|
waitMs?: number;
|
|
295
200
|
/** The listing's fetch deadline. */
|
|
296
201
|
fetchDeadlineMs?: number;
|
|
297
|
-
/** A remote run's deadline (push, pull, a branch's fetch). */
|
|
298
|
-
remoteDeadlineMs?: number;
|
|
299
202
|
}
|
|
300
203
|
|
|
301
204
|
/** The branches of host's workspace's projects. */
|
|
302
205
|
export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
303
|
-
const { waitMs = 100_000, fetchDeadlineMs = 30_000
|
|
206
|
+
const { waitMs = 100_000, fetchDeadlineMs = 30_000 } = settings;
|
|
304
207
|
// Its host's process (a worker is a thread of it), its workspace, this start: two Bridges sharing a repository, each
|
|
305
208
|
// with a workspace of that name, never take each other's claims for an older worker's.
|
|
306
209
|
const worker = `${process.pid}:${host.slug}:${randomUUID()}`;
|
|
307
210
|
/** The claims this worker is making now, by file. */
|
|
308
211
|
const making = new Set<string>();
|
|
309
212
|
|
|
310
|
-
/** git
|
|
311
|
-
const
|
|
312
|
-
const
|
|
313
|
-
if (
|
|
314
|
-
|
|
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();
|
|
213
|
+
/** The `git` service; refused, saying how to get it, without it. */
|
|
214
|
+
const gitOf = () => {
|
|
215
|
+
const git = host.git();
|
|
216
|
+
if (!git) throw new Error('git actions need the Git plugin: install Git (@bridgebrew/git) in this workspace');
|
|
217
|
+
return git;
|
|
321
218
|
};
|
|
322
|
-
const resolves = (folder: string, ref: string) =>
|
|
323
|
-
host.git(folder, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]).then(({ code }) => code === 0);
|
|
324
219
|
|
|
325
220
|
/** The claim `text` when it marks an unfinished branch. */
|
|
326
221
|
const unfinished = (text: string | undefined, file: string) => {
|
|
@@ -355,58 +250,21 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
355
250
|
/** The repository's branches that have a folder (`git worktree list`): its own checkout first (main), then each
|
|
356
251
|
* worktree under `.worktrees/`; a detached one named `(detached)`, marked. Read only. */
|
|
357
252
|
const worktreesOf = async (folder: string) => {
|
|
358
|
-
const
|
|
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
|
-
});
|
|
253
|
+
const all = await gitOf().worktrees(folder);
|
|
366
254
|
const main = all[0]?.folder ?? real(folder);
|
|
367
255
|
return all
|
|
368
256
|
.filter((each) => each.folder === main || within(each.folder, join(main, '.worktrees')))
|
|
369
|
-
.map((
|
|
257
|
+
.map(({ folder: path, branch, detached }) => ({
|
|
258
|
+
name: branch ?? '(detached)',
|
|
259
|
+
folder: path,
|
|
260
|
+
main: path === main,
|
|
261
|
+
...(detached && { detached: true as const }),
|
|
262
|
+
}));
|
|
370
263
|
};
|
|
371
264
|
type Worktree = Awaited<ReturnType<typeof worktreesOf>>[number];
|
|
372
265
|
const holder = <T extends { folder: string }>(branches: T[], path: string) =>
|
|
373
266
|
branches.filter((each) => within(path, each.folder)).sort((a, b) => b.folder.length - a.folder.length)[0];
|
|
374
267
|
|
|
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
|
-
// Its full name: the short form is `heads/<name>` beside a tag of the same name (plugins#198).
|
|
379
|
-
const head = await git(folder, ['symbolic-ref', '--quiet', 'HEAD']).catch(() => '');
|
|
380
|
-
const branch = head.replace(/^refs\/heads\//, '');
|
|
381
|
-
const tracked = branch && (await git(folder, ['config', '--get', `branch.${branch}.remote`]).catch(() => ''));
|
|
382
|
-
const names = (await git(folder, ['remote']).catch(() => '')).split('\n').filter(Boolean);
|
|
383
|
-
const name = tracked && names.includes(tracked) ? tracked : names.length === 1 ? names[0] : 'origin';
|
|
384
|
-
return name !== undefined && names.includes(name) ? name : undefined;
|
|
385
|
-
};
|
|
386
|
-
/** The project's default branch on `remote` (`<remote>/HEAD`) when the branch it names exists (bridge#540), read as a
|
|
387
|
-
* full ref so a local branch or a tag of the same name never shadows it (bridge#595), else the branch its own
|
|
388
|
-
* checkout is on, else `main`. */
|
|
389
|
-
const defaultBranch = async (folder: string, remote: string | undefined) => {
|
|
390
|
-
const head = `refs/remotes/${remote}/HEAD`;
|
|
391
|
-
const named =
|
|
392
|
-
remote && (await resolves(folder, head)) ? await git(folder, ['symbolic-ref', head]).catch(() => '') : '';
|
|
393
|
-
const prefix = `refs/remotes/${remote}/`;
|
|
394
|
-
const current = await git(folder, ['symbolic-ref', '--quiet', 'HEAD']).catch(() => '');
|
|
395
|
-
return (
|
|
396
|
-
(named.startsWith(prefix) ? named.slice(prefix.length) : '') ||
|
|
397
|
-
(current.startsWith('refs/heads/') ? current.slice('refs/heads/'.length) : '') ||
|
|
398
|
-
'main'
|
|
399
|
-
);
|
|
400
|
-
};
|
|
401
|
-
/** What a branch's commits are compared with: the default branch on the remote, or its local one without one. */
|
|
402
|
-
const baseOf = async (folder: string) => {
|
|
403
|
-
const remote = await remoteOf(folder);
|
|
404
|
-
const name = await defaultBranch(folder, remote);
|
|
405
|
-
return { remote, name, ref: remote ? `refs/remotes/${remote}/${name}` : `refs/heads/${name}` };
|
|
406
|
-
};
|
|
407
|
-
type Base = Awaited<ReturnType<typeof baseOf>>;
|
|
408
|
-
const count = async (path: string, range: string) => Number(await git(path, ['rev-list', '--count', range]));
|
|
409
|
-
|
|
410
268
|
/** When each project's remote was last fetched. */
|
|
411
269
|
const fetched = new Map<string, number>();
|
|
412
270
|
/** Fetches the project's remote at most once a minute, without git's automatic maintenance in the user's
|
|
@@ -433,13 +291,7 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
433
291
|
// ponytail: one fetch a minute per project, a background poll if a fresher Pull matters.
|
|
434
292
|
if (Date.now() - (fetched.get(folder) ?? 0) < 60_000) return;
|
|
435
293
|
fetched.set(folder, Date.now());
|
|
436
|
-
behind(main, `fetch`, () =>
|
|
437
|
-
remoteGit(
|
|
438
|
-
folder,
|
|
439
|
-
['-c', 'maintenance.auto=false', '-c', 'gc.auto=0', 'fetch', '--quiet', '--no-auto-maintenance', remote],
|
|
440
|
-
fetchDeadlineMs,
|
|
441
|
-
),
|
|
442
|
-
);
|
|
294
|
+
behind(main, `fetch`, () => gitOf().fetch(folder, { remote, deadlineMs: fetchDeadlineMs }));
|
|
443
295
|
};
|
|
444
296
|
|
|
445
297
|
// --- Pull requests: the ones Bridge made or found, by worktree folder (a renamed or detached branch keeps its own)
|
|
@@ -505,46 +357,6 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
505
357
|
return number ? Number(number) : undefined;
|
|
506
358
|
};
|
|
507
359
|
|
|
508
|
-
/** What a branch's folder changed and did not commit, as GitHub's diffstat counts it (bridge.yml aside); `git
|
|
509
|
-
* diff-index`, which writes no index (bridge#522). */
|
|
510
|
-
const diffOf = async (folder: string): Promise<Diff> => {
|
|
511
|
-
const diff = { files: 0, additions: 0, deletions: 0 };
|
|
512
|
-
const tracked = await git(folder, ['diff-index', '--numstat', '--no-renames', 'HEAD', '--', '.', ':!bridge.yml']);
|
|
513
|
-
for (const line of tracked ? tracked.split('\n') : []) {
|
|
514
|
-
const [added = '', deleted = ''] = line.split('\t');
|
|
515
|
-
diff.files++;
|
|
516
|
-
diff.additions += Number(added) || 0;
|
|
517
|
-
diff.deletions += Number(deleted) || 0;
|
|
518
|
-
}
|
|
519
|
-
const untracked = await git(folder, [
|
|
520
|
-
'ls-files',
|
|
521
|
-
'--others',
|
|
522
|
-
'--exclude-standard',
|
|
523
|
-
'-z',
|
|
524
|
-
'--',
|
|
525
|
-
'.',
|
|
526
|
-
':!bridge.yml',
|
|
527
|
-
]);
|
|
528
|
-
for (const path of untracked.split('\0').filter(Boolean)) {
|
|
529
|
-
diff.files++;
|
|
530
|
-
diff.additions += await newLines(join(folder, path));
|
|
531
|
-
}
|
|
532
|
-
return diff;
|
|
533
|
-
};
|
|
534
|
-
/** Whether the branch in `path` is in the middle of a merge: its `MERGE_HEAD`, read where git keeps it. */
|
|
535
|
-
const merging = (path: string) => resolves(path, 'MERGE_HEAD');
|
|
536
|
-
/** The upstream of branch `name`, else `''`; the default branch's remote ref is no upstream of another branch. */
|
|
537
|
-
const upstreamOf = async (path: string, name: string, base: Base) => {
|
|
538
|
-
const upstream = await git(path, ['rev-parse', '--symbolic-full-name', '@{upstream}']).catch(() => '');
|
|
539
|
-
return upstream === base.ref && name !== base.name ? '' : upstream;
|
|
540
|
-
};
|
|
541
|
-
/** The commits no remote has; throws when git cannot tell. */
|
|
542
|
-
const unpushedOf = async (path: string, name: string, base: Base) => {
|
|
543
|
-
if (!base.remote) return count(path, `${base.ref}..HEAD`);
|
|
544
|
-
const upstream = await upstreamOf(path, name, base);
|
|
545
|
-
return count(path, upstream ? '@{upstream}..HEAD' : `${base.ref}..HEAD`);
|
|
546
|
-
};
|
|
547
|
-
|
|
548
360
|
/** The recent jobs of each project (by its own folder), by branch name (a new one by its title), oldest first. */
|
|
549
361
|
const jobs = new Map<string, Map<string, Job[]>>();
|
|
550
362
|
const jobsOf = (main: string) => {
|
|
@@ -592,7 +404,8 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
592
404
|
const listBranches = async (
|
|
593
405
|
folder: string,
|
|
594
406
|
): Promise<{ branches: Branch[]; worktrees: Worktree[]; code: CodeFrom; refreshing: () => boolean }> => {
|
|
595
|
-
const
|
|
407
|
+
const git = gitOf();
|
|
408
|
+
const base = await git.defaultBranch(folder);
|
|
596
409
|
const worktrees = await worktreesOf(folder);
|
|
597
410
|
const main = worktrees[0]?.folder ?? real(folder);
|
|
598
411
|
// The reads of the remote and GitHub run behind it: this listing tells what they read last, and says whether one
|
|
@@ -640,26 +453,18 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
640
453
|
...(job && { job, jobs: recent! }),
|
|
641
454
|
};
|
|
642
455
|
try {
|
|
643
|
-
const
|
|
644
|
-
git(path, ['status', '--porcelain']),
|
|
645
|
-
count(path, `${base.ref}..HEAD`).catch(() => 0),
|
|
646
|
-
count(path, `HEAD..${base.ref}`).catch(() => 0),
|
|
647
|
-
upstreamOf(path, name, base),
|
|
648
|
-
diffOf(path),
|
|
649
|
-
merging(path),
|
|
650
|
-
]);
|
|
651
|
-
const changed = status ? status.split('\n').filter((line) => !/ bridge\.yml$/.test(line)).length : 0;
|
|
456
|
+
const status = await git.branchStatus(path, { exclude: [BRIDGE_YML], base });
|
|
652
457
|
return {
|
|
653
458
|
...known,
|
|
654
459
|
// A merge resolved to HEAD's own tree changes no file, yet waits for its commit (bridge#522): one change.
|
|
655
|
-
dirty: changed || (
|
|
656
|
-
diff,
|
|
657
|
-
ahead,
|
|
658
|
-
behindDefault,
|
|
460
|
+
dirty: status.changed || (status.merging ? 1 : 0),
|
|
461
|
+
diff: status.diff,
|
|
462
|
+
ahead: status.ahead,
|
|
463
|
+
behindDefault: status.behindDefault,
|
|
659
464
|
// Shown only: Delete checks it again and refuses when git cannot tell.
|
|
660
|
-
unpushed:
|
|
661
|
-
behind:
|
|
662
|
-
upstream: !!upstream,
|
|
465
|
+
unpushed: status.unpushed ?? Math.max(status.ahead, 1),
|
|
466
|
+
behind: status.behind,
|
|
467
|
+
upstream: !!status.upstream,
|
|
663
468
|
};
|
|
664
469
|
} catch {
|
|
665
470
|
return {
|
|
@@ -689,13 +494,14 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
689
494
|
const undoMaking = async (main: string, file: string, claim: Making) => {
|
|
690
495
|
const keep = () => writeAtomic(file, JSON.stringify({ ...claim, kept: true }));
|
|
691
496
|
if (!claim.added) return existsSync(claim.folder) ? keep() : rmSync(file, { force: true });
|
|
497
|
+
const git = gitOf();
|
|
692
498
|
const worktree = (await worktreesOf(main)).find((each) => each.folder === claim.folder);
|
|
693
499
|
if (!worktree || worktree.name !== claim.name) return keep();
|
|
694
|
-
const head = await git(claim.folder,
|
|
695
|
-
const status = await git(claim.folder
|
|
696
|
-
if (head !== claim.head || status !==
|
|
697
|
-
if ((await
|
|
698
|
-
if (claim.made) await
|
|
500
|
+
const head = await git.resolve(claim.folder, 'HEAD');
|
|
501
|
+
const status = await git.branchStatus(claim.folder).catch(() => undefined);
|
|
502
|
+
if (head !== claim.head || status?.changed !== 0) return keep();
|
|
503
|
+
if (!(await git.removeWorktree(main, claim.folder).then(() => true, () => false))) return keep();
|
|
504
|
+
if (claim.made) await git.deleteBranch(main, claim.name, { expected: claim.head }).catch(() => undefined);
|
|
699
505
|
rmSync(file, { force: true });
|
|
700
506
|
};
|
|
701
507
|
|
|
@@ -703,9 +509,10 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
703
509
|
* name is made safe from `title`; `existing`: the folder of branch `title` as git names it, refused when git has no
|
|
704
510
|
* such branch. */
|
|
705
511
|
const newBranch = async (folder: string, title: string, existing = false) => {
|
|
512
|
+
const git = gitOf();
|
|
706
513
|
const name = existing ? title : branchName(title);
|
|
707
514
|
if (!name) throw new Error('name the branch');
|
|
708
|
-
if (existing && !(await git(folder
|
|
515
|
+
if (existing && !(await git.branchNames(folder)).includes(name))
|
|
709
516
|
throw new Error(`no branch ${name} in this project`);
|
|
710
517
|
const worktrees = await worktreesOf(folder);
|
|
711
518
|
const main = worktrees[0]?.folder ?? folder;
|
|
@@ -722,11 +529,8 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
722
529
|
const ours =
|
|
723
530
|
left.made &&
|
|
724
531
|
left.head !== '' &&
|
|
725
|
-
(await git(main,
|
|
726
|
-
!(await git(main
|
|
727
|
-
.split('\n\n')
|
|
728
|
-
.map((block) => block.split('\n'))
|
|
729
|
-
.some((lines) => lines.includes(`branch ${ref}`) && !lines.includes(`worktree ${left.folder}`));
|
|
532
|
+
(await git.resolve(main, ref)) === left.head &&
|
|
533
|
+
!(await git.worktrees(main)).some((tree) => tree.branch === name && tree.folder !== left.folder);
|
|
730
534
|
const commands = [
|
|
731
535
|
`cd ${shellQuoted(main)}`,
|
|
732
536
|
...(listed ? [`git worktree remove ${shellQuoted(left.folder)}`] : []),
|
|
@@ -742,25 +546,17 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
742
546
|
if (worktrees.some((each) => each.name === name)) throw new Error(`a branch ${name} exists already`);
|
|
743
547
|
// The worktrees and the `bridge.yml` Bridge writes are Bridge's, never the repository's, where git reads its
|
|
744
548
|
// exclude (a project that is itself a worktree has its own in the main repository's).
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
if (!existsSync(exclude) || !readFileSync(exclude, 'utf8').includes('/.worktrees/'))
|
|
748
|
-
writeFileSync(exclude, `${existsSync(exclude) ? readFileSync(exclude, 'utf8') : ''}\n/.worktrees/\nbridge.yml\n`);
|
|
749
|
-
const base = await baseOf(folder);
|
|
549
|
+
await git.exclude(folder, ['/.worktrees/', BRIDGE_YML]);
|
|
550
|
+
const base = await git.defaultBranch(folder);
|
|
750
551
|
// From the remote's default branch, fetched now, else as fetched last (offline: bridge#540); its local one only
|
|
751
552
|
// without a remote.
|
|
752
553
|
if (base.remote)
|
|
753
554
|
// Its full ref: a tag of the same name would be fetched in its place, the branch left as it was (plugins#198).
|
|
754
|
-
await
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
`refs/heads/${base.name}`,
|
|
760
|
-
]).catch(() => undefined);
|
|
761
|
-
const from = base.remote && (await resolves(folder, base.ref)) ? base.ref : `refs/heads/${base.name}`;
|
|
762
|
-
const kept = await git(folder, ['branch', '--list', name]);
|
|
763
|
-
const head = await git(folder, ['rev-parse', `${kept ? `refs/heads/${name}` : from}^{commit}`]);
|
|
555
|
+
await git.fetch(folder, { remote: base.remote, ref: `refs/heads/${base.name}` }).catch(() => undefined);
|
|
556
|
+
const from = base.remote && (await git.resolve(folder, base.ref)) ? base.ref : `refs/heads/${base.name}`;
|
|
557
|
+
const kept = (await git.branchNames(folder)).includes(name);
|
|
558
|
+
const head = await git.resolve(folder, kept ? `refs/heads/${name}` : from);
|
|
559
|
+
if (!head) throw new Error(`${kept ? name : from} names no commit`);
|
|
764
560
|
mkdirSync(join(main, '.worktrees'), { recursive: true });
|
|
765
561
|
let worktree = '';
|
|
766
562
|
let file = '';
|
|
@@ -787,14 +583,11 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
787
583
|
}
|
|
788
584
|
}
|
|
789
585
|
try {
|
|
790
|
-
|
|
791
|
-
folder,
|
|
792
|
-
|
|
793
|
-
kept ? ['worktree', 'add', worktree, name] : ['worktree', 'add', '--no-track', '-b', name, worktree, head],
|
|
794
|
-
);
|
|
795
|
-
if (added.code !== 0) {
|
|
586
|
+
try {
|
|
587
|
+
await git.addWorktree(folder, { folder: worktree, branch: name, existing: kept, from: head });
|
|
588
|
+
} catch (error) {
|
|
796
589
|
rmSync(file, { force: true });
|
|
797
|
-
throw new Error(
|
|
590
|
+
throw new Error(reason(error));
|
|
798
591
|
}
|
|
799
592
|
writeAtomic(file, JSON.stringify(claim(true)));
|
|
800
593
|
try {
|
|
@@ -822,93 +615,69 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
822
615
|
return project;
|
|
823
616
|
};
|
|
824
617
|
|
|
825
|
-
/** At most `max` characters of `text`, saying how much was cut. */
|
|
826
|
-
/** At most `max` characters of `text`, never half an emoji (a lone surrogate a model's API refuses, bridge#542), saying
|
|
827
|
-
* how much was cut; `more`: git's output was cut before already. */
|
|
828
|
-
const clip = (text: string, max: number, more = false) => {
|
|
829
|
-
const kept = cutText(text, max);
|
|
830
|
-
return kept === text && !more ? text : `${kept}\n… (${more ? 'more' : text.length - kept.length} characters cut)`;
|
|
831
|
-
};
|
|
832
618
|
const unfenced = (text: string) =>
|
|
833
619
|
text
|
|
834
620
|
.trim()
|
|
835
621
|
.replace(/^```[^\n]*\n([\s\S]*?)\n?```$/, '$1')
|
|
836
622
|
.trim();
|
|
837
|
-
/** A diff for a model: its first `DIFF_BYTES` bytes read from git, cut to `DIFF_CHARS` (a 20 MB file never fills
|
|
838
|
-
* memory, bridge#597). */
|
|
839
|
-
const diffForModel = async (folder: string, args: string[]) => {
|
|
840
|
-
const ran = await host.git(folder, [...plainDiff, ...args], { maxBytes: DIFF_BYTES });
|
|
841
|
-
if (ran.code !== 0 && !ran.cut) throw new Error(ran.stderr.trim() || 'git diff failed');
|
|
842
|
-
return clip(ran.stdout, DIFF_CHARS, ran.cut === true);
|
|
843
|
-
};
|
|
844
|
-
/** Runs git with a message from a file: the host's process never closes stdin. */
|
|
845
|
-
const withFile = async <T>(text: string, work: (file: string) => Promise<T>) => {
|
|
846
|
-
const dir = join(tmpdir(), `bridge-git-${randomUUID()}`);
|
|
847
|
-
mkdirSync(dir, { recursive: true });
|
|
848
|
-
const file = join(dir, 'message.txt');
|
|
849
|
-
writeFileSync(file, text);
|
|
850
|
-
try {
|
|
851
|
-
return await work(file);
|
|
852
|
-
} finally {
|
|
853
|
-
rmSync(dir, { recursive: true, force: true });
|
|
854
|
-
}
|
|
855
|
-
};
|
|
856
623
|
|
|
857
624
|
/** Commits every change in the branch's folder (bridge.yml aside): the message written, else, finishing a merge,
|
|
858
625
|
* git's own, else one a model writes from the staged diff, else the branch's name (`fellBack` says why). Refused
|
|
859
626
|
* while a merge leaves conflicts (bridge#552): their markers would be committed. */
|
|
860
627
|
const commitBranch = async (branch: Branch, node: string, message?: string) => {
|
|
861
628
|
if (!branch.dirty) throw new Error(`${branch.name} has nothing to commit`);
|
|
862
|
-
const conflicted = await git(branch.folder, ['diff', '--name-only', '--diff-filter=U']);
|
|
863
|
-
if (conflicted)
|
|
864
|
-
throw new Error(`${branch.name} has conflicts to resolve first: ${conflicted.split('\n').join(', ')}`);
|
|
865
|
-
await git(branch.folder, ['add', '-A', '--', '.', ':!bridge.yml']);
|
|
866
|
-
let text = message?.trim() ?? '';
|
|
867
|
-
if (!text && (await merging(branch.folder))) {
|
|
868
|
-
const file = await git(branch.folder, ['rev-parse', '--git-path', 'MERGE_MSG']);
|
|
869
|
-
text = readFileSync(resolve(branch.folder, file), 'utf8')
|
|
870
|
-
.split('\n')
|
|
871
|
-
.filter((line) => !line.startsWith('#'))
|
|
872
|
-
.join('\n')
|
|
873
|
-
.trim();
|
|
874
|
-
}
|
|
875
629
|
let fellBack: string | undefined;
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
recent
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
630
|
+
try {
|
|
631
|
+
const done = await gitOf().commit(branch.folder, {
|
|
632
|
+
scope: 'branch',
|
|
633
|
+
exclude: [BRIDGE_YML],
|
|
634
|
+
maxChars: DIFF_CHARS,
|
|
635
|
+
message: message?.trim()
|
|
636
|
+
? message.trim()
|
|
637
|
+
: async ({ mergeMessage, recent, stat, diff }) => {
|
|
638
|
+
if (mergeMessage) return mergeMessage;
|
|
639
|
+
try {
|
|
640
|
+
const prompt = [
|
|
641
|
+
'Write the git commit message for the staged changes below.',
|
|
642
|
+
'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.',
|
|
643
|
+
recent.length
|
|
644
|
+
? `Follow the style of this repository's recent commits (prefix, tense, length):\n${recent.join('\n')}`
|
|
645
|
+
: 'Use the imperative mood.',
|
|
646
|
+
`Files:\n${stat ?? ''}`,
|
|
647
|
+
`Diff:\n${diff}`,
|
|
648
|
+
].join('\n\n');
|
|
649
|
+
const text = unfenced(await host.write(node, prompt, []));
|
|
650
|
+
if (!text) throw new Error('the model wrote nothing');
|
|
651
|
+
return text;
|
|
652
|
+
} catch (error) {
|
|
653
|
+
fellBack = `the message could not be written (${reason(error)})`;
|
|
654
|
+
return branch.name.replace(/[-/]/g, ' ');
|
|
655
|
+
}
|
|
656
|
+
},
|
|
657
|
+
});
|
|
658
|
+
return { message: done.message, ...(fellBack && { fellBack }) };
|
|
659
|
+
} catch (error) {
|
|
660
|
+
if (isRecord(error) && error.code === 'conflict')
|
|
661
|
+
throw new Error(`${branch.name} has ${reason(error)}`);
|
|
662
|
+
throw error;
|
|
663
|
+
}
|
|
897
664
|
};
|
|
898
665
|
const pushBranch = async (branch: Branch, confirmed = false) => {
|
|
899
666
|
if (branch.isDefault && !confirmed)
|
|
900
667
|
throw new Error(`pushing ${branch.name}, the default branch, needs a confirmation`);
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
668
|
+
await gitOf()
|
|
669
|
+
.push(branch.folder, { branch: branch.name })
|
|
670
|
+
.catch((error: unknown) => {
|
|
671
|
+
throw new Error(`${branch.name} is not pushed, git refused: ${reason(error)}`);
|
|
672
|
+
});
|
|
906
673
|
};
|
|
907
674
|
const pullBranch = async (branch: Branch) => {
|
|
908
675
|
if (!branch.upstream) throw new Error(`${branch.name} has no upstream to pull from`);
|
|
909
|
-
await
|
|
910
|
-
|
|
911
|
-
|
|
676
|
+
await gitOf()
|
|
677
|
+
.pullFastForward(branch.folder)
|
|
678
|
+
.catch((error: unknown) => {
|
|
679
|
+
throw new Error(`${branch.name} is not pulled, git refused: ${reason(error)}`);
|
|
680
|
+
});
|
|
912
681
|
};
|
|
913
682
|
|
|
914
683
|
/** The repository's pull request template, where GitHub looks for one. */
|
|
@@ -929,7 +698,7 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
929
698
|
|
|
930
699
|
/** Its pull request, made once (a draft, through `github`), its texts written by a model from its commits, its diff,
|
|
931
700
|
* the template and the conversations of `sessions`; its changes committed and pushed first. */
|
|
932
|
-
const pullRequest = async (branch: Branch, main: string, node: string, sessions: string[]) => {
|
|
701
|
+
const pullRequest = async (branch: Branch, main: string, node: string, sessions: string[], commit = true) => {
|
|
933
702
|
if (branch.main || branch.isDefault) throw new Error('the default branch has no pull request: start a branch');
|
|
934
703
|
const github = host.github();
|
|
935
704
|
if (!github)
|
|
@@ -939,7 +708,8 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
939
708
|
repositories.set(main, { at: Date.now(), repository });
|
|
940
709
|
if (!repository)
|
|
941
710
|
throw new Error(`${branch.name} has no GitHub repository gh knows: its remote is not one on github.com`);
|
|
942
|
-
|
|
711
|
+
// `commit: false` (the Commit changes dialog committed what goes in): the rest stays uncommitted.
|
|
712
|
+
const committed = commit && branch.dirty ? await commitBranch(branch, node) : undefined;
|
|
943
713
|
await pushBranch(branch);
|
|
944
714
|
const open = (await github.pullRequestsForBranch({ repository, branch: branch.name })).find(
|
|
945
715
|
({ state }) => state === 'open' || state === 'draft',
|
|
@@ -949,9 +719,11 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
949
719
|
found.set(`${repository}\0${branch.name}`, { at: Date.now(), prs: [{ url: open.url, state: open.state }] });
|
|
950
720
|
return { url: open.url, ...(committed && { committed }) };
|
|
951
721
|
}
|
|
952
|
-
const
|
|
953
|
-
const
|
|
954
|
-
const
|
|
722
|
+
const git = gitOf();
|
|
723
|
+
const base = await git.defaultBranch(branch.folder);
|
|
724
|
+
const commits = (await git.history(branch.folder, { max: 1000, range: `${base.ref}..HEAD` })).reverse();
|
|
725
|
+
const log = commits.map(({ subject, body }) => `${subject}\n\n${body}`).join('\n');
|
|
726
|
+
const subjects = commits.map(({ subject }) => subject).join('\n');
|
|
955
727
|
const template = pullRequestTemplate(branch.folder);
|
|
956
728
|
let title = '';
|
|
957
729
|
let body = '';
|
|
@@ -965,7 +737,7 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
965
737
|
? `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}`
|
|
966
738
|
: 'The description: a short summary, then what changed.',
|
|
967
739
|
`Commits (oldest first):\n${log}`,
|
|
968
|
-
`Diff against ${base.name}:\n${await
|
|
740
|
+
`Diff against ${base.name}:\n${await git.rangeDiff(branch.folder, `${base.ref}...HEAD`, DIFF_CHARS)}`,
|
|
969
741
|
].join('\n\n');
|
|
970
742
|
const [first = '', ...rest] = unfenced(await host.write(node, prompt, sessions)).split('\n');
|
|
971
743
|
title = first.replace(/^#+\s*|^title:\s*/i, '').trim();
|
|
@@ -990,34 +762,6 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
990
762
|
return { url, title, ...(committed && { committed }), ...(fellBack && { fellBack }) };
|
|
991
763
|
};
|
|
992
764
|
|
|
993
|
-
/** The repositories of their own (a `.git`) inside the folders git ignores in `folder` (bridge#523): deleting the
|
|
994
|
-
* folder would delete them, with their commits. */
|
|
995
|
-
const nestedRepositories = async (folder: string) => {
|
|
996
|
-
const ignored = (
|
|
997
|
-
await git(folder, ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory', '-z'])
|
|
998
|
-
)
|
|
999
|
-
.split('\0')
|
|
1000
|
-
.filter(Boolean);
|
|
1001
|
-
const nested: string[] = [];
|
|
1002
|
-
// Every level down each ignored folder (a repository nine levels under node_modules is one too), read without
|
|
1003
|
-
// blocking the worker: a large ignored tree takes its time, never the other routes'.
|
|
1004
|
-
const walk = async (path: string): Promise<void> => {
|
|
1005
|
-
if (existsSync(join(path, '.git'))) return void nested.push(relative(folder, path));
|
|
1006
|
-
let entries;
|
|
1007
|
-
try {
|
|
1008
|
-
entries = await readdir(path, { withFileTypes: true });
|
|
1009
|
-
} catch {
|
|
1010
|
-
return;
|
|
1011
|
-
}
|
|
1012
|
-
for (const entry of entries) if (entry.isDirectory() && entry.name !== '.git') await walk(join(path, entry.name));
|
|
1013
|
-
};
|
|
1014
|
-
for (const each of ignored) {
|
|
1015
|
-
const path = join(folder, each);
|
|
1016
|
-
if (lstatSync(path, { throwIfNoEntry: false })?.isDirectory()) await walk(path);
|
|
1017
|
-
}
|
|
1018
|
-
return nested;
|
|
1019
|
-
};
|
|
1020
|
-
|
|
1021
765
|
/** Deletes a branch's folder, refused while anything uses it or holds work. */
|
|
1022
766
|
const removeBranch = async (folder: string, branch: Branch, worktrees: Worktree[]) => {
|
|
1023
767
|
if (branch.main) throw new Error('the project’s own folder is never deleted');
|
|
@@ -1026,14 +770,13 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
1026
770
|
const dead = unfinished(claimed, claim);
|
|
1027
771
|
if (claimed !== undefined && !dead)
|
|
1028
772
|
throw new Error(`${branch.name} is still being made: delete it once its creation is done`);
|
|
1029
|
-
const
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
);
|
|
1033
|
-
|
|
1034
|
-
if (branch.dirty || unpushed)
|
|
773
|
+
const git = gitOf();
|
|
774
|
+
const status = await git.branchStatus(branch.folder).catch(() => undefined);
|
|
775
|
+
if (status?.unpushed === undefined)
|
|
776
|
+
throw new Error(`${branch.name} is not deleted: git cannot tell whether its commits are pushed`);
|
|
777
|
+
if (branch.dirty || status.unpushed)
|
|
1035
778
|
throw new Error(`${branch.name} holds work that is not pushed: open its pull request first`);
|
|
1036
|
-
const nested = await nestedRepositories(branch.folder);
|
|
779
|
+
const nested = await git.nestedRepositories(branch.folder);
|
|
1037
780
|
if (nested.length > 0)
|
|
1038
781
|
throw new Error(
|
|
1039
782
|
`${branch.name} is not deleted: its folder holds a repository of its own git does not track (${nested.join(', ')}); move it out first`,
|
|
@@ -1050,6 +793,7 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
1050
793
|
const project = await listedProject(node);
|
|
1051
794
|
if (!project) return { project: null, branches: [] };
|
|
1052
795
|
if (!project.repository) return { project: { title: project.title, folder: project.folder }, repository: false };
|
|
796
|
+
if (!host.git()) return { project: { title: project.title, folder: project.folder }, git: 'missing', branches: [] };
|
|
1053
797
|
const { branches, worktrees, code, refreshing } = await listBranches(project.folder);
|
|
1054
798
|
const hostLevel = hostLevelOf(worktrees, code);
|
|
1055
799
|
const main = worktrees[0]?.folder ?? project.folder;
|
|
@@ -1063,6 +807,9 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
1063
807
|
return {
|
|
1064
808
|
project: { title: project.title, folder: project.folder },
|
|
1065
809
|
github: host.github() ? 'ready' : 'missing',
|
|
810
|
+
// Its pull request honours `commit: false` (the `git` plugin's page offers a session's commit then its pull
|
|
811
|
+
// request only to a Project that says so: an older one committed the whole branch first).
|
|
812
|
+
prWithoutCommit: true,
|
|
1066
813
|
...(hostLevel && { hostLevel }),
|
|
1067
814
|
branches,
|
|
1068
815
|
...(making.length > 0 && { jobs: making }),
|
|
@@ -1166,7 +913,7 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
1166
913
|
result = await run(name, 'pull', async () => (await pullBranch(await now()), { pulled: name }));
|
|
1167
914
|
else if (action === 'pr')
|
|
1168
915
|
result = await run(name, 'pr', async () => {
|
|
1169
|
-
const { url, ...made } = await pullRequest(await now(), main, node, await sessionsOf());
|
|
916
|
+
const { url, ...made } = await pullRequest(await now(), main, node, await sessionsOf(), input.commit !== false);
|
|
1170
917
|
return { pr: url, ...made };
|
|
1171
918
|
});
|
|
1172
919
|
else if (action === 'remove') {
|
|
@@ -1178,9 +925,59 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
1178
925
|
return { ...(await view(node)), result };
|
|
1179
926
|
};
|
|
1180
927
|
|
|
928
|
+
/** Branch `name` of project `node`, as the Commit changes dialog reads it: its repository's top, the branch's folder in
|
|
929
|
+
* it, and its changes (bridge.yml aside), each path relative to the top. */
|
|
930
|
+
const changesOf = async (node: string, name: string) => {
|
|
931
|
+
const git = gitOf();
|
|
932
|
+
const project = await projectOf(node);
|
|
933
|
+
const branch = (await worktreesOf(project.folder)).find((each) => each.name === name);
|
|
934
|
+
if (!branch) throw new Error(`no branch ${name} in ${project.title}`);
|
|
935
|
+
const repository = await git.repositoryAt(branch.folder);
|
|
936
|
+
if (!repository) throw new Error(`${branch.folder} is in no git repository`);
|
|
937
|
+
const own = `${repository.prefix}${BRIDGE_YML}`;
|
|
938
|
+
const files = (await git.status(branch.folder)).map(({ path }) => path).filter((path) => path !== own);
|
|
939
|
+
return { git, branch, top: repository.top, files };
|
|
940
|
+
};
|
|
941
|
+
/** What the dialog shows of branch `name`: every uncommitted file with its counts, the diff (past `DIFF_FILES_MAX`
|
|
942
|
+
* files none, `byFile`; cut short past `DIFF_MAX`, `cut`), and the branch; with `path`, that file's diff only. */
|
|
943
|
+
const changes = async (node: string, name: string, path?: string) => {
|
|
944
|
+
const { git, branch, top, files } = await changesOf(node, name);
|
|
945
|
+
if (path !== undefined) {
|
|
946
|
+
if (!files.includes(path)) throw new Error(`${path} has no uncommitted change on ${name}`);
|
|
947
|
+
const { patch, cut } = await git.diff(top, { paths: [path], maxChars: DIFF_MAX });
|
|
948
|
+
return { repository: top, path, diff: patch, ...(cut && { cut: true }) };
|
|
949
|
+
}
|
|
950
|
+
const counts = await git.counts(top, files);
|
|
951
|
+
const whole = files.length <= DIFF_FILES_MAX;
|
|
952
|
+
const diff = whole ? await git.diff(top, { paths: files, maxChars: DIFF_MAX }) : { patch: '', cut: false };
|
|
953
|
+
const status = await git.branchStatus(branch.folder, { exclude: [BRIDGE_YML] }).catch(() => undefined);
|
|
954
|
+
return {
|
|
955
|
+
repository: top,
|
|
956
|
+
files: files.map((each) => ({ path: each, pending: true, ...counts[each] })),
|
|
957
|
+
diff: diff.patch,
|
|
958
|
+
...(!whole && { byFile: true }),
|
|
959
|
+
...(diff.cut && { cut: true }),
|
|
960
|
+
branch: status && {
|
|
961
|
+
name,
|
|
962
|
+
isDefault: status.isDefault,
|
|
963
|
+
remote: status.remote,
|
|
964
|
+
upstream: !!status.upstream,
|
|
965
|
+
unpushed: status.unpushed ?? 0,
|
|
966
|
+
},
|
|
967
|
+
...(status?.merging && { merging: true }),
|
|
968
|
+
};
|
|
969
|
+
};
|
|
970
|
+
|
|
1181
971
|
return {
|
|
1182
972
|
view,
|
|
1183
973
|
act,
|
|
974
|
+
changes,
|
|
975
|
+
/** Lines `from`–`to` of an uncommitted file of branch `name`, as it is now (the dialog's folds). */
|
|
976
|
+
lines: async (node: string, name: string, path: string, from: number, to: number) => {
|
|
977
|
+
const { git, top, files } = await changesOf(node, name);
|
|
978
|
+
if (!files.includes(path)) throw new Error(`${path} has no uncommitted change on ${name}`);
|
|
979
|
+
return { path, lines: await git.lines(top, path, from, to) };
|
|
980
|
+
},
|
|
1184
981
|
/** A session's new branch in project `node` (Sessions, research-083): made as New makes one; `existing`: the folder
|
|
1185
982
|
* of that branch, its name kept. */
|
|
1186
983
|
newBranch: async ({
|
|
@@ -1206,23 +1003,4 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
1206
1003
|
};
|
|
1207
1004
|
}
|
|
1208
1005
|
|
|
1209
|
-
/** A new file's lines (a last one without a newline counts), its first `READ_CAP` bytes only; a binary has none. */
|
|
1210
|
-
const newLines = async (path: string) => {
|
|
1211
|
-
try {
|
|
1212
|
-
const file = await open(path);
|
|
1213
|
-
try {
|
|
1214
|
-
const { buffer, bytesRead } = await file.read(Buffer.alloc(READ_CAP), 0, READ_CAP, 0);
|
|
1215
|
-
const text = buffer.subarray(0, bytesRead);
|
|
1216
|
-
if (text.includes(0)) return 0;
|
|
1217
|
-
let lines = 0;
|
|
1218
|
-
for (const byte of text) if (byte === 10) lines++;
|
|
1219
|
-
return bytesRead > 0 && text[bytesRead - 1] !== 10 ? lines + 1 : lines;
|
|
1220
|
-
} finally {
|
|
1221
|
-
await file.close();
|
|
1222
|
-
}
|
|
1223
|
-
} catch {
|
|
1224
|
-
return 0;
|
|
1225
|
-
}
|
|
1226
|
-
};
|
|
1227
|
-
|
|
1228
1006
|
export type Branches = ReturnType<typeof createBranches>;
|
package/browser/branches.tsx
CHANGED
|
@@ -2,13 +2,15 @@
|
|
|
2
2
|
// branch in its worktree (`.worktrees/<name>`), one line each in the kit's Table: its name, then marks in slots of their
|
|
3
3
|
// own (Active, its commits behind | ahead of the default branch, its uncommitted changes as GitHub's diffstat, its pull
|
|
4
4
|
// request; commits to push or pull show through the Git button), then its actions, right-aligned in one order: the Git
|
|
5
|
-
// button and its menu (
|
|
5
|
+
// button and its menu (the `git` plugin's, filling `project.branch-actions`: its commits through the one Commit changes
|
|
6
|
+
// dialog, bridge-plugins#256), Activate, and "…" for the rest (Delete, with why it is
|
|
6
7
|
// refused). New branch starts one from the default branch; a selected branch takes a prompt whose session works on it.
|
|
7
8
|
// Activate makes a branch the active one: everything Bridge loads from the project (its plugins, host-level code such as
|
|
8
9
|
// the Bridge UI kit) follows it, without a restart. Data and actions from this plugin's `/branches` routes
|
|
9
10
|
// (../branches.ts, bridgebrew/bridge#557). New, Push, Pull, Create PR and Activate may run on past their route: the
|
|
10
11
|
// row says which runs, then why it failed, and the screen reads the branches again until it ends. Without the GitHub
|
|
11
|
-
// plugin, every git action works and a notice offers to install it for pull requests
|
|
12
|
+
// plugin, every git action works and a notice offers to install it for pull requests; without the Git plugin, the
|
|
13
|
+
// screen offers to install it.
|
|
12
14
|
import * as React from 'react';
|
|
13
15
|
import {
|
|
14
16
|
Badge,
|
|
@@ -43,12 +45,45 @@ import {
|
|
|
43
45
|
import type { Context } from 'cordis';
|
|
44
46
|
import type {} from '@bridge/ui-renderer/client';
|
|
45
47
|
import { SessionPrompt } from '@bridgebrew/session-ui/prompt';
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
48
|
+
|
|
49
|
+
/** What a Branches route lists of a branch (the `git` plugin's Git button reads it whole). */
|
|
50
|
+
export interface GitBranch {
|
|
51
|
+
name: string;
|
|
52
|
+
folder: string;
|
|
53
|
+
main: boolean;
|
|
54
|
+
dirty: number;
|
|
55
|
+
diff: { files: number; additions: number; deletions: number };
|
|
56
|
+
ahead: number;
|
|
57
|
+
behindDefault: number;
|
|
58
|
+
unpushed: number;
|
|
59
|
+
behind: number;
|
|
60
|
+
upstream: boolean;
|
|
61
|
+
remote: boolean;
|
|
62
|
+
isDefault: boolean;
|
|
63
|
+
prOpen: boolean;
|
|
64
|
+
pullRequests?: boolean;
|
|
65
|
+
prState?: 'open' | 'draft' | 'merged' | 'closed';
|
|
66
|
+
prNumber?: number;
|
|
67
|
+
unknown?: boolean;
|
|
68
|
+
active: boolean;
|
|
69
|
+
pr?: string;
|
|
70
|
+
}
|
|
71
|
+
type BranchesRoute = (slug: string, node: string, action?: string) => string;
|
|
72
|
+
interface BranchesAnswer {
|
|
73
|
+
branches: GitBranch[];
|
|
74
|
+
github?: 'ready' | 'missing';
|
|
75
|
+
}
|
|
76
|
+
/** What `project.branch-actions`' entries get (contract `project` 1.1): a branch row's, its answers back. */
|
|
77
|
+
export interface BranchActionsProps {
|
|
78
|
+
slug: string;
|
|
79
|
+
node: string;
|
|
80
|
+
branch: GitBranch;
|
|
81
|
+
route: BranchesRoute;
|
|
82
|
+
disabled: boolean;
|
|
83
|
+
onAnswer: (answer: BranchesAnswer) => void;
|
|
84
|
+
}
|
|
85
|
+
/** The renderer's `renderSlot` for this screen's child slot. */
|
|
86
|
+
export type RenderBranchActions = (name: 'project.branch-actions', props: BranchActionsProps) => React.ReactNode;
|
|
52
87
|
|
|
53
88
|
/** This plugin's Branches route of project `node` in workspace `slug`, or one of its actions. */
|
|
54
89
|
export const projectBranchesRoute: BranchesRoute = (slug, node, action) =>
|
|
@@ -238,7 +273,16 @@ export function PrPill({
|
|
|
238
273
|
);
|
|
239
274
|
}
|
|
240
275
|
|
|
241
|
-
export function Branches({
|
|
276
|
+
export function Branches({
|
|
277
|
+
ctx,
|
|
278
|
+
node,
|
|
279
|
+
renderSlot,
|
|
280
|
+
}: {
|
|
281
|
+
ctx: Context;
|
|
282
|
+
node: string;
|
|
283
|
+
/** Draws each row's `project.branch-actions` (the `git` plugin's Git button); none in a test. */
|
|
284
|
+
renderSlot?: RenderBranchActions | undefined;
|
|
285
|
+
}) {
|
|
242
286
|
const { toast } = useToast();
|
|
243
287
|
const slug = ctx.workspace.slug;
|
|
244
288
|
const [view, setView] = React.useState<View>();
|
|
@@ -248,7 +292,10 @@ export function Branches({ ctx, node }: { ctx: Context; node: string }) {
|
|
|
248
292
|
const [selected, setSelected] = React.useState<string>();
|
|
249
293
|
const [running, setRunning] = React.useState<{ action: string; name?: string }>();
|
|
250
294
|
const [installing, setInstalling] = React.useState(false);
|
|
295
|
+
const [gitMissing, setGitMissing] = React.useState(false);
|
|
251
296
|
const [reads, setReads] = React.useState(0);
|
|
297
|
+
/** Counts the reads that ended, read or failed: the poll's next timer starts from there (plugins#272). */
|
|
298
|
+
const [settled, setSettled] = React.useState(0);
|
|
252
299
|
React.useEffect(() => {
|
|
253
300
|
let gone = false;
|
|
254
301
|
fetch(projectBranchesRoute(slug, node), { cache: 'no-store' })
|
|
@@ -256,22 +303,39 @@ export function Branches({ ctx, node }: { ctx: Context; node: string }) {
|
|
|
256
303
|
.then((body: unknown) => {
|
|
257
304
|
if (gone) return;
|
|
258
305
|
// A project that is not a git repository of its own has no branches: that state, in place of the list.
|
|
259
|
-
|
|
306
|
+
// These three answers end the polling: no job of a list they replace runs on.
|
|
307
|
+
if (isRecord(body) && body.repository === false && isRecord(body.project)) {
|
|
308
|
+
setView(undefined);
|
|
260
309
|
return setError(`${String(body.project.title)} is not a git repository`);
|
|
310
|
+
}
|
|
261
311
|
// A node no bridge.yml lists as a project (one made before projects had one): no branches either.
|
|
262
|
-
if (isRecord(body) && body.project === null)
|
|
312
|
+
if (isRecord(body) && body.project === null) {
|
|
313
|
+
setView(undefined);
|
|
263
314
|
return setError('No bridge.yml lists this project: Bridge shows no branches for it');
|
|
315
|
+
}
|
|
316
|
+
// A read that failed before (a poll while the project plugin reloaded) is over.
|
|
317
|
+
setError('');
|
|
318
|
+
// No Git plugin: nothing to list; its install offered.
|
|
319
|
+
if (isRecord(body) && body.git === 'missing') {
|
|
320
|
+
setView(undefined);
|
|
321
|
+
return setGitMissing(true);
|
|
322
|
+
}
|
|
323
|
+
setGitMissing(false);
|
|
264
324
|
// The host's own answer: typed once where it is read.
|
|
265
325
|
setView(body as View);
|
|
266
326
|
})
|
|
267
327
|
.catch((cause: unknown) => {
|
|
268
328
|
if (!gone) setError(cause instanceof Error ? cause.message : String(cause));
|
|
329
|
+
})
|
|
330
|
+
.finally(() => {
|
|
331
|
+
if (!gone) setSettled((count) => count + 1);
|
|
269
332
|
});
|
|
270
333
|
return () => {
|
|
271
334
|
gone = true;
|
|
272
335
|
};
|
|
273
336
|
}, [slug, node, reads]);
|
|
274
|
-
// While an action runs on past its route, the branches are read again until it ends
|
|
337
|
+
// While an action runs on past its route, the branches are read again until it ends: each read once the one before
|
|
338
|
+
// it ended, read or failed (a failed one keeps the last list's jobs, so the polling goes on).
|
|
275
339
|
const runsOn =
|
|
276
340
|
!!view?.refreshing ||
|
|
277
341
|
!!view?.branches.some((branch) => branch.job?.running) ||
|
|
@@ -280,23 +344,23 @@ export function Branches({ ctx, node }: { ctx: Context; node: string }) {
|
|
|
280
344
|
if (!runsOn) return;
|
|
281
345
|
const timer = setTimeout(() => setReads((count) => count + 1), POLL_MS);
|
|
282
346
|
return () => clearTimeout(timer);
|
|
283
|
-
}, [runsOn,
|
|
284
|
-
/** Installs
|
|
285
|
-
const
|
|
347
|
+
}, [runsOn, settled]);
|
|
348
|
+
/** Installs a plugin in this workspace (the Plugins screen's own install), then reads the branches again. */
|
|
349
|
+
const install = async (source: string, title: string) => {
|
|
286
350
|
setInstalling(true);
|
|
287
351
|
try {
|
|
288
352
|
const res = await fetch(`/_bridge/workspaces/${encodeURIComponent(slug)}/plugins/install`, {
|
|
289
353
|
method: 'POST',
|
|
290
354
|
headers: { 'content-type': 'application/json' },
|
|
291
|
-
body: JSON.stringify({ source
|
|
355
|
+
body: JSON.stringify({ source }),
|
|
292
356
|
});
|
|
293
357
|
await readJson(res);
|
|
294
|
-
toast({ variant: 'success', title:
|
|
358
|
+
toast({ variant: 'success', title: `${title} installed` });
|
|
295
359
|
setReads((count) => count + 1);
|
|
296
360
|
} catch (cause) {
|
|
297
361
|
toast({
|
|
298
362
|
variant: 'error',
|
|
299
|
-
title:
|
|
363
|
+
title: `${title} is not installed`,
|
|
300
364
|
description: cause instanceof Error ? cause.message : String(cause),
|
|
301
365
|
});
|
|
302
366
|
} finally {
|
|
@@ -317,6 +381,8 @@ export function Branches({ ctx, node }: { ctx: Context; node: string }) {
|
|
|
317
381
|
)) as View & {
|
|
318
382
|
result?: { name?: string; running?: string; left?: { plugin: string; reason: string }[] };
|
|
319
383
|
};
|
|
384
|
+
// A list read: an error a poll met meanwhile is over.
|
|
385
|
+
setError('');
|
|
320
386
|
setView(answer);
|
|
321
387
|
if (action === 'new') {
|
|
322
388
|
setTitle('');
|
|
@@ -347,6 +413,15 @@ export function Branches({ ctx, node }: { ctx: Context; node: string }) {
|
|
|
347
413
|
}
|
|
348
414
|
};
|
|
349
415
|
if (error) return <EmptyState icon={<Icon name="git-branch" size={20} />} title={error} fill />;
|
|
416
|
+
if (gitMissing)
|
|
417
|
+
return (
|
|
418
|
+
<EmptyState icon={<Icon name="git-branch" size={20} />} title="Branches need the Git plugin" fill>
|
|
419
|
+
<p>Git runs every branch action: its changes, commits, pushes and pull requests.</p>
|
|
420
|
+
<Button variant="primary" disabled={installing} onClick={() => void install('@bridgebrew/git', 'Git')}>
|
|
421
|
+
{installing ? 'Installing…' : 'Install Git'}
|
|
422
|
+
</Button>
|
|
423
|
+
</EmptyState>
|
|
424
|
+
);
|
|
350
425
|
if (!view) return <section aria-label="Screen" className="flex h-full min-h-0 flex-col" />;
|
|
351
426
|
const busy = running !== undefined;
|
|
352
427
|
const spinning = (action: string, branch?: string) =>
|
|
@@ -381,7 +456,12 @@ export function Branches({ ctx, node }: { ctx: Context; node: string }) {
|
|
|
381
456
|
<span className="min-w-0 flex-1 break-words">
|
|
382
457
|
Pull requests need the GitHub plugin: every other action works without it.
|
|
383
458
|
</span>
|
|
384
|
-
<Button
|
|
459
|
+
<Button
|
|
460
|
+
size="sm"
|
|
461
|
+
variant="outline"
|
|
462
|
+
disabled={installing}
|
|
463
|
+
onClick={() => void install('@bridgebrew/github', 'GitHub')}
|
|
464
|
+
>
|
|
385
465
|
{installing ? 'Installing…' : 'Install GitHub'}
|
|
386
466
|
</Button>
|
|
387
467
|
</p>
|
|
@@ -493,17 +573,16 @@ export function Branches({ ctx, node }: { ctx: Context; node: string }) {
|
|
|
493
573
|
// Its menus and dialogs are portals: their clicks reach the row through React, never selecting it.
|
|
494
574
|
onClick={(event) => event.stopPropagation()}
|
|
495
575
|
>
|
|
496
|
-
|
|
497
|
-
slug
|
|
498
|
-
node
|
|
576
|
+
{renderSlot?.('project.branch-actions', {
|
|
577
|
+
slug,
|
|
578
|
+
node,
|
|
499
579
|
// Without the GitHub plugin, no pull request is offered: the notice above says why (bridge#557).
|
|
500
|
-
branch
|
|
501
|
-
route
|
|
502
|
-
disabled
|
|
503
|
-
onAnswer
|
|
504
|
-
setView((was) => (was ? { ...was, branches: answer.branches } : was))
|
|
505
|
-
|
|
506
|
-
/>
|
|
580
|
+
branch: view.github === 'missing' ? { ...branch, pullRequests: false } : branch,
|
|
581
|
+
route: projectBranchesRoute,
|
|
582
|
+
disabled: busy || !!branch.job?.running,
|
|
583
|
+
onAnswer: (answer) =>
|
|
584
|
+
setView((was) => (was ? { ...was, branches: answer.branches } : was)),
|
|
585
|
+
})}
|
|
507
586
|
<Button
|
|
508
587
|
size="sm"
|
|
509
588
|
variant="outline"
|
package/browser/browser.tsx
CHANGED
|
@@ -10,7 +10,7 @@ import * as React from 'react';
|
|
|
10
10
|
import { Button, EmptyState, Icon, List, ListItem, isRecord } from '@bridge/ui';
|
|
11
11
|
import type { Context } from 'cordis';
|
|
12
12
|
import type {} from '@bridge/ui-renderer/client';
|
|
13
|
-
import { Branches } from './branches.tsx';
|
|
13
|
+
import { Branches, type RenderBranchActions } from './branches.tsx';
|
|
14
14
|
import { MobileProjects } from './mobile.tsx';
|
|
15
15
|
import { NewProject } from './new-project.tsx';
|
|
16
16
|
import { Overview } from './overview.tsx';
|
|
@@ -255,11 +255,31 @@ export function apply(ctx: Context) {
|
|
|
255
255
|
<Dialog ctx={ctx} requests={requests} />
|
|
256
256
|
));
|
|
257
257
|
// Its root screens (package.json): a project node's Overview and Branches, shown where chosen, and Projects.
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
258
|
+
// It declares `project.branch-actions`, each branch row's actions, which the `git` plugin fills (bridge-plugins#256): a
|
|
259
|
+
// list not in the shell's slot map, so typed here.
|
|
260
|
+
// oxlint-disable-next-line bridge/no-new-unchecked-cast -- typing: slots.register's overloads do not name this screen's children
|
|
261
|
+
const slots = ctx.slots as unknown as {
|
|
262
|
+
register(
|
|
263
|
+
options: {
|
|
264
|
+
name: 'screen';
|
|
265
|
+
key: string;
|
|
266
|
+
children: { 'project.branch-actions': { kind: 'list'; scope: 'root' } };
|
|
267
|
+
},
|
|
268
|
+
render: (props: { node: string; screen: string; renderSlot: RenderBranchActions }) => React.ReactNode,
|
|
269
|
+
): void;
|
|
270
|
+
};
|
|
271
|
+
slots.register(
|
|
272
|
+
{
|
|
273
|
+
name: 'screen',
|
|
274
|
+
key: name,
|
|
275
|
+
children: { 'project.branch-actions': { kind: 'list', scope: 'root' } },
|
|
276
|
+
},
|
|
277
|
+
({ node, screen, renderSlot }) => {
|
|
278
|
+
const root = screen.split('/')[0];
|
|
279
|
+
if (root === 'overview') return <Overview ctx={ctx} node={node} />;
|
|
280
|
+
if (root === 'branches') return <Branches ctx={ctx} node={node} renderSlot={renderSlot} />;
|
|
281
|
+
return <Projects ctx={ctx} node={node} requests={requests} />;
|
|
282
|
+
},
|
|
283
|
+
);
|
|
264
284
|
ctx.slots.register({ name: 'mobileScreen', key: name }, () => <MobileProjects ctx={ctx} />);
|
|
265
285
|
}
|
package/names.ts
CHANGED
|
@@ -14,13 +14,24 @@ export const nameOfUrl = (url: string) =>
|
|
|
14
14
|
.replace(/[^\w.-]/g, '-')
|
|
15
15
|
.replace(/^[.-]+/, '');
|
|
16
16
|
|
|
17
|
+
/** The letters NFKD leaves whole (no base letter and mark to split them into), spelled in plain Latin (plugins#217). */
|
|
18
|
+
const LETTERS: Record<string, string> = { ß: 'ss', æ: 'ae', œ: 'oe', ø: 'o', ł: 'l', đ: 'd', ð: 'd', þ: 'th', ı: 'i' };
|
|
19
|
+
/** `text` lowercase in plain Latin letters where it has them: those letters spelled out, then accents dropped
|
|
20
|
+
* (`Straße Łódź` → `strasse lodz`). */
|
|
21
|
+
export const foldLetters = (text: string) =>
|
|
22
|
+
text
|
|
23
|
+
// ʼn first: NFKD splits it into an apostrophe and `n`, which would split the word.
|
|
24
|
+
.replace(/ʼn/g, 'n')
|
|
25
|
+
// NFKD before the rest: it reveals letters (`Ǽ` → `Æ` + accent, `𝐒` → `S`) the table and the lowercase then see.
|
|
26
|
+
.normalize('NFKD')
|
|
27
|
+
.toLowerCase()
|
|
28
|
+
.replace(/[ßæœøłđðþı]/g, (letter) => LETTERS[letter] ?? letter)
|
|
29
|
+
.replace(/[\u0300-\u036f]/g, '');
|
|
30
|
+
|
|
17
31
|
/** A project's folder name from its title, which may be anything: `Test git` → `test-git`, `Café` → `cafe`. Empty
|
|
18
32
|
* when nothing of it fits a folder name (letters, digits, `_ - .`, at most 100). */
|
|
19
33
|
export const folderOf = (title: string) =>
|
|
20
|
-
title
|
|
21
|
-
.normalize('NFKD')
|
|
22
|
-
.replace(/[̀-ͯ]/g, '')
|
|
23
|
-
.toLowerCase()
|
|
34
|
+
foldLetters(title)
|
|
24
35
|
.replace(/[^\w.-]+/g, '-')
|
|
25
36
|
.replace(/-{2,}/g, '-')
|
|
26
37
|
.replace(/^[.-]+|-+$/g, '')
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bridgebrew/project",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.12",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "A project is a folder of work with its bridge.yml, and a node with its own sessions: code, documents, anything; Bridge plugins can be made there too.",
|
|
6
6
|
"keywords": [
|
|
@@ -21,8 +21,38 @@
|
|
|
21
21
|
"domain": "development",
|
|
22
22
|
"server": "./server.ts",
|
|
23
23
|
"browser": "./browser/browser.tsx",
|
|
24
|
-
"
|
|
25
|
-
"
|
|
24
|
+
"contracts": {
|
|
25
|
+
"provides": {
|
|
26
|
+
"project": {
|
|
27
|
+
"version": "1.1",
|
|
28
|
+
"data": [
|
|
29
|
+
"folder"
|
|
30
|
+
],
|
|
31
|
+
"routes": [
|
|
32
|
+
"/branches",
|
|
33
|
+
"/projects"
|
|
34
|
+
],
|
|
35
|
+
"slots": [
|
|
36
|
+
"branch-actions"
|
|
37
|
+
]
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
"uses": {
|
|
41
|
+
"storage": {
|
|
42
|
+
"version": "1.0"
|
|
43
|
+
},
|
|
44
|
+
"sessions": {
|
|
45
|
+
"version": "1.0",
|
|
46
|
+
"optional": true
|
|
47
|
+
},
|
|
48
|
+
"github": {
|
|
49
|
+
"version": "1.0",
|
|
50
|
+
"optional": true
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
"dataVersions": {
|
|
55
|
+
"folder": 1
|
|
26
56
|
},
|
|
27
57
|
"screen": [
|
|
28
58
|
{
|
|
@@ -86,13 +116,14 @@
|
|
|
86
116
|
"/branches/push": 120000,
|
|
87
117
|
"/branches/pull": 120000,
|
|
88
118
|
"/branches/pr": 120000,
|
|
89
|
-
"/branches/remove": 120000
|
|
119
|
+
"/branches/remove": 120000,
|
|
120
|
+
"/branches/changes": 60000
|
|
90
121
|
},
|
|
91
122
|
"provenance": "official",
|
|
92
123
|
"placement": "workspace"
|
|
93
124
|
},
|
|
94
125
|
"dependencies": {
|
|
95
|
-
"@bridgebrew/session-ui": "0.0.
|
|
126
|
+
"@bridgebrew/session-ui": "0.0.2",
|
|
96
127
|
"zod": "4.6.5"
|
|
97
128
|
},
|
|
98
129
|
"peerDependencies": {
|
|
@@ -106,6 +137,6 @@
|
|
|
106
137
|
"typecheck": "bridge plugin check ."
|
|
107
138
|
},
|
|
108
139
|
"engines": {
|
|
109
|
-
"bridge": ">=0.0.1-nightly.
|
|
140
|
+
"bridge": ">=0.0.1-nightly.20261123.1"
|
|
110
141
|
}
|
|
111
142
|
}
|
package/server.ts
CHANGED
|
@@ -19,7 +19,8 @@ import { readdirSync, realpathSync } from 'node:fs';
|
|
|
19
19
|
import { isAbsolute, join, relative, resolve } from 'node:path';
|
|
20
20
|
import type { Context } from 'cordis';
|
|
21
21
|
import { z } from 'zod';
|
|
22
|
-
import {
|
|
22
|
+
import type { GitService } from '@bridgebrew/git/contract.ts';
|
|
23
|
+
import { createBranches, type GitHubLike } from './branches.ts';
|
|
23
24
|
|
|
24
25
|
const folder = z.strictObject({ path: z.string(), title: z.string() });
|
|
25
26
|
type Folder = z.infer<typeof folder>;
|
|
@@ -46,7 +47,7 @@ const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
|
46
47
|
const hidden = new Set(['node_modules', '.git', '.bridge']);
|
|
47
48
|
|
|
48
49
|
export const name = 'project';
|
|
49
|
-
export const inject = ['router', 'storage', 'nodes', 'bridgeNodes', '
|
|
50
|
+
export const inject = ['router', 'storage', 'nodes', 'bridgeNodes', 'workspace'];
|
|
50
51
|
|
|
51
52
|
/** A 4xx the route answers itself (the router's `clientError` brand). */
|
|
52
53
|
const refused = (code: string, message: string, status = 400, details?: object) =>
|
|
@@ -259,7 +260,14 @@ export async function apply(ctx: Context) {
|
|
|
259
260
|
const branches = createBranches({
|
|
260
261
|
slug: ctx.workspace.slug,
|
|
261
262
|
dataDir: join(ctx.workspace.dataDir, name),
|
|
262
|
-
git:
|
|
263
|
+
git: () => {
|
|
264
|
+
// The `git` plugin's service (optional: the screen offers to install it); its version's major checked.
|
|
265
|
+
const service: unknown = ctx.get('git', false);
|
|
266
|
+
return isRecord(service) && typeof service.version === 'string' && service.version.startsWith('1.')
|
|
267
|
+
? // oxlint-disable-next-line bridge/no-new-unchecked-cast -- the `git` plugin's own service, its contract's major checked above
|
|
268
|
+
(service as unknown as GitService)
|
|
269
|
+
: undefined;
|
|
270
|
+
},
|
|
263
271
|
projects: () => ctx.bridgeNodes.projects(),
|
|
264
272
|
codeFrom: (input) => ctx.bridgeNodes.codeFrom(input),
|
|
265
273
|
follow: (input) => ctx.bridgeNodes.follow(input),
|
|
@@ -328,6 +336,55 @@ export async function apply(ctx: Context) {
|
|
|
328
336
|
}
|
|
329
337
|
},
|
|
330
338
|
});
|
|
339
|
+
// The Commit changes dialog of a branch (the `git` plugin's): its changes, one file's diff, a file's lines.
|
|
340
|
+
const changesBody = z.strictObject({ name: z.string().min(1), path: z.string().min(1).optional() });
|
|
341
|
+
const linesBody = z.strictObject({
|
|
342
|
+
name: z.string().min(1),
|
|
343
|
+
path: z.string().min(1),
|
|
344
|
+
from: z.number().int().positive(),
|
|
345
|
+
to: z.number().int().positive(),
|
|
346
|
+
});
|
|
347
|
+
const bodyOf = <T>(schema: z.ZodType<T>, body: Uint8Array | undefined, usage: string) => {
|
|
348
|
+
let parsed;
|
|
349
|
+
try {
|
|
350
|
+
parsed = schema.safeParse(JSON.parse(new TextDecoder().decode(body ?? new Uint8Array()) || '{}'));
|
|
351
|
+
} catch {}
|
|
352
|
+
if (!parsed?.success) throw refused('invalid_body', usage);
|
|
353
|
+
return parsed.data;
|
|
354
|
+
};
|
|
355
|
+
/** A refusal of the `git` service as this route's own (its code kept), anything else as `refused`. */
|
|
356
|
+
const asRefused = (error: unknown) =>
|
|
357
|
+
isRecord(error) && typeof error.code === 'string' && error.code !== 'failed'
|
|
358
|
+
? refused(error.code, error instanceof Error ? error.message : String(error), error.code === 'not_found' ? 404 : 409)
|
|
359
|
+
: refused('refused', error instanceof Error ? error.message : String(error), 409);
|
|
360
|
+
ctx.router.route(ctx, {
|
|
361
|
+
method: 'POST',
|
|
362
|
+
path: '/branches/changes',
|
|
363
|
+
agent: false,
|
|
364
|
+
description: "A branch's uncommitted changes for the Commit changes dialog (?node=): { name, path? }",
|
|
365
|
+
query: z.object({ node: z.string().optional() }),
|
|
366
|
+
handle: async ({ query, node, body }) => {
|
|
367
|
+
const { name: branch, path } = bodyOf(changesBody, body, 'POST /branches/changes takes { name, path? }');
|
|
368
|
+
return branches.changes(nodeOf(query, node), branch, path).catch((error: unknown) => {
|
|
369
|
+
throw asRefused(error);
|
|
370
|
+
});
|
|
371
|
+
},
|
|
372
|
+
});
|
|
373
|
+
ctx.router.route(ctx, {
|
|
374
|
+
method: 'POST',
|
|
375
|
+
path: '/branches/lines',
|
|
376
|
+
agent: false,
|
|
377
|
+
description: "Lines of an uncommitted file of a branch, as it is now (?node=): { name, path, from, to }",
|
|
378
|
+
query: z.object({ node: z.string().optional() }),
|
|
379
|
+
handle: async ({ query, node, body }) => {
|
|
380
|
+
const input = bodyOf(linesBody, body, 'POST /branches/lines takes { name, path, from, to }');
|
|
381
|
+
return branches
|
|
382
|
+
.lines(nodeOf(query, node), input.name, input.path, input.from, input.to)
|
|
383
|
+
.catch((error: unknown) => {
|
|
384
|
+
throw asRefused(error);
|
|
385
|
+
});
|
|
386
|
+
},
|
|
387
|
+
});
|
|
331
388
|
ctx.provide('projectBranches', {
|
|
332
389
|
newBranch: branches.newBranch,
|
|
333
390
|
branchForPlugins: branches.branchForPlugins,
|