@bridgebrew/project 0.0.5 → 0.0.9
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 +177 -397
- package/browser/branches.tsx +87 -26
- package/browser/browser.tsx +27 -7
- package/package.json +37 -6
- package/server.ts +60 -3
package/branches.ts
CHANGED
|
@@ -2,119 +2,27 @@
|
|
|
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';
|
|
118
26
|
|
|
119
27
|
/** What the host says Bridge loads from a repository (`bridgeNodes.codeFrom`). */
|
|
120
28
|
export interface CodeFrom {
|
|
@@ -149,7 +57,8 @@ export interface BranchesHost {
|
|
|
149
57
|
slug: string;
|
|
150
58
|
/** Where this plugin keeps its records (the pull requests it made or found). */
|
|
151
59
|
dataDir: string;
|
|
152
|
-
git
|
|
60
|
+
/** The `git` service, when the workspace has the `git` plugin. */
|
|
61
|
+
git(): GitService | undefined;
|
|
153
62
|
/** The workspace's projects as its `bridge.yml` files list them (`bridgeNodes.projects`). */
|
|
154
63
|
projects(): Promise<{ project: string; node?: string | undefined; folder: string; title: string }[]>;
|
|
155
64
|
codeFrom(input: { repository: string; sessions?: boolean }): Promise<CodeFrom>;
|
|
@@ -238,16 +147,14 @@ export const branchName = (title: string) =>
|
|
|
238
147
|
.replace(/^-+|-+$/g, '')
|
|
239
148
|
.slice(0, 50);
|
|
240
149
|
|
|
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). */
|
|
150
|
+
/** How much of a diff a model is given (bridge#597). */
|
|
245
151
|
const DIFF_CHARS = 60_000;
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
152
|
+
/** Bridge's own file in a project's folder: never committed, never counted as a change. */
|
|
153
|
+
const BRIDGE_YML = 'bridge.yml';
|
|
154
|
+
/** How many files' diff the Commit changes dialog gets whole: past them, each file is read by its path. */
|
|
155
|
+
const DIFF_FILES_MAX = 50;
|
|
156
|
+
/** The most characters of the dialog's whole diff. */
|
|
157
|
+
const DIFF_MAX = 24 * 1024;
|
|
251
158
|
|
|
252
159
|
/** The claim `newBranch` takes on a branch's folder in `.worktrees/` before it makes the branch (created exclusively,
|
|
253
160
|
* so two creators never share a folder), removed once made or undone (bridge#326). Workers are threads of the host's
|
|
@@ -294,33 +201,23 @@ export interface Settings {
|
|
|
294
201
|
waitMs?: number;
|
|
295
202
|
/** The listing's fetch deadline. */
|
|
296
203
|
fetchDeadlineMs?: number;
|
|
297
|
-
/** A remote run's deadline (push, pull, a branch's fetch). */
|
|
298
|
-
remoteDeadlineMs?: number;
|
|
299
204
|
}
|
|
300
205
|
|
|
301
206
|
/** The branches of host's workspace's projects. */
|
|
302
207
|
export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
303
|
-
const { waitMs = 100_000, fetchDeadlineMs = 30_000
|
|
208
|
+
const { waitMs = 100_000, fetchDeadlineMs = 30_000 } = settings;
|
|
304
209
|
// Its host's process (a worker is a thread of it), its workspace, this start: two Bridges sharing a repository, each
|
|
305
210
|
// with a workspace of that name, never take each other's claims for an older worker's.
|
|
306
211
|
const worker = `${process.pid}:${host.slug}:${randomUUID()}`;
|
|
307
212
|
/** The claims this worker is making now, by file. */
|
|
308
213
|
const making = new Set<string>();
|
|
309
214
|
|
|
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();
|
|
215
|
+
/** The `git` service; refused, saying how to get it, without it. */
|
|
216
|
+
const gitOf = () => {
|
|
217
|
+
const git = host.git();
|
|
218
|
+
if (!git) throw new Error('git actions need the Git plugin: install Git (@bridgebrew/git) in this workspace');
|
|
219
|
+
return git;
|
|
321
220
|
};
|
|
322
|
-
const resolves = (folder: string, ref: string) =>
|
|
323
|
-
host.git(folder, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]).then(({ code }) => code === 0);
|
|
324
221
|
|
|
325
222
|
/** The claim `text` when it marks an unfinished branch. */
|
|
326
223
|
const unfinished = (text: string | undefined, file: string) => {
|
|
@@ -355,58 +252,21 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
355
252
|
/** The repository's branches that have a folder (`git worktree list`): its own checkout first (main), then each
|
|
356
253
|
* worktree under `.worktrees/`; a detached one named `(detached)`, marked. Read only. */
|
|
357
254
|
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
|
-
});
|
|
255
|
+
const all = await gitOf().worktrees(folder);
|
|
366
256
|
const main = all[0]?.folder ?? real(folder);
|
|
367
257
|
return all
|
|
368
258
|
.filter((each) => each.folder === main || within(each.folder, join(main, '.worktrees')))
|
|
369
|
-
.map((
|
|
259
|
+
.map(({ folder: path, branch, detached }) => ({
|
|
260
|
+
name: branch ?? '(detached)',
|
|
261
|
+
folder: path,
|
|
262
|
+
main: path === main,
|
|
263
|
+
...(detached && { detached: true as const }),
|
|
264
|
+
}));
|
|
370
265
|
};
|
|
371
266
|
type Worktree = Awaited<ReturnType<typeof worktreesOf>>[number];
|
|
372
267
|
const holder = <T extends { folder: string }>(branches: T[], path: string) =>
|
|
373
268
|
branches.filter((each) => within(path, each.folder)).sort((a, b) => b.folder.length - a.folder.length)[0];
|
|
374
269
|
|
|
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
270
|
/** When each project's remote was last fetched. */
|
|
411
271
|
const fetched = new Map<string, number>();
|
|
412
272
|
/** Fetches the project's remote at most once a minute, without git's automatic maintenance in the user's
|
|
@@ -433,13 +293,7 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
433
293
|
// ponytail: one fetch a minute per project, a background poll if a fresher Pull matters.
|
|
434
294
|
if (Date.now() - (fetched.get(folder) ?? 0) < 60_000) return;
|
|
435
295
|
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
|
-
);
|
|
296
|
+
behind(main, `fetch`, () => gitOf().fetch(folder, { remote, deadlineMs: fetchDeadlineMs }));
|
|
443
297
|
};
|
|
444
298
|
|
|
445
299
|
// --- Pull requests: the ones Bridge made or found, by worktree folder (a renamed or detached branch keeps its own)
|
|
@@ -505,46 +359,6 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
505
359
|
return number ? Number(number) : undefined;
|
|
506
360
|
};
|
|
507
361
|
|
|
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
362
|
/** The recent jobs of each project (by its own folder), by branch name (a new one by its title), oldest first. */
|
|
549
363
|
const jobs = new Map<string, Map<string, Job[]>>();
|
|
550
364
|
const jobsOf = (main: string) => {
|
|
@@ -592,7 +406,8 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
592
406
|
const listBranches = async (
|
|
593
407
|
folder: string,
|
|
594
408
|
): Promise<{ branches: Branch[]; worktrees: Worktree[]; code: CodeFrom; refreshing: () => boolean }> => {
|
|
595
|
-
const
|
|
409
|
+
const git = gitOf();
|
|
410
|
+
const base = await git.defaultBranch(folder);
|
|
596
411
|
const worktrees = await worktreesOf(folder);
|
|
597
412
|
const main = worktrees[0]?.folder ?? real(folder);
|
|
598
413
|
// The reads of the remote and GitHub run behind it: this listing tells what they read last, and says whether one
|
|
@@ -640,26 +455,18 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
640
455
|
...(job && { job, jobs: recent! }),
|
|
641
456
|
};
|
|
642
457
|
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;
|
|
458
|
+
const status = await git.branchStatus(path, { exclude: [BRIDGE_YML] });
|
|
652
459
|
return {
|
|
653
460
|
...known,
|
|
654
461
|
// 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,
|
|
462
|
+
dirty: status.changed || (status.merging ? 1 : 0),
|
|
463
|
+
diff: status.diff,
|
|
464
|
+
ahead: status.ahead,
|
|
465
|
+
behindDefault: status.behindDefault,
|
|
659
466
|
// Shown only: Delete checks it again and refuses when git cannot tell.
|
|
660
|
-
unpushed:
|
|
661
|
-
behind:
|
|
662
|
-
upstream: !!upstream,
|
|
467
|
+
unpushed: status.unpushed ?? Math.max(status.ahead, 1),
|
|
468
|
+
behind: status.behind,
|
|
469
|
+
upstream: !!status.upstream,
|
|
663
470
|
};
|
|
664
471
|
} catch {
|
|
665
472
|
return {
|
|
@@ -689,13 +496,14 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
689
496
|
const undoMaking = async (main: string, file: string, claim: Making) => {
|
|
690
497
|
const keep = () => writeAtomic(file, JSON.stringify({ ...claim, kept: true }));
|
|
691
498
|
if (!claim.added) return existsSync(claim.folder) ? keep() : rmSync(file, { force: true });
|
|
499
|
+
const git = gitOf();
|
|
692
500
|
const worktree = (await worktreesOf(main)).find((each) => each.folder === claim.folder);
|
|
693
501
|
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
|
|
502
|
+
const head = await git.resolve(claim.folder, 'HEAD');
|
|
503
|
+
const status = await git.branchStatus(claim.folder).catch(() => undefined);
|
|
504
|
+
if (head !== claim.head || status?.changed !== 0) return keep();
|
|
505
|
+
if (!(await git.removeWorktree(main, claim.folder).then(() => true, () => false))) return keep();
|
|
506
|
+
if (claim.made) await git.deleteBranch(main, claim.name, { expected: claim.head }).catch(() => undefined);
|
|
699
507
|
rmSync(file, { force: true });
|
|
700
508
|
};
|
|
701
509
|
|
|
@@ -703,9 +511,10 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
703
511
|
* name is made safe from `title`; `existing`: the folder of branch `title` as git names it, refused when git has no
|
|
704
512
|
* such branch. */
|
|
705
513
|
const newBranch = async (folder: string, title: string, existing = false) => {
|
|
514
|
+
const git = gitOf();
|
|
706
515
|
const name = existing ? title : branchName(title);
|
|
707
516
|
if (!name) throw new Error('name the branch');
|
|
708
|
-
if (existing && !(await git(folder
|
|
517
|
+
if (existing && !(await git.branchNames(folder)).includes(name))
|
|
709
518
|
throw new Error(`no branch ${name} in this project`);
|
|
710
519
|
const worktrees = await worktreesOf(folder);
|
|
711
520
|
const main = worktrees[0]?.folder ?? folder;
|
|
@@ -722,11 +531,8 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
722
531
|
const ours =
|
|
723
532
|
left.made &&
|
|
724
533
|
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}`));
|
|
534
|
+
(await git.resolve(main, ref)) === left.head &&
|
|
535
|
+
!(await git.worktrees(main)).some((tree) => tree.branch === name && tree.folder !== left.folder);
|
|
730
536
|
const commands = [
|
|
731
537
|
`cd ${shellQuoted(main)}`,
|
|
732
538
|
...(listed ? [`git worktree remove ${shellQuoted(left.folder)}`] : []),
|
|
@@ -742,25 +548,17 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
742
548
|
if (worktrees.some((each) => each.name === name)) throw new Error(`a branch ${name} exists already`);
|
|
743
549
|
// The worktrees and the `bridge.yml` Bridge writes are Bridge's, never the repository's, where git reads its
|
|
744
550
|
// 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);
|
|
551
|
+
await git.exclude(folder, ['/.worktrees/', BRIDGE_YML]);
|
|
552
|
+
const base = await git.defaultBranch(folder);
|
|
750
553
|
// From the remote's default branch, fetched now, else as fetched last (offline: bridge#540); its local one only
|
|
751
554
|
// without a remote.
|
|
752
555
|
if (base.remote)
|
|
753
556
|
// 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}`]);
|
|
557
|
+
await git.fetch(folder, { remote: base.remote, ref: `refs/heads/${base.name}` }).catch(() => undefined);
|
|
558
|
+
const from = base.remote && (await git.resolve(folder, base.ref)) ? base.ref : `refs/heads/${base.name}`;
|
|
559
|
+
const kept = (await git.branchNames(folder)).includes(name);
|
|
560
|
+
const head = await git.resolve(folder, kept ? `refs/heads/${name}` : from);
|
|
561
|
+
if (!head) throw new Error(`${kept ? name : from} names no commit`);
|
|
764
562
|
mkdirSync(join(main, '.worktrees'), { recursive: true });
|
|
765
563
|
let worktree = '';
|
|
766
564
|
let file = '';
|
|
@@ -787,14 +585,11 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
787
585
|
}
|
|
788
586
|
}
|
|
789
587
|
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) {
|
|
588
|
+
try {
|
|
589
|
+
await git.addWorktree(folder, { folder: worktree, branch: name, existing: kept, from: head });
|
|
590
|
+
} catch (error) {
|
|
796
591
|
rmSync(file, { force: true });
|
|
797
|
-
throw new Error(
|
|
592
|
+
throw new Error(reason(error));
|
|
798
593
|
}
|
|
799
594
|
writeAtomic(file, JSON.stringify(claim(true)));
|
|
800
595
|
try {
|
|
@@ -822,93 +617,69 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
822
617
|
return project;
|
|
823
618
|
};
|
|
824
619
|
|
|
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
620
|
const unfenced = (text: string) =>
|
|
833
621
|
text
|
|
834
622
|
.trim()
|
|
835
623
|
.replace(/^```[^\n]*\n([\s\S]*?)\n?```$/, '$1')
|
|
836
624
|
.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
625
|
|
|
857
626
|
/** Commits every change in the branch's folder (bridge.yml aside): the message written, else, finishing a merge,
|
|
858
627
|
* git's own, else one a model writes from the staged diff, else the branch's name (`fellBack` says why). Refused
|
|
859
628
|
* while a merge leaves conflicts (bridge#552): their markers would be committed. */
|
|
860
629
|
const commitBranch = async (branch: Branch, node: string, message?: string) => {
|
|
861
630
|
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
631
|
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
|
-
|
|
632
|
+
try {
|
|
633
|
+
const done = await gitOf().commit(branch.folder, {
|
|
634
|
+
scope: 'branch',
|
|
635
|
+
exclude: [BRIDGE_YML],
|
|
636
|
+
maxChars: DIFF_CHARS,
|
|
637
|
+
message: message?.trim()
|
|
638
|
+
? message.trim()
|
|
639
|
+
: async ({ mergeMessage, recent, stat, diff }) => {
|
|
640
|
+
if (mergeMessage) return mergeMessage;
|
|
641
|
+
try {
|
|
642
|
+
const prompt = [
|
|
643
|
+
'Write the git commit message for the staged changes below.',
|
|
644
|
+
'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.',
|
|
645
|
+
recent.length
|
|
646
|
+
? `Follow the style of this repository's recent commits (prefix, tense, length):\n${recent.join('\n')}`
|
|
647
|
+
: 'Use the imperative mood.',
|
|
648
|
+
`Files:\n${stat ?? ''}`,
|
|
649
|
+
`Diff:\n${diff}`,
|
|
650
|
+
].join('\n\n');
|
|
651
|
+
const text = unfenced(await host.write(node, prompt, []));
|
|
652
|
+
if (!text) throw new Error('the model wrote nothing');
|
|
653
|
+
return text;
|
|
654
|
+
} catch (error) {
|
|
655
|
+
fellBack = `the message could not be written (${reason(error)})`;
|
|
656
|
+
return branch.name.replace(/[-/]/g, ' ');
|
|
657
|
+
}
|
|
658
|
+
},
|
|
659
|
+
});
|
|
660
|
+
return { message: done.message, ...(fellBack && { fellBack }) };
|
|
661
|
+
} catch (error) {
|
|
662
|
+
if (isRecord(error) && error.code === 'conflict')
|
|
663
|
+
throw new Error(`${branch.name} has ${reason(error)}`);
|
|
664
|
+
throw error;
|
|
665
|
+
}
|
|
897
666
|
};
|
|
898
667
|
const pushBranch = async (branch: Branch, confirmed = false) => {
|
|
899
668
|
if (branch.isDefault && !confirmed)
|
|
900
669
|
throw new Error(`pushing ${branch.name}, the default branch, needs a confirmation`);
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
670
|
+
await gitOf()
|
|
671
|
+
.push(branch.folder, { branch: branch.name })
|
|
672
|
+
.catch((error: unknown) => {
|
|
673
|
+
throw new Error(`${branch.name} is not pushed, git refused: ${reason(error)}`);
|
|
674
|
+
});
|
|
906
675
|
};
|
|
907
676
|
const pullBranch = async (branch: Branch) => {
|
|
908
677
|
if (!branch.upstream) throw new Error(`${branch.name} has no upstream to pull from`);
|
|
909
|
-
await
|
|
910
|
-
|
|
911
|
-
|
|
678
|
+
await gitOf()
|
|
679
|
+
.pullFastForward(branch.folder)
|
|
680
|
+
.catch((error: unknown) => {
|
|
681
|
+
throw new Error(`${branch.name} is not pulled, git refused: ${reason(error)}`);
|
|
682
|
+
});
|
|
912
683
|
};
|
|
913
684
|
|
|
914
685
|
/** The repository's pull request template, where GitHub looks for one. */
|
|
@@ -929,7 +700,7 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
929
700
|
|
|
930
701
|
/** Its pull request, made once (a draft, through `github`), its texts written by a model from its commits, its diff,
|
|
931
702
|
* 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[]) => {
|
|
703
|
+
const pullRequest = async (branch: Branch, main: string, node: string, sessions: string[], commit = true) => {
|
|
933
704
|
if (branch.main || branch.isDefault) throw new Error('the default branch has no pull request: start a branch');
|
|
934
705
|
const github = host.github();
|
|
935
706
|
if (!github)
|
|
@@ -939,7 +710,8 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
939
710
|
repositories.set(main, { at: Date.now(), repository });
|
|
940
711
|
if (!repository)
|
|
941
712
|
throw new Error(`${branch.name} has no GitHub repository gh knows: its remote is not one on github.com`);
|
|
942
|
-
|
|
713
|
+
// `commit: false` (the Commit changes dialog committed what goes in): the rest stays uncommitted.
|
|
714
|
+
const committed = commit && branch.dirty ? await commitBranch(branch, node) : undefined;
|
|
943
715
|
await pushBranch(branch);
|
|
944
716
|
const open = (await github.pullRequestsForBranch({ repository, branch: branch.name })).find(
|
|
945
717
|
({ state }) => state === 'open' || state === 'draft',
|
|
@@ -949,9 +721,11 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
949
721
|
found.set(`${repository}\0${branch.name}`, { at: Date.now(), prs: [{ url: open.url, state: open.state }] });
|
|
950
722
|
return { url: open.url, ...(committed && { committed }) };
|
|
951
723
|
}
|
|
952
|
-
const
|
|
953
|
-
const
|
|
954
|
-
const
|
|
724
|
+
const git = gitOf();
|
|
725
|
+
const base = await git.defaultBranch(branch.folder);
|
|
726
|
+
const commits = (await git.history(branch.folder, { max: 1000, range: `${base.ref}..HEAD` })).reverse();
|
|
727
|
+
const log = commits.map(({ subject, body }) => `${subject}\n\n${body}`).join('\n');
|
|
728
|
+
const subjects = commits.map(({ subject }) => subject).join('\n');
|
|
955
729
|
const template = pullRequestTemplate(branch.folder);
|
|
956
730
|
let title = '';
|
|
957
731
|
let body = '';
|
|
@@ -965,7 +739,7 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
965
739
|
? `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
740
|
: 'The description: a short summary, then what changed.',
|
|
967
741
|
`Commits (oldest first):\n${log}`,
|
|
968
|
-
`Diff against ${base.name}:\n${await
|
|
742
|
+
`Diff against ${base.name}:\n${await git.rangeDiff(branch.folder, `${base.ref}...HEAD`, DIFF_CHARS)}`,
|
|
969
743
|
].join('\n\n');
|
|
970
744
|
const [first = '', ...rest] = unfenced(await host.write(node, prompt, sessions)).split('\n');
|
|
971
745
|
title = first.replace(/^#+\s*|^title:\s*/i, '').trim();
|
|
@@ -990,34 +764,6 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
990
764
|
return { url, title, ...(committed && { committed }), ...(fellBack && { fellBack }) };
|
|
991
765
|
};
|
|
992
766
|
|
|
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
767
|
/** Deletes a branch's folder, refused while anything uses it or holds work. */
|
|
1022
768
|
const removeBranch = async (folder: string, branch: Branch, worktrees: Worktree[]) => {
|
|
1023
769
|
if (branch.main) throw new Error('the project’s own folder is never deleted');
|
|
@@ -1026,14 +772,13 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
1026
772
|
const dead = unfinished(claimed, claim);
|
|
1027
773
|
if (claimed !== undefined && !dead)
|
|
1028
774
|
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)
|
|
775
|
+
const git = gitOf();
|
|
776
|
+
const status = await git.branchStatus(branch.folder).catch(() => undefined);
|
|
777
|
+
if (status?.unpushed === undefined)
|
|
778
|
+
throw new Error(`${branch.name} is not deleted: git cannot tell whether its commits are pushed`);
|
|
779
|
+
if (branch.dirty || status.unpushed)
|
|
1035
780
|
throw new Error(`${branch.name} holds work that is not pushed: open its pull request first`);
|
|
1036
|
-
const nested = await nestedRepositories(branch.folder);
|
|
781
|
+
const nested = await git.nestedRepositories(branch.folder);
|
|
1037
782
|
if (nested.length > 0)
|
|
1038
783
|
throw new Error(
|
|
1039
784
|
`${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 +795,7 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
1050
795
|
const project = await listedProject(node);
|
|
1051
796
|
if (!project) return { project: null, branches: [] };
|
|
1052
797
|
if (!project.repository) return { project: { title: project.title, folder: project.folder }, repository: false };
|
|
798
|
+
if (!host.git()) return { project: { title: project.title, folder: project.folder }, git: 'missing', branches: [] };
|
|
1053
799
|
const { branches, worktrees, code, refreshing } = await listBranches(project.folder);
|
|
1054
800
|
const hostLevel = hostLevelOf(worktrees, code);
|
|
1055
801
|
const main = worktrees[0]?.folder ?? project.folder;
|
|
@@ -1063,6 +809,9 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
1063
809
|
return {
|
|
1064
810
|
project: { title: project.title, folder: project.folder },
|
|
1065
811
|
github: host.github() ? 'ready' : 'missing',
|
|
812
|
+
// Its pull request honours `commit: false` (the `git` plugin's page offers a session's commit then its pull
|
|
813
|
+
// request only to a Project that says so: an older one committed the whole branch first).
|
|
814
|
+
prWithoutCommit: true,
|
|
1066
815
|
...(hostLevel && { hostLevel }),
|
|
1067
816
|
branches,
|
|
1068
817
|
...(making.length > 0 && { jobs: making }),
|
|
@@ -1166,7 +915,7 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
1166
915
|
result = await run(name, 'pull', async () => (await pullBranch(await now()), { pulled: name }));
|
|
1167
916
|
else if (action === 'pr')
|
|
1168
917
|
result = await run(name, 'pr', async () => {
|
|
1169
|
-
const { url, ...made } = await pullRequest(await now(), main, node, await sessionsOf());
|
|
918
|
+
const { url, ...made } = await pullRequest(await now(), main, node, await sessionsOf(), input.commit !== false);
|
|
1170
919
|
return { pr: url, ...made };
|
|
1171
920
|
});
|
|
1172
921
|
else if (action === 'remove') {
|
|
@@ -1178,9 +927,59 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
1178
927
|
return { ...(await view(node)), result };
|
|
1179
928
|
};
|
|
1180
929
|
|
|
930
|
+
/** Branch `name` of project `node`, as the Commit changes dialog reads it: its repository's top, the branch's folder in
|
|
931
|
+
* it, and its changes (bridge.yml aside), each path relative to the top. */
|
|
932
|
+
const changesOf = async (node: string, name: string) => {
|
|
933
|
+
const git = gitOf();
|
|
934
|
+
const project = await projectOf(node);
|
|
935
|
+
const branch = (await worktreesOf(project.folder)).find((each) => each.name === name);
|
|
936
|
+
if (!branch) throw new Error(`no branch ${name} in ${project.title}`);
|
|
937
|
+
const repository = await git.repositoryAt(branch.folder);
|
|
938
|
+
if (!repository) throw new Error(`${branch.folder} is in no git repository`);
|
|
939
|
+
const own = `${repository.prefix}${BRIDGE_YML}`;
|
|
940
|
+
const files = (await git.status(branch.folder)).map(({ path }) => path).filter((path) => path !== own);
|
|
941
|
+
return { git, branch, top: repository.top, files };
|
|
942
|
+
};
|
|
943
|
+
/** What the dialog shows of branch `name`: every uncommitted file with its counts, the diff (past `DIFF_FILES_MAX`
|
|
944
|
+
* files none, `byFile`; cut short past `DIFF_MAX`, `cut`), and the branch; with `path`, that file's diff only. */
|
|
945
|
+
const changes = async (node: string, name: string, path?: string) => {
|
|
946
|
+
const { git, branch, top, files } = await changesOf(node, name);
|
|
947
|
+
if (path !== undefined) {
|
|
948
|
+
if (!files.includes(path)) throw new Error(`${path} has no uncommitted change on ${name}`);
|
|
949
|
+
const { patch, cut } = await git.diff(top, { paths: [path], maxChars: DIFF_MAX });
|
|
950
|
+
return { repository: top, path, diff: patch, ...(cut && { cut: true }) };
|
|
951
|
+
}
|
|
952
|
+
const counts = await git.counts(top, files);
|
|
953
|
+
const whole = files.length <= DIFF_FILES_MAX;
|
|
954
|
+
const diff = whole ? await git.diff(top, { paths: files, maxChars: DIFF_MAX }) : { patch: '', cut: false };
|
|
955
|
+
const status = await git.branchStatus(branch.folder, { exclude: [BRIDGE_YML] }).catch(() => undefined);
|
|
956
|
+
return {
|
|
957
|
+
repository: top,
|
|
958
|
+
files: files.map((each) => ({ path: each, pending: true, ...counts[each] })),
|
|
959
|
+
diff: diff.patch,
|
|
960
|
+
...(!whole && { byFile: true }),
|
|
961
|
+
...(diff.cut && { cut: true }),
|
|
962
|
+
branch: status && {
|
|
963
|
+
name,
|
|
964
|
+
isDefault: status.isDefault,
|
|
965
|
+
remote: status.remote,
|
|
966
|
+
upstream: !!status.upstream,
|
|
967
|
+
unpushed: status.unpushed ?? 0,
|
|
968
|
+
},
|
|
969
|
+
...(status?.merging && { merging: true }),
|
|
970
|
+
};
|
|
971
|
+
};
|
|
972
|
+
|
|
1181
973
|
return {
|
|
1182
974
|
view,
|
|
1183
975
|
act,
|
|
976
|
+
changes,
|
|
977
|
+
/** Lines `from`–`to` of an uncommitted file of branch `name`, as it is now (the dialog's folds). */
|
|
978
|
+
lines: async (node: string, name: string, path: string, from: number, to: number) => {
|
|
979
|
+
const { git, top, files } = await changesOf(node, name);
|
|
980
|
+
if (!files.includes(path)) throw new Error(`${path} has no uncommitted change on ${name}`);
|
|
981
|
+
return { path, lines: await git.lines(top, path, from, to) };
|
|
982
|
+
},
|
|
1184
983
|
/** A session's new branch in project `node` (Sessions, research-083): made as New makes one; `existing`: the folder
|
|
1185
984
|
* of that branch, its name kept. */
|
|
1186
985
|
newBranch: async ({
|
|
@@ -1206,23 +1005,4 @@ export function createBranches(host: BranchesHost, settings: Settings = {}) {
|
|
|
1206
1005
|
};
|
|
1207
1006
|
}
|
|
1208
1007
|
|
|
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
1008
|
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,
|
|
@@ -42,13 +44,46 @@ import {
|
|
|
42
44
|
} from '@bridge/ui';
|
|
43
45
|
import type { Context } from 'cordis';
|
|
44
46
|
import type {} from '@bridge/ui-renderer/client';
|
|
45
|
-
import { SessionPrompt } from '@
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
47
|
+
import { SessionPrompt } from '@bridgebrew/session-ui/prompt';
|
|
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,6 +292,7 @@ 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);
|
|
252
297
|
React.useEffect(() => {
|
|
253
298
|
let gone = false;
|
|
@@ -261,6 +306,9 @@ export function Branches({ ctx, node }: { ctx: Context; node: string }) {
|
|
|
261
306
|
// A node no bridge.yml lists as a project (one made before projects had one): no branches either.
|
|
262
307
|
if (isRecord(body) && body.project === null)
|
|
263
308
|
return setError('No bridge.yml lists this project: Bridge shows no branches for it');
|
|
309
|
+
// No Git plugin: nothing to list; its install offered.
|
|
310
|
+
if (isRecord(body) && body.git === 'missing') return setGitMissing(true);
|
|
311
|
+
setGitMissing(false);
|
|
264
312
|
// The host's own answer: typed once where it is read.
|
|
265
313
|
setView(body as View);
|
|
266
314
|
})
|
|
@@ -281,22 +329,22 @@ export function Branches({ ctx, node }: { ctx: Context; node: string }) {
|
|
|
281
329
|
const timer = setTimeout(() => setReads((count) => count + 1), POLL_MS);
|
|
282
330
|
return () => clearTimeout(timer);
|
|
283
331
|
}, [runsOn, view]);
|
|
284
|
-
/** Installs
|
|
285
|
-
const
|
|
332
|
+
/** Installs a plugin in this workspace (the Plugins screen's own install), then reads the branches again. */
|
|
333
|
+
const install = async (source: string, title: string) => {
|
|
286
334
|
setInstalling(true);
|
|
287
335
|
try {
|
|
288
336
|
const res = await fetch(`/_bridge/workspaces/${encodeURIComponent(slug)}/plugins/install`, {
|
|
289
337
|
method: 'POST',
|
|
290
338
|
headers: { 'content-type': 'application/json' },
|
|
291
|
-
body: JSON.stringify({ source
|
|
339
|
+
body: JSON.stringify({ source }),
|
|
292
340
|
});
|
|
293
341
|
await readJson(res);
|
|
294
|
-
toast({ variant: 'success', title:
|
|
342
|
+
toast({ variant: 'success', title: `${title} installed` });
|
|
295
343
|
setReads((count) => count + 1);
|
|
296
344
|
} catch (cause) {
|
|
297
345
|
toast({
|
|
298
346
|
variant: 'error',
|
|
299
|
-
title:
|
|
347
|
+
title: `${title} is not installed`,
|
|
300
348
|
description: cause instanceof Error ? cause.message : String(cause),
|
|
301
349
|
});
|
|
302
350
|
} finally {
|
|
@@ -347,6 +395,15 @@ export function Branches({ ctx, node }: { ctx: Context; node: string }) {
|
|
|
347
395
|
}
|
|
348
396
|
};
|
|
349
397
|
if (error) return <EmptyState icon={<Icon name="git-branch" size={20} />} title={error} fill />;
|
|
398
|
+
if (gitMissing)
|
|
399
|
+
return (
|
|
400
|
+
<EmptyState icon={<Icon name="git-branch" size={20} />} title="Branches need the Git plugin" fill>
|
|
401
|
+
<p>Git runs every branch action: its changes, commits, pushes and pull requests.</p>
|
|
402
|
+
<Button variant="primary" disabled={installing} onClick={() => void install('@bridgebrew/git', 'Git')}>
|
|
403
|
+
{installing ? 'Installing…' : 'Install Git'}
|
|
404
|
+
</Button>
|
|
405
|
+
</EmptyState>
|
|
406
|
+
);
|
|
350
407
|
if (!view) return <section aria-label="Screen" className="flex h-full min-h-0 flex-col" />;
|
|
351
408
|
const busy = running !== undefined;
|
|
352
409
|
const spinning = (action: string, branch?: string) =>
|
|
@@ -381,7 +438,12 @@ export function Branches({ ctx, node }: { ctx: Context; node: string }) {
|
|
|
381
438
|
<span className="min-w-0 flex-1 break-words">
|
|
382
439
|
Pull requests need the GitHub plugin: every other action works without it.
|
|
383
440
|
</span>
|
|
384
|
-
<Button
|
|
441
|
+
<Button
|
|
442
|
+
size="sm"
|
|
443
|
+
variant="outline"
|
|
444
|
+
disabled={installing}
|
|
445
|
+
onClick={() => void install('@bridgebrew/github', 'GitHub')}
|
|
446
|
+
>
|
|
385
447
|
{installing ? 'Installing…' : 'Install GitHub'}
|
|
386
448
|
</Button>
|
|
387
449
|
</p>
|
|
@@ -493,17 +555,16 @@ export function Branches({ ctx, node }: { ctx: Context; node: string }) {
|
|
|
493
555
|
// Its menus and dialogs are portals: their clicks reach the row through React, never selecting it.
|
|
494
556
|
onClick={(event) => event.stopPropagation()}
|
|
495
557
|
>
|
|
496
|
-
|
|
497
|
-
slug
|
|
498
|
-
node
|
|
558
|
+
{renderSlot?.('project.branch-actions', {
|
|
559
|
+
slug,
|
|
560
|
+
node,
|
|
499
561
|
// 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
|
-
/>
|
|
562
|
+
branch: view.github === 'missing' ? { ...branch, pullRequests: false } : branch,
|
|
563
|
+
route: projectBranchesRoute,
|
|
564
|
+
disabled: busy || !!branch.job?.running,
|
|
565
|
+
onAnswer: (answer) =>
|
|
566
|
+
setView((was) => (was ? { ...was, branches: answer.branches } : was)),
|
|
567
|
+
})}
|
|
507
568
|
<Button
|
|
508
569
|
size="sm"
|
|
509
570
|
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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bridgebrew/project",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.9",
|
|
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,16 +116,17 @@
|
|
|
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": {
|
|
126
|
+
"@bridgebrew/session-ui": "0.0.2",
|
|
95
127
|
"zod": "4.6.5"
|
|
96
128
|
},
|
|
97
129
|
"peerDependencies": {
|
|
98
|
-
"@bridge/session-ui": ">=0.0.1",
|
|
99
130
|
"@bridge/ui": ">=0.0.1",
|
|
100
131
|
"cordis": "4.0.0-rc.11",
|
|
101
132
|
"react": "19.3.0"
|
|
@@ -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.20261120.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,
|