@coderook/cli 0.49.0 → 0.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,153 +1,47 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
36
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
4
  };
38
5
  Object.defineProperty(exports, "__esModule", { value: true });
39
6
  exports.AlreadyReported = void 0;
7
+ exports.projectOf = projectOf;
8
+ exports.gitAddress = gitAddress;
9
+ exports.tuning = tuning;
40
10
  exports.main = main;
41
11
  /**
42
- * `git push coderook` — a git remote helper.
43
- *
44
- * Git looks for a program called `git-remote-<scheme>` on PATH when it meets a
45
- * remote URL it does not recognise, hands it the remote name and URL, and then
46
- * talks a small line protocol over stdin and stdout. This is that program for
47
- * `coderook://` URLs, which is what lets every editor's built-in git panel work
48
- * with CodeRook without any per-editor work.
49
- *
50
- * Both directions are implemented: `push` publishes each commit as a save, and
51
- * `import` rebuilds a git history from those saves so `git clone` and `git
52
- * fetch` work.
53
- *
54
- * The vocabulary matters here, because the two products do not agree by
55
- * accident. A pushed commit becomes a *commit* in CodeRook — a save, inside
56
- * the project, that nobody outside can see. Tagging it names it, and a named
57
- * save is a *version*, which is the only thing the public side offers. That
58
- * is the same distinction git already draws between a commit and a tag, so
59
- * the mapping is one-to-one rather than an approximation.
60
- *
61
- * A save also carries a description of its own, separate from its message.
62
- * That travels as a git note on `refs/notes/coderook` in both directions.
63
- *
64
- * ## Why the `push` capability rather than `export`
65
- *
66
- * A helper may declare `export`, in which case git runs `git fast-export` and
67
- * pipes the stream in. It is less code and it is the wrong shape here:
68
- * fast-export states each commit as a *delta against its parent*, so replaying
69
- * it onto one working tree is only correct while the history is a straight
70
- * line. The moment a branch or a merge appears, the tree a commit is applied to
71
- * is not the tree it was written against, and the version published is a blend
72
- * of two commits that never existed. That failure is silent — every file is
73
- * valid, the push reports success, and the contents are wrong.
74
- *
75
- * Declaring `push` instead means git tells us which refs to move and leaves the
76
- * method to us, so each commit is read as a *complete tree* and parentage never
77
- * has to be reconstructed. It also lets us diff any two commits directly, which
78
- * is what keeps the upload incremental.
79
- *
80
- * ## What is deliberately not supported
81
- *
82
- * Named here rather than discovered by failure:
83
- *
84
- * - **Tag kind.** A tag becomes a release and a release becomes a tag, but
85
- * fast-import can only create annotated tags — so a lightweight tag pushed
86
- * comes back annotated. CodeRook has no notion of the difference to record.
87
- * - **Force pushes and deletions.** CodeRook versions are immutable, so there
88
- * is nothing to rewind to. Both are refused rather than silently ignored.
89
- * - **Submodules.** A gitlink is a pointer into another repository and there
90
- * are no bytes to publish. Skipped on push, and said out loud.
91
- * - **File modes.** The executable bit travels both ways: a pushed `100755`
92
- * is recorded as executable, and an executable file is fetched as `100755`.
93
- * Versions saved before the bit was recorded come back `100644`.
94
- *
95
- * ## What a round trip does and does not preserve
96
- *
97
- * Push then clone returns the same *contents*, not the same *commits*. The
98
- * rebuilt commits have different ids, because a git commit id covers its
99
- * author, committer and timestamps, and CodeRook stores who published a
100
- * version but not the original stamps. So a clone of a pushed project is a
101
- * faithful copy of the files and an honest approximation of the history.
102
- *
103
- * Merges are asymmetric, and the asymmetry is in the service rather than here.
104
- * A publish states one base version, so pushing a git merge commit records one
105
- * parent and the second is lost — the merged *tree* is exact, the fork in the
106
- * history is not. Reading back is the richer direction: a version states its
107
- * parents in order, so a version that genuinely has two is rebuilt as a real
108
- * git merge commit. Push then clone therefore returns a straight line even
109
- * where the original branched.
12
+ * `git-remote-coderook`: the push half of git with CodeRook.
13
+ *
14
+ * Git with CodeRook is plain git: https://coderook.com/<owner>/<project>.git
15
+ * clones, fetches and pushes like any host. One thing plain git cannot do
16
+ * there is push more than 100 MB at once, because Cloudflare, in front of the
17
+ * service, refuses any request that large and git sends a whole push as one
18
+ * request. `coderook git setup` therefore points pushes to CodeRook here
19
+ * (git's pushInsteadOf), and this sends them through git_bridge.ts: large
20
+ * files beside the push in pieces, the rest as git's own push. Commit ids are
21
+ * the ones the person made; nothing is rewritten.
22
+ *
23
+ * Until 30 November 2026 this helper was a whole second way of using git with
24
+ * CodeRook (`coderook://` remotes): it published each commit as a save and
25
+ * rebuilt history from saves on fetch, under commit ids of its own. Plain git
26
+ * replaced it, so all that is left is the push. A fetch through an old
27
+ * `coderook://` remote is refused with the command that moves it to plain git.
110
28
  */
111
- const node_child_process_1 = require("node:child_process");
112
- const safe_path_js_1 = require("../../cbx/src/shared/safe_path.js");
113
- const promises_1 = require("node:fs/promises");
114
- const node_os_1 = __importDefault(require("node:os"));
115
- const node_path_1 = __importDefault(require("node:path"));
116
29
  const node_process_1 = __importDefault(require("node:process"));
117
- const upload_js_1 = require("../../cbx/src/core/upload.js");
118
- const stored_zip_js_1 = require("./stored_zip.js");
119
- const tracks_js_1 = require("../../cbx/src/core/tracks.js");
120
30
  const identify_js_1 = require("../../cbx/src/core/identify.js");
121
31
  const config_js_1 = require("./config.js");
122
32
  const version_js_1 = require("./version.js");
123
- const publish_js_1 = require("./publish.js");
124
- const git_history_js_1 = require("./git_history.js");
125
33
  const api_js_1 = require("./api.js");
126
- /** A fetch that cannot be served. Carried out so the process can exit non-zero. */
127
- class ImportFailed extends Error {
128
- }
34
+ const git_bridge_js_1 = require("./git_bridge.js");
35
+ const chunking_js_1 = require("../../cbx/src/shared/chunking.js");
129
36
  /**
130
37
  * A failure this code has already explained.
131
38
  *
132
39
  * The entry point prints whatever reaches it, which is right for a surprise
133
- * and wrong for a refusal that has just been set out in full — the person
134
- * would read the same paragraph twice, the second time with a program name
135
- * in front of it.
40
+ * and wrong for a refusal that has just been set out in full.
136
41
  */
137
42
  class AlreadyReported extends Error {
138
43
  }
139
44
  exports.AlreadyReported = AlreadyReported;
140
- /**
141
- * A name as fast-import may carry it on an author, committer or tagger line.
142
- *
143
- * Every other line of the stream is built from values the helper made; these
144
- * come from what people typed. A newline in a display name ended the line and
145
- * began another — any command the stream accepts, a symlink or a ref update
146
- * included — and `<` or `>` would end the name early. Each becomes a space.
147
- */
148
- function identity(name) {
149
- return name.replace(/[\x00-\x1f\x7f<>]/g, " ").replace(/\s+/g, " ").trim() || "CodeRook";
150
- }
151
45
  /** Everything the helper writes for a person goes to stderr; stdout is protocol. */
152
46
  function say(text) {
153
47
  node_process_1.default.stderr.write(`${text}\n`);
@@ -155,1338 +49,47 @@ function say(text) {
155
49
  function send(text) {
156
50
  node_process_1.default.stdout.write(`${text}\n`);
157
51
  }
158
- /** Run git and return stdout as text. Throws with git's own message. */
159
- function git(args) {
160
- const result = (0, node_child_process_1.spawnSync)("git", args, {
161
- encoding: "utf8",
162
- maxBuffer: 1024 * 1024 * 256,
163
- });
164
- if (result.status !== 0) {
165
- throw new Error(`git ${args.slice(0, 3).join(" ")} failed: ${(result.stderr || "").trim()}`);
166
- }
167
- return result.stdout;
168
- }
169
- /**
170
- * Where CodeRook keeps a save's description inside a git repository.
171
- *
172
- * `refs/notes/coderook` rather than git's default `refs/notes/commits`,
173
- * because the default is shared ground — anything else attaching notes writes
174
- * there too, and a fetch that overwrote somebody's own notes with ours would
175
- * be taking something that was not offered.
176
- */
177
- const NOTES_REF = "refs/notes/coderook";
178
- /**
179
- * The description attached to a commit, if there is one.
180
- *
181
- * Empty rather than throwing for every ordinary reason it can be missing: no
182
- * notes ref at all, no note on this commit, or a repository where notes have
183
- * never been used. None of those is a problem worth stopping a push for.
184
- */
185
- function noteOn(sha) {
186
- const result = (0, node_child_process_1.spawnSync)("git", ["notes", `--ref=${NOTES_REF}`, "show", sha], { encoding: "utf8", maxBuffer: 1024 * 1024 * 8 });
187
- return result.status === 0 ? (result.stdout ?? "").trim() : "";
188
- }
189
- /** Run git for its exit status alone. False rather than throwing. */
190
- function gitOk(args) {
191
- return ((0, node_child_process_1.spawnSync)("git", args, { encoding: "utf8", stdio: "ignore" }).status === 0);
192
- }
193
- /**
194
- * One long-lived `git cat-file --batch` process.
195
- *
196
- * A push reads one blob per changed path per commit, and starting a git process
197
- * for each costs more than the reading does. GitLab measured the same walk as
198
- * 70% faster with a single batch process, which is the whole reason this is a
199
- * class rather than a function that shells out.
200
- *
201
- * The protocol is: write `<object>\n`, read a header line
202
- * `<oid> <type> <size>\n`, then exactly `<size>` bytes, then one newline.
203
- */
204
- class CatFile {
205
- child = (0, node_child_process_1.spawn)("git", ["cat-file", "--batch"], {
206
- stdio: ["pipe", "pipe", "inherit"],
207
- });
208
- buffer = Buffer.alloc(0);
209
- waiters = [];
210
- closed = false;
211
- constructor() {
212
- this.child.stdout.on("data", (chunk) => {
213
- this.buffer = Buffer.concat([this.buffer, chunk]);
214
- const waiting = this.waiters;
215
- this.waiters = [];
216
- for (const wake of waiting)
217
- wake();
218
- });
219
- this.child.stdout.on("end", () => {
220
- this.closed = true;
221
- for (const wake of this.waiters)
222
- wake();
223
- this.waiters = [];
224
- });
225
- }
226
- async more() {
227
- if (this.closed)
228
- throw new Error("git cat-file closed unexpectedly");
229
- await new Promise((resolve) => this.waiters.push(resolve));
230
- }
231
- async readLine() {
232
- for (;;) {
233
- const at = this.buffer.indexOf(0x0a);
234
- if (at !== -1) {
235
- const line = this.buffer.subarray(0, at).toString("utf8");
236
- this.buffer = this.buffer.subarray(at + 1);
237
- return line;
238
- }
239
- await this.more();
240
- }
241
- }
242
- async readBytes(count) {
243
- while (this.buffer.length < count)
244
- await this.more();
245
- const out = this.buffer.subarray(0, count);
246
- this.buffer = this.buffer.subarray(count);
247
- return Buffer.from(out);
248
- }
249
- /** The bytes of one blob, named as `<commit>:<path>` or by object id. */
250
- async blob(reference) {
251
- this.child.stdin.write(`${reference}\n`);
252
- const header = await this.readLine();
253
- if (header.endsWith(" missing")) {
254
- throw new Error(`git has no object for ${reference}`);
255
- }
256
- const size = Number(header.split(" ")[2]);
257
- const body = await this.readBytes(size);
258
- await this.readBytes(1); // the trailing newline
259
- return body;
260
- }
261
- close() {
262
- this.child.stdin.end();
263
- this.child.kill();
264
- }
265
- }
266
52
  /**
267
- * Bring the scratch tree from one commit to another, and say what moved.
268
- *
269
- * Renames are asked for as a delete plus an add (`--no-renames`) rather than
270
- * as a rename. CodeRook is content-addressed, so the added path costs nothing
271
- * to store when the bytes already exist, and the alternative is carrying a
272
- * second change shape through every branch below for no benefit.
53
+ * Owner and project from whatever address git handed over:
54
+ * `https://coderook.com/owner/project.git` (after pushInsteadOf),
55
+ * `https://api.coderook.com/git/owner/project.git`, or an old
56
+ * `coderook://owner/project` / `coderook://project`.
273
57
  */
274
- async function applyCommit(catFile, scratch, fromCommit, toCommit) {
275
- const raw = git([
276
- "diff",
277
- "--name-status",
278
- "--no-renames",
279
- "-z",
280
- fromCommit,
281
- toCommit,
282
- ]);
283
- const fields = raw.split("\0").filter((field) => field.length > 0);
284
- const written = [];
285
- const deleted = [];
286
- const skipped = [];
287
- const executable = new Map();
288
- for (let index = 0; index + 1 < fields.length; index += 2) {
289
- const status = fields[index];
290
- const filePath = fields[index + 1];
291
- const target = node_path_1.default.join(scratch, filePath);
292
- if (status.startsWith("D")) {
293
- await (0, promises_1.rm)(target, { force: true });
294
- deleted.push(filePath);
295
- continue;
296
- }
297
- /*
298
- A gitlink has a mode but no bytes. Writing the commit id it points at as
299
- the file's contents would produce a forty-byte text file where a
300
- directory belongs, which is worse than not publishing it.
301
- */
302
- const mode = git(["ls-tree", "-z", toCommit, "--", filePath])
303
- .split("\0")[0]
304
- ?.split(/\s+/)[0];
305
- if (mode === "160000") {
306
- skipped.push(filePath);
307
- continue;
308
- }
309
- const bytes = await catFile.blob(`${toCommit}:${filePath}`);
310
- await (0, promises_1.mkdir)(node_path_1.default.dirname(target), { recursive: true });
311
- await (0, promises_1.writeFile)(target, bytes);
312
- written.push(filePath);
313
- executable.set(filePath, mode === "100755");
314
- }
315
- return { written, deleted, skipped, executable };
316
- }
317
- /*
318
- The service's answer when a line is already there.
319
-
320
- Matched on the wording as well as the shape because the message is the only
321
- thing that reaches here: `This project already has a track called main`. The
322
- previous test looked for "exist", which that sentence does not contain — so a
323
- branch arriving after the project had been created was reported as a hard
324
- failure rather than the ordinary "it is already there".
325
- */
326
- const TRACK_EXISTS = /already has a track|track_exists|exists/i;
327
- /**
328
- * The order refs are published in, which is not the order git sends them.
329
- *
330
- * `git push --all` hands over every branch at once, and on a project that does
331
- * not exist yet the first one creates it — along with an empty `main`. If a
332
- * side branch happens to go first it takes the whole history, and `main`
333
- * arrives to find its own line already made and nothing it can do with it:
334
- * there is no way to move an existing line's head, only to start one at a
335
- * version. The result was a project whose default line was permanently empty.
336
- *
337
- * Publishing the branch the others fork from first makes every later branch an
338
- * ordinary fork, which is the case that already worked. Local HEAD wins,
339
- * because that is what the person is standing on; `main` and `master` are the
340
- * conventional fallbacks; everything else keeps a stable order so two runs of
341
- * the same push behave the same way.
342
- */
343
- function ordered(requests) {
344
- let head = "";
345
- try {
346
- head = git(["symbolic-ref", "--short", "HEAD"]).trim();
347
- }
348
- catch {
349
- // A detached HEAD has no branch to prefer; the fallbacks still apply.
350
- }
351
- const rank = (request) => {
352
- const branch = (0, git_history_js_1.branchOf)(request.dst);
353
- if (!branch)
354
- return 4; // tags last: they name versions that must exist
355
- if (branch === head)
356
- return 0;
357
- if (branch === "main")
358
- return 1;
359
- if (branch === "master")
360
- return 2;
361
- return 3;
58
+ function projectOf(url) {
59
+ let rest = url.trim();
60
+ for (const prefix of ["coderook://", "coderook::", "coderook:"]) {
61
+ if (rest.startsWith(prefix)) {
62
+ rest = rest.slice(prefix.length);
63
+ break;
64
+ }
65
+ }
66
+ rest = rest.replace(/^https?:\/\/[^/]+\//i, "").replace(/^git\//, "").replace(/\/+$/, "").replace(/\.git$/, "");
67
+ const parts = rest.split("/").filter(Boolean);
68
+ if (parts.length >= 2)
69
+ return { owner: parts[parts.length - 2], slug: parts[parts.length - 1] };
70
+ return { owner: null, slug: parts[0] ?? "" };
71
+ }
72
+ /** The project's plain-git address on the service, which this pushes to. */
73
+ async function gitAddress(url) {
74
+ const found = projectOf(url);
75
+ if (!found.slug)
76
+ throw new Error(`"${url}" does not name a CodeRook project`);
77
+ const owner = found.owner ?? (await (0, api_js_1.whoami)()).username;
78
+ if (!owner)
79
+ throw new Error("Not signed in. Run `cbx sign-in` first.");
80
+ return { address: `${(0, config_js_1.apiOrigin)()}/git/${encodeURIComponent(owner)}/${encodeURIComponent(found.slug)}.git`, named: `${owner}/${found.slug}` };
81
+ }
82
+ /* Smaller sizes for tests: what counts as large, the most one push may carry, and the pieces. */
83
+ function tuning() {
84
+ const big = Number(node_process_1.default.env.CODEROOK_GIT_BIG_BYTES ?? "");
85
+ const most = Number(node_process_1.default.env.CODEROOK_GIT_MOST_PUSH_BYTES ?? "");
86
+ const commits = Number(node_process_1.default.env.CODEROOK_GIT_MOST_COMMITS ?? "");
87
+ return {
88
+ ...(commits > 0 ? { mostCommits: commits } : {}),
89
+ ...(big > 0 ? { bigBytes: big, profile: { ...chunking_js_1.MICRO_CHUNK_PROFILE, minSize: 4096, targetSize: 16384, maxSize: 65536, strictMask: 0x3fff, looseMask: 0x0fff } } : {}),
90
+ ...(most > 0 ? { mostPushBytes: most } : {}),
362
91
  };
363
- return [...requests].sort((left, right) => rank(left) - rank(right) || left.dst.localeCompare(right.dst));
364
92
  }
365
- /**
366
- * The refs the remote already holds, as far as we can tell.
367
- *
368
- * Git uses this to work out which commits to send, so being wrong here is
369
- * expensive in both directions: claim too much and work is silently dropped,
370
- * claim too little and a history is published twice.
371
- */
372
- async function remoteRefs(repositoryId) {
373
- const known = new Map();
374
- if (!repositoryId)
375
- return known;
376
- const state = await remoteState(repositoryId);
377
- const marks = await readMarks();
378
- for (const track of state.tracks) {
379
- if (track.kind !== "line" || !track.headVersionId)
380
- continue;
381
- const sha = headCommit(track.headVersionId, state, marks);
382
- if (sha)
383
- known.set(`refs/heads/${track.name}`, sha);
384
- }
385
- return known;
386
- }
387
- /**
388
- * Which commit *in this repository* holds a version.
389
- *
390
- * There are two answers and they are not interchangeable. The message marker
391
- * names the commit a version was published from, which is the right answer in
392
- * the repository that published it. The mark table names the commit this
393
- * repository built when it imported that version, which is the right answer in
394
- * a clone. A repository that cloned and then pushes has both, and they disagree
395
- * permanently — the imported commit is a different object with a different id.
396
- *
397
- * The mark wins, because git is about to be told this id and has to be able to
398
- * find it. Offering the marker instead makes every push from a clone fail with
399
- * "the remote has a commit you do not have", naming a commit that only exists
400
- * on somebody else's machine — which is precisely the loop this closed.
401
- */
402
- function headCommit(versionId, state, marks) {
403
- const mark = marks?.ofVersion.get(versionId);
404
- const imported = mark === undefined ? undefined : marks?.sha.get(mark);
405
- return imported ?? state.shaOfVersion.get(versionId);
406
- }
407
- /**
408
- * Everything about the project that a push needs to decide anything.
409
- *
410
- * Gathered once per push rather than per branch: it is two calls, both of
411
- * which were being made repeatedly, and having one snapshot removes the
412
- * possibility of two decisions in the same push disagreeing about what the
413
- * remote holds.
414
- */
415
- async function remoteState(repositoryId) {
416
- const tracks = await new tracks_js_1.Tracks(config_js_1.credentials).list(repositoryId);
417
- const { versions } = await Promise.resolve().then(() => __importStar(require("./api.js")));
418
- const all = await versions(repositoryId);
419
- const versionOfSha = new Map();
420
- const shaOfVersion = new Map();
421
- for (const version of all) {
422
- const sha = (0, git_history_js_1.commitFromMessage)(version.message);
423
- if (!sha)
424
- continue;
425
- versionOfSha.set(sha, version.id);
426
- shaOfVersion.set(version.id, sha);
427
- }
428
- return { tracks, versionOfSha, shaOfVersion, versionCount: all.length };
429
- }
430
- /**
431
- * The commit this branch should fork from, and the version that holds it.
432
- *
433
- * Walking the branch's own ancestry newest-first and stopping at the first
434
- * commit the project already has is the same answer `git merge-base` would
435
- * give against every pushed branch at once, without having to ask which
436
- * branches those are.
437
- */
438
- function forkPoint(tip, versionOfSha) {
439
- const ancestry = git(["rev-list", tip])
440
- .split("\n")
441
- .map((line) => line.trim())
442
- .filter(Boolean);
443
- for (const sha of ancestry) {
444
- const versionId = versionOfSha.get(sha);
445
- if (versionId)
446
- return { sha, versionId };
447
- }
448
- return null;
449
- }
450
- async function readMarks() {
451
- let gitDir;
452
- try {
453
- gitDir = git(["rev-parse", "--absolute-git-dir"]).trim();
454
- }
455
- catch {
456
- return null;
457
- }
458
- if (!gitDir)
459
- return null;
460
- const dir = node_path_1.default.join(gitDir, "coderook");
461
- const marks = {
462
- file: node_path_1.default.join(dir, "marks"),
463
- ofVersion: new Map(),
464
- sha: new Map(),
465
- dir,
466
- };
467
- try {
468
- const table = await (0, promises_1.readFile)(node_path_1.default.join(dir, "versions"), "utf8");
469
- for (const line of table.split("\n")) {
470
- const [versionId, mark] = line.trim().split(/\s+/);
471
- if (versionId && mark)
472
- marks.ofVersion.set(versionId, Number(mark));
473
- }
474
- }
475
- catch {
476
- // No table yet. Every version is new, which is correct for a clone.
477
- }
478
- try {
479
- const table = await (0, promises_1.readFile)(marks.file, "utf8");
480
- for (const line of table.split("\n")) {
481
- const match = line.trim().match(/^:(\d+)\s+([0-9a-f]{40})$/);
482
- if (match)
483
- marks.sha.set(Number(match[1]), match[2]);
484
- }
485
- }
486
- catch {
487
- // Likewise.
488
- }
489
- /*
490
- Drop any version whose mark no object ever got.
491
-
492
- The two files are written by different things at different moments, so a
493
- run that dies between them leaves a version claiming a mark that names
494
- nothing. Believing it is the worst outcome available: the next fetch
495
- reports the project already imported and hands back an empty history,
496
- silently, with no error to notice. Cross-checking here makes a half-write
497
- cost a re-import instead of a wrong answer.
498
- */
499
- for (const [versionId, mark] of [...marks.ofVersion]) {
500
- if (!marks.sha.has(mark))
501
- marks.ofVersion.delete(versionId);
502
- }
503
- return marks;
504
- }
505
- async function writeMarks(marks) {
506
- await (0, promises_1.mkdir)(marks.dir, { recursive: true });
507
- const body = [...marks.ofVersion]
508
- .map(([versionId, mark]) => `${versionId} ${mark}`)
509
- .join("\n");
510
- await (0, promises_1.writeFile)(node_path_1.default.join(marks.dir, "versions"), `${body}\n`, "utf8");
511
- }
512
- /**
513
- * Record commits this repository *pushed* in the same table imports use.
514
- *
515
- * Without this, pushing and fetching keep separate ideas of what a version is.
516
- * A repository that pushes gets a tracking ref pointing at its own commits; a
517
- * later fetch rebuilds those same versions as new commits with new ids, and
518
- * git refuses to move the ref because the two histories share no ancestor:
519
- *
520
- * not updating refs/coderook/main (new tip … does not contain …)
521
- *
522
- * Writing the pushed commits here means a later import recognises those
523
- * versions as already present, skips them, and hangs anything new off the
524
- * commit that is genuinely in this repository. One identity space, both ways.
525
- *
526
- * The fast-import marks file is written directly rather than left to
527
- * fast-import, because no import ran — the objects are already here.
528
- */
529
- async function recordPushedCommits(marks) {
530
- await (0, promises_1.mkdir)(marks.dir, { recursive: true });
531
- const table = [...marks.sha]
532
- .sort(([left], [right]) => left - right)
533
- .map(([mark, sha]) => `:${mark} ${sha}`)
534
- .join("\n");
535
- await (0, promises_1.writeFile)(marks.file, table ? `${table}\n` : "", "utf8");
536
- await writeMarks(marks);
537
- }
538
- /**
539
- * Rebuild a git history from a project's versions and write it to stdout as a
540
- * fast-import stream.
541
- *
542
- * Each version becomes one commit holding that version's complete file list,
543
- * stated with `deleteall` followed by every path. Emitting a delta instead
544
- * would be smaller and would mean tracking what the previous commit held on
545
- * every branch of the graph; restating the tree is bounded work per commit and
546
- * cannot drift.
547
- *
548
- * Contents are deduplicated by SHA-256 across the whole history, so a file
549
- * unchanged across a thousand versions is downloaded and sent to git once.
550
- */
551
- /*
552
- How many blobs a clone fetches at once, and how much it will hold doing it.
553
-
554
- Eight lanes for the same reason the folder walks use eight: these are
555
- latency, not work, and the measured curve flattens there. The byte ceiling
556
- is what stops a window of large files becoming a window of memory — one
557
- oversized file still goes through on its own, because the count check comes
558
- first and an empty window always accepts one more.
559
- */
560
- const BLOB_LANES = 8;
561
- /** Fewer new files than this, and one request for them each is quicker. */
562
- const ARCHIVE_MIN_FILES = 64;
563
- /** The share of a version's bytes that must be new before it is fetched whole. */
564
- const ARCHIVE_MIN_SHARE = 0.5;
565
- const BLOB_WINDOW_BYTES = 64 * 1024 * 1024;
566
- async function doImport(refs, url,
567
- /** From `git clone --depth N`; only honoured on a first import. */
568
- depth = null) {
569
- const { owner, slug } = (0, git_history_js_1.parseRemoteUrl)(url);
570
- const project = await (0, api_js_1.findProject)(owner ? `${owner}/${slug}` : slug);
571
- if (!project) {
572
- say(`No CodeRook project called "${owner ? `${owner}/${slug}` : slug}",` +
573
- " or you cannot read it.");
574
- /*
575
- `done` closes the stream cleanly, but git reads "no refs" as "an empty
576
- repository" and reports success — so a clone of something that is not
577
- there made an empty folder and exited zero. Saying so on the way out is
578
- what turns that into a failure the person can see.
579
- */
580
- send("done");
581
- throw new ImportFailed(`No CodeRook project called "${owner ? `${owner}/${slug}` : slug}", or you cannot read it.`);
582
- }
583
- const repositoryId = project.id;
584
- const state = await remoteState(repositoryId);
585
- const { versions } = await Promise.resolve().then(() => __importStar(require("./api.js")));
586
- const all = await versions(repositoryId);
587
- const wanted = new Map();
588
- for (const ref of refs) {
589
- const branch = (0, git_history_js_1.branchOf)(ref);
590
- if (!branch)
591
- continue;
592
- const track = state.tracks.find((candidate) => candidate.name === branch && candidate.kind === "line");
593
- if (track?.headVersionId)
594
- wanted.set(ref, track.headVersionId);
595
- else
596
- say(` no line called "${branch}" on ${slug}`);
597
- }
598
- if (!wanted.size) {
599
- send("done");
600
- return;
601
- }
602
- const order = (0, git_history_js_1.versionsInOrder)([...wanted.values()], all);
603
- const marks = await readMarks();
604
- /** SHA-256 of the contents to the fast-import mark already carrying it. */
605
- const blobMark = new Map();
606
- /** Version id to the mark of the commit built from it. */
607
- const commitMark = new Map(marks?.ofVersion ?? []);
608
- /*
609
- Numbering continues above every mark this repository already holds.
610
- Restarting at 1 would hand a new commit a mark that already names a
611
- different object, and fast-import would happily believe us.
612
- */
613
- let nextMark = 1;
614
- for (const mark of commitMark.values())
615
- nextMark = Math.max(nextMark, mark + 1);
616
- /*
617
- What this import takes, out of everything the heads can reach.
618
-
619
- Never history an earlier shallow clone left out: its first ordinary fetch
620
- would otherwise bring the lot in as a second line of commits. And on a
621
- first import with `--depth`, only that many generations of each line.
622
- */
623
- const leftOut = (0, git_history_js_1.historyLeftOut)(all, commitMark.keys());
624
- let chosen = order.filter((version) => !leftOut.has(version.id));
625
- if (depth && depth > 0) {
626
- if (commitMark.size) {
627
- say(` --depth applies to a new clone; fetching everything newer than what is here.`);
628
- }
629
- else {
630
- const keep = (0, git_history_js_1.withinDepth)([...wanted.values()], all, depth);
631
- chosen = chosen.filter((version) => keep.has(version.id));
632
- say(`Taking the newest ${depth} version${depth === 1 ? "" : "s"} of each line ` +
633
- `(--depth ${depth}); ${order.length - chosen.length} older left out.`);
634
- }
635
- }
636
- /*
637
- Point every ref git asked for at the commit its line's head became.
638
-
639
- Which ref needs what is worked out in `refPlacements`; this only says it.
640
- `reset` is idempotent, so naming a ref that a commit in this stream has
641
- already set costs a line and changes nothing.
642
- */
643
- const settleRefs = () => {
644
- const { placed, unplaceable } = (0, git_history_js_1.refPlacements)(wanted, commitMark);
645
- for (const { ref, mark } of placed) {
646
- send(`reset ${(0, git_history_js_1.importRef)(ref)}`);
647
- send(`from :${mark}`);
648
- }
649
- for (const ref of unplaceable) {
650
- say(` could not place ${ref}: no commit for its head version`);
651
- }
652
- };
653
- const fresh = chosen.filter((version) => !commitMark.has(version.id));
654
- if (!fresh.length) {
655
- say(`Already up to date with ${slug}.`);
656
- /*
657
- Still has to name the refs. "Nothing new to fetch" and "this ref does
658
- not exist" are different answers, and a line added since the last fetch
659
- is the first case while looking like the second.
660
-
661
- The marks table is loaded first because the refs are placed by mark,
662
- and without it those marks name nothing in this stream.
663
- */
664
- if (marks) {
665
- send("feature done");
666
- send(`feature import-marks-if-exists=${marks.file.replaceAll("\\", "/")}`);
667
- send(`feature export-marks=${marks.file.replaceAll("\\", "/")}`);
668
- settleRefs();
669
- }
670
- send("done");
671
- return;
672
- }
673
- say(`Importing ${fresh.length} version${fresh.length === 1 ? "" : "s"} from ${slug}` +
674
- (chosen.length > fresh.length
675
- ? ` (${chosen.length - fresh.length} already here)`
676
- : "") +
677
- ".");
678
- const { Downloader } = await Promise.resolve().then(() => __importStar(require("../../cbx/src/core/download.js")));
679
- const downloader = new Downloader(config_js_1.credentials);
680
- const scratch = await (0, promises_1.mkdtemp)(node_path_1.default.join(node_os_1.default.tmpdir(), "coderook-fetch-"));
681
- try {
682
- send("feature done");
683
- if (marks) {
684
- /*
685
- `-if-exists` because the first import has no file yet, and plain
686
- `import-marks` is a hard error when the file is missing.
687
- */
688
- send(`feature import-marks-if-exists=${marks.file.replaceAll("\\", "/")}`);
689
- send(`feature export-marks=${marks.file.replaceAll("\\", "/")}`);
690
- }
691
- let done = 0;
692
- for (const version of fresh) {
693
- const files = await downloader.files(repositoryId, version.id);
694
- /*
695
- Blobs first: fast-import requires a mark to exist before a commit
696
- names it. Fetched a window at a time and written out in order.
697
-
698
- This asked for one file, waited for it, wrote it to a scratch path,
699
- read it back, and only then asked for the next — so a clone cost one
700
- network round trip per file, in series. Against a 21,071-file project
701
- that is 21,071 round trips at about seven tenths of a second each,
702
- and a clone that never finished: measured over twenty seconds it was
703
- using 0.17s of processor and moving two kilobytes.
704
-
705
- The stream fast-import reads has to stay ordered, so the fetching is
706
- what overlaps, not the writing. The window is bounded by count and by
707
- bytes together, because sixteen source files and sixteen video files
708
- are not the same amount to be holding at once.
709
- */
710
- /* Only content not already imported: a blob is written once, by digest. */
711
- const seenBlob = new Set();
712
- const wantedBlobs = files.filter((file) => {
713
- if (blobMark.has(file.sha256) || seenBlob.has(file.sha256))
714
- return false;
715
- seenBlob.add(file.sha256);
716
- return true;
717
- });
718
- /*
719
- The whole version in one request — but only when most of it is new.
720
-
721
- The archive is every file the version holds, and this used to fetch it
722
- for every version and then keep only the files not already imported.
723
- After the first, that is nearly none of them: a five-version clone of
724
- a large project downloaded its whole snapshot five times over to use
725
- the changed files out of each, which is why an archive added to speed
726
- clones up left one taking eighty-two minutes.
727
-
728
- So it is weighed per version: where the files still wanted are at
729
- least half of the version's bytes, one request for the lot wins; where
730
- they are a handful, fetching just those does. Below a few dozen files
731
- the round trips are not worth avoiding at all.
732
-
733
- Where it is worth it, fetching per file would be one round trip each:
734
- 21,071 of them on a real Unity project, four hours in series and about
735
- half an hour even eight at a time.
736
-
737
- Anything unexpected about the archive — an entry this cannot read, a
738
- short download, a service that does not offer the route — falls
739
- through to the per-file path below, which is slow and known to work.
740
- A clone that is slow is a nuisance; a clone that writes the wrong bytes
741
- is not recoverable by trying again.
742
- */
743
- const bytesOf = (list) => list.reduce((sum, file) => sum + Number(file.sourceSize ?? 0), 0);
744
- const archiveWorthIt = wantedBlobs.length >= ARCHIVE_MIN_FILES &&
745
- bytesOf(wantedBlobs) >= bytesOf(files) * ARCHIVE_MIN_SHARE;
746
- const fromArchive = new Map();
747
- if (archiveWorthIt)
748
- try {
749
- const packed = await downloader.archive(repositoryId, version.id);
750
- for (const entry of (0, stored_zip_js_1.readStoredZip)(packed)) {
751
- fromArchive.set(entry.path, entry.bytes);
752
- }
753
- }
754
- catch (error) {
755
- /*
756
- Said out loud, not swallowed.
757
-
758
- This fell back silently, and the silence cost an hour: a deadline
759
- meant for ordinary requests was aborting the archive, the import
760
- dropped to fetching every file on its own, and from the outside it
761
- looked exactly like the slow clone the archive was added to fix.
762
- A fallback nobody can see is a fallback nobody can diagnose.
763
- */
764
- say(` the archive for v${version.sequence} could not be used ` +
765
- `(${error instanceof Error ? error.message : String(error)}); ` +
766
- `fetching its files one by one`);
767
- fromArchive.clear();
768
- }
769
- for (let at = 0; at < wantedBlobs.length;) {
770
- const window = [];
771
- let held = 0;
772
- while (at < wantedBlobs.length && window.length < BLOB_LANES) {
773
- const size = Number(wantedBlobs[at].sourceSize ?? 0);
774
- if (window.length > 0 && held + size > BLOB_WINDOW_BYTES)
775
- break;
776
- held += size;
777
- window.push(wantedBlobs[at]);
778
- at += 1;
779
- }
780
- const fetched = await Promise.all(window.map(async (file, lane) => {
781
- /* Already in hand, if the archive carried it. */
782
- const packed = fromArchive.get(file.path);
783
- if (packed)
784
- return { file, bytes: packed };
785
- /*
786
- A scratch path per lane. They shared one name, which is fine
787
- while only one download is ever in flight and silently wrong
788
- the moment two are.
789
- */
790
- const target = node_path_1.default.join(scratch, `blob-${lane}.bin`);
791
- await (0, promises_1.rm)(target, { force: true });
792
- await downloader.fileTo(repositoryId, version.id, file, target);
793
- return { file, bytes: await (0, promises_1.readFile)(target) };
794
- }));
795
- for (const { file, bytes } of fetched) {
796
- const mark = nextMark++;
797
- blobMark.set(file.sha256, mark);
798
- send("blob");
799
- send(`mark :${mark}`);
800
- send(`data ${bytes.length}`);
801
- node_process_1.default.stdout.write(bytes);
802
- node_process_1.default.stdout.write("\n");
803
- }
804
- }
805
- const mark = nextMark++;
806
- commitMark.set(version.id, mark);
807
- marks?.ofVersion.set(version.id, mark);
808
- const ref = [...wanted.entries()].find(([, head]) => head === version.id)?.[0] ??
809
- `refs/heads/${state.tracks.find((track) => track.headVersionId === version.id)?.name ?? "main"}`;
810
- const parents = version.parentVersionIds
811
- .map((parent) => commitMark.get(parent))
812
- .filter((value) => value !== undefined);
813
- const author = version.authorName || "CodeRook";
814
- const when = `${(0, git_history_js_1.stamp)(version.createdAt)} +0000`;
815
- const message = (0, git_history_js_1.messageWithoutMarker)(version.message) || `Version ${version.sequence}`;
816
- const body = Buffer.from(message, "utf8");
817
- send(`commit ${(0, git_history_js_1.importRef)(ref)}`);
818
- send(`mark :${mark}`);
819
- /*
820
- No email is invented. CodeRook records who published a version, not an
821
- address, and a plausible-looking address that belongs to nobody is
822
- worse than an obviously synthetic one: it survives being copied into a
823
- mailing list or a CONTRIBUTORS file.
824
- */
825
- send(`author ${identity(author)} <noreply@coderook.com> ${when}`);
826
- send(`committer ${identity(author)} <noreply@coderook.com> ${when}`);
827
- send(`data ${body.length}`);
828
- node_process_1.default.stdout.write(body);
829
- node_process_1.default.stdout.write("\n");
830
- if (parents[0] !== undefined)
831
- send(`from :${parents[0]}`);
832
- for (const extra of parents.slice(1))
833
- send(`merge :${extra}`);
834
- send("deleteall");
835
- for (const file of files) {
836
- /*
837
- Never into git's own directory. Git would refuse to check one out,
838
- but it would sit in the history of every clone; new versions cannot
839
- hold one, and this keeps older ones from carrying it into git.
840
- */
841
- if (file.path.split("/").some(safe_path_js_1.isGitDirectoryName))
842
- continue;
843
- send(`M ${file.executable ? "100755" : "100644"} :${blobMark.get(file.sha256)} ${(0, git_history_js_1.quotePath)(file.path)}`);
844
- }
845
- send("");
846
- done += 1;
847
- if (done % 10 === 0 || done === fresh.length) {
848
- say(` ${done}/${fresh.length} versions`);
849
- }
850
- }
851
- /*
852
- What each save says about itself, as git notes.
853
-
854
- A CodeRook save carries a description separate from its message — the
855
- thing the website shows as release info and `cbx notes` writes — and a
856
- fetch used to drop all of it except on the few versions that were also
857
- releases. Git's answer for text attached to a commit without changing
858
- the commit is a note, so that is where it goes: `git log
859
- --notes=coderook` shows them, and pushing them back returns them.
860
-
861
- Written as one commit on its own ref after every version commit exists,
862
- because a note has to name a commit that is already in the stream.
863
- */
864
- const described = fresh.filter((version) => (version.notes ?? "").trim());
865
- if (described.length) {
866
- send(`commit ${(0, git_history_js_1.importRef)(NOTES_REF)}`);
867
- send(`committer CodeRook <noreply@coderook.com> ` +
868
- `${(0, git_history_js_1.stamp)(new Date().toISOString())} +0000`);
869
- const why = Buffer.from("What each save says about itself\n", "utf8");
870
- send(`data ${why.length}`);
871
- node_process_1.default.stdout.write(why);
872
- node_process_1.default.stdout.write("\n");
873
- for (const version of described) {
874
- const mark = commitMark.get(version.id);
875
- if (mark === undefined)
876
- continue;
877
- const body = Buffer.from(`${(version.notes ?? "").trim()}\n`, "utf8");
878
- send(`N inline :${mark}`);
879
- send(`data ${body.length}`);
880
- node_process_1.default.stdout.write(body);
881
- node_process_1.default.stdout.write("\n");
882
- }
883
- say(` ${described.length} description${described.length === 1 ? "" : "s"} as git notes`);
884
- }
885
- /* Every ref git asked for, named outright now the commits exist. */
886
- settleRefs();
887
- /*
888
- Releases come back as tags, because that is the same statement in the
889
- other vocabulary: a version somebody gave a name to.
890
-
891
- Emitted after every commit, so the mark a tag points at is certain to
892
- exist. A release naming a version outside the branches being imported is
893
- skipped rather than guessed at — the tag would have nothing to point to.
894
- */
895
- try {
896
- const { releases } = await Promise.resolve().then(() => __importStar(require("./api.js")));
897
- const named = await releases(repositoryId);
898
- let tagged = 0;
899
- for (const release of named) {
900
- const mark = commitMark.get(release.versionId);
901
- if (mark === undefined)
902
- continue;
903
- const body = Buffer.from(release.notes || release.name, "utf8");
904
- const tagName = release.name.replace(/[\s~^:?*[\\\x00-\x1f]/g, "-");
905
- if (!tagName || tagName.startsWith("-") || tagName.includes(".."))
906
- continue;
907
- send(`tag ${tagName}`);
908
- send(`from :${mark}`);
909
- send(`tagger ${identity(release.releasedBy || "CodeRook")} <noreply@coderook.com> ` +
910
- `${(0, git_history_js_1.stamp)(release.releasedAt)} +0000`);
911
- send(`data ${body.length}`);
912
- node_process_1.default.stdout.write(body);
913
- node_process_1.default.stdout.write("\n");
914
- tagged += 1;
915
- }
916
- if (tagged)
917
- say(` ${tagged} release${tagged === 1 ? "" : "s"} as tags`);
918
- }
919
- catch (error) {
920
- // A project whose releases cannot be read is still worth importing.
921
- say(` could not read releases: ${error.message}`);
922
- }
923
- send("done");
924
- /*
925
- Written after the stream, not during. fast-import only writes its own
926
- mark file when it finishes, so a table saved earlier would name marks
927
- that no object ever got — and the next fetch would build commits whose
928
- parents do not exist.
929
- */
930
- if (marks)
931
- await writeMarks(marks);
932
- }
933
- finally {
934
- await (0, promises_1.rm)(scratch, { recursive: true, force: true });
935
- }
936
- }
937
- async function doPush(requests, url, options = {}) {
938
- /*
939
- A push never goes to the account named in the URL — it goes to the one the
940
- token belongs to. Publishing somebody's work to a different account on
941
- their behalf would be the worse mistake of the two.
942
-
943
- But it is not enough to ignore the name, now that fetching honours it.
944
- The same URL would then read from one account and write to another: a
945
- push to `coderook://somebody/their-project` quietly made a private
946
- project of that name on your own account and reported success, while git
947
- printed "To coderook://somebody/their-project". Saying no is the honest
948
- answer, and it leaves the person a working one.
949
- */
950
- const { owner, slug } = (0, git_history_js_1.parseRemoteUrl)(url);
951
- if (owner) {
952
- const me = await (0, api_js_1.whoami)().catch(() => null);
953
- const mine = (me?.username ?? "").toLowerCase();
954
- if (mine && owner.toLowerCase() !== mine) {
955
- say(`This remote names ${owner}, and you are signed in as ${mine}.` +
956
- ` A push goes to your own account, so it would land somewhere the` +
957
- ` URL does not name.`);
958
- say(`To publish your own copy: git remote set-url origin coderook://${mine}/${slug}`);
959
- for (const request of requests) {
960
- send(`error ${request.dst} this remote belongs to ${owner}, not to ${mine}`);
961
- }
962
- send("");
963
- return;
964
- }
965
- }
966
- const marks = await readMarks();
967
- /*
968
- Re-read the project before every ref, not once before the batch.
969
-
970
- `git push --all` sends every branch in one batch, and the first of them
971
- routinely creates the project. Reading the state once meant every later
972
- ref in that same push still believed the project did not exist: it
973
- published against a null repository, started its history from nothing, and
974
- left its line without a head. Pushing two branches to a new project
975
- produced one working line and one empty one, and reported success for
976
- both — which is the shape a whole-repository transfer takes, so it failed
977
- exactly where it mattered most.
978
-
979
- One extra listing per ref. A push carries a handful of refs and each one
980
- publishes versions costing seconds, so the cost is not worth the class of
981
- bug avoiding it creates.
982
- */
983
- let repositoryId = (await (0, api_js_1.findProject)(slug))?.id ?? null;
984
- let state = repositoryId
985
- ? await remoteState(repositoryId)
986
- : null;
987
- const refreshProject = async () => {
988
- if (!repositoryId)
989
- repositoryId = (await (0, api_js_1.findProject)(slug))?.id ?? null;
990
- state = repositoryId ? await remoteState(repositoryId) : null;
991
- /*
992
- A clone knows commits the messages do not name: the ones it built when
993
- it imported each version. Counted as published, so a branch started in
994
- a clone forks from the version it was cloned at — and a clone of a
995
- project saved with `cbx submit` is not mistaken for unrelated history.
996
- */
997
- if (state && marks) {
998
- for (const [versionId, mark] of marks.ofVersion) {
999
- const sha = marks.sha.get(mark);
1000
- if (sha && !state.versionOfSha.has(sha))
1001
- state.versionOfSha.set(sha, versionId);
1002
- }
1003
- }
1004
- };
1005
- const knownRefs = () => {
1006
- const found = new Map();
1007
- for (const track of state?.tracks ?? []) {
1008
- if (track.kind !== "line" || !track.headVersionId)
1009
- continue;
1010
- const sha = headCommit(track.headVersionId, state, marks);
1011
- if (sha)
1012
- found.set(`refs/heads/${track.name}`, sha);
1013
- }
1014
- return found;
1015
- };
1016
- let known = knownRefs();
1017
- let nextPushMark = 1;
1018
- for (const mark of marks?.sha.keys() ?? []) {
1019
- nextPushMark = Math.max(nextPushMark, mark + 1);
1020
- }
1021
- const uploader = new upload_js_1.Uploader(config_js_1.credentials);
1022
- const catFile = new CatFile();
1023
- const scratch = await (0, promises_1.mkdtemp)(node_path_1.default.join(node_os_1.default.tmpdir(), "coderook-push-"));
1024
- let warnedAboutMerges = false;
1025
- try {
1026
- for (const request of ordered(requests)) {
1027
- /*
1028
- Whatever the previous ref did, this one starts from what the project
1029
- actually holds now — including a project the previous ref created.
1030
- */
1031
- await refreshProject();
1032
- known = knownRefs();
1033
- /*
1034
- A tag names a version, which is exactly what a CodeRook release is:
1035
- "a Version with a name on it, not a different kind of object". So a tag
1036
- does not publish anything — it finds the version the tagged commit
1037
- already became and gives it that name. Pushing a tag for a commit that
1038
- was never pushed is refused rather than guessed at.
1039
- */
1040
- const tag = (0, git_history_js_1.tagOf)(request.dst);
1041
- if (tag) {
1042
- if (!request.src) {
1043
- send(`error ${request.dst} deleting a tag is not supported`);
1044
- continue;
1045
- }
1046
- if (!state) {
1047
- send(`error ${request.dst} push a branch before tagging it`);
1048
- continue;
1049
- }
1050
- const target = git(["rev-list", "-n", "1", request.src]).trim();
1051
- const versionId = state.versionOfSha.get(target);
1052
- if (!versionId) {
1053
- send(`error ${request.dst} commit ${target.slice(0, 8)} has not been pushed to CodeRook yet`);
1054
- say(`\n Push the branch first, then push the tag.\n`);
1055
- continue;
1056
- }
1057
- /*
1058
- An annotated tag carries a message and a lightweight one does not.
1059
- `for-each-ref` gives the annotation only for the former, and reading
1060
- the commit's message instead would put the commit text on the
1061
- release, which is a different thing that happens to be nearby.
1062
- */
1063
- /*
1064
- Only an annotated tag has a message of its own. `%(contents)` on a
1065
- lightweight tag falls through to the commit it points at, so asking
1066
- for it unconditionally puts the commit's message on the release —
1067
- text nobody wrote about the release, presented as release notes.
1068
-
1069
- `%(objecttype)` separates the two: `tag` for an annotated one, and
1070
- `commit` for a lightweight tag, which points straight at the commit
1071
- and carries nothing.
1072
- */
1073
- const described = git([
1074
- "for-each-ref",
1075
- "--format=%(objecttype)%0a%(contents)",
1076
- request.dst,
1077
- ]);
1078
- const newline = described.indexOf("\n");
1079
- const kind = (newline === -1 ? described : described.slice(0, newline)).trim();
1080
- const notes = kind === "tag" && newline !== -1 ? described.slice(newline + 1).trim() : "";
1081
- try {
1082
- const { markRelease, releases } = await Promise.resolve().then(() => __importStar(require("./api.js")));
1083
- /*
1084
- A version carries one name, so two tags on the same commit cannot
1085
- both survive — the second renames the release the first made. Git
1086
- allows it and CodeRook cannot represent it, and quietly dropping a
1087
- release somebody just published is the wrong way to find that out.
1088
- */
1089
- const existing = await releases(repositoryId).catch(() => []);
1090
- const already = existing.find((release) => release.versionId === versionId && release.name !== tag);
1091
- if (already) {
1092
- say(` note: v${already.sequence} was already released as "${already.name}".
1093
- ` +
1094
- ` A version carries one name, so it is now "${tag}".`);
1095
- }
1096
- await markRelease(repositoryId, versionId, tag, notes || null);
1097
- send(`ok ${request.dst}`);
1098
- say(` released "${tag}" at ${target.slice(0, 8)}`);
1099
- }
1100
- catch (error) {
1101
- send(`error ${request.dst} ${error instanceof Error ? error.message : String(error)}`);
1102
- }
1103
- continue;
1104
- }
1105
- const branch = (0, git_history_js_1.branchOf)(request.dst);
1106
- if (!branch) {
1107
- send(`error ${request.dst} only branches and tags can be pushed to CodeRook`);
1108
- continue;
1109
- }
1110
- if (!request.src) {
1111
- send(`error ${request.dst} deleting a branch is not supported; CodeRook versions are immutable`);
1112
- continue;
1113
- }
1114
- /*
1115
- Refused rather than quietly treated as an ordinary push. A force push
1116
- means "make the remote match me, discarding what is there", and a
1117
- published version cannot be unpublished — so the one thing the person
1118
- asked for is the one thing that cannot happen. Accepting it and
1119
- appending instead would be a different operation wearing its name.
1120
- */
1121
- if (request.force) {
1122
- send(`error ${request.dst} force pushing is not supported; published versions are immutable and cannot be discarded`);
1123
- continue;
1124
- }
1125
- const tip = git(["rev-parse", request.src]).trim();
1126
- const already = known.get(request.dst);
1127
- if (already === tip) {
1128
- send(`ok ${request.dst}`);
1129
- say(` ${branch}: already up to date`);
1130
- continue;
1131
- }
1132
- /*
1133
- Refuse a push that is not a fast-forward, the way git itself does.
1134
-
1135
- Left alone, the publish still succeeds: the service notices the
1136
- divergence, keeps both sides and opens a merge track. That is the right
1137
- behaviour for the desktop app and exactly the wrong end state here,
1138
- because the person is standing in git and a merge track is not
1139
- something git can see, let alone resolve — they would be told the push
1140
- failed while their work sat in a queue that only `cbx merge` can
1141
- empty.
1142
-
1143
- Rejecting first keeps the whole loop inside git: pull, merge, push.
1144
- Nothing is uploaded, so there is nothing stranded to clean up.
1145
- */
1146
- if (already) {
1147
- if (!gitOk(["cat-file", "-e", `${already}^{commit}`])) {
1148
- send(`error ${request.dst} the remote has commit ${already.slice(0, 8)}, which this repository does not have; run "git fetch" first`);
1149
- continue;
1150
- }
1151
- if (!gitOk(["merge-base", "--is-ancestor", already, tip])) {
1152
- send(`error ${request.dst} non-fast-forward; the remote has work you do not have locally`);
1153
- say(`\n Someone published to "${branch}" since you last fetched.\n` +
1154
- ` git pull --rebase coderook ${branch}\n` +
1155
- ` then push again. Nothing was uploaded.\n`);
1156
- continue;
1157
- }
1158
- }
1159
- /*
1160
- A project whose versions cannot be tied to any commit is refused
1161
- rather than appended to. Those versions are real work — published from
1162
- the desktop app, the CLI or an import — and replaying a git history on
1163
- top of them would interleave two unrelated sequences with no way back.
1164
-
1165
- The test is whether the project came from git *at all*, not whether
1166
- this particular branch is known. Checking the branch instead refuses
1167
- the ordinary act of pushing a second branch to a project git already
1168
- owns, which is the common case and not a conflict of any kind.
1169
- */
1170
- /*
1171
- Unless the person says this repository *is* that project.
1172
-
1173
- The usual way here is a working repository whose CodeRook project was
1174
- started with `cbx submit` or the desktop app: same files, different
1175
- history. Refusing outright sent people to make a second project, which
1176
- is the duplicate this exists to prevent. `-o adopt` takes the middle
1177
- road: the project's saves stay as they are, this commit's tree is saved
1178
- on top as one save that names the commit, and from then on the project
1179
- and the repository agree, so later pushes add one save per commit.
1180
- */
1181
- let adopting = null;
1182
- if (state && !already && state.versionCount > 0 && state.versionOfSha.size === 0) {
1183
- const line = state.tracks.find((candidate) => candidate.name === branch && candidate.kind === "line");
1184
- if (options.adopt && line?.headVersionId) {
1185
- adopting = { headVersionId: line.headVersionId };
1186
- say(` adopting "${slug}": its ${state.versionCount} save${state.versionCount === 1 ? "" : "s"} stay as they are;` +
1187
- ` ${tip.slice(0, 8)} is saved on top as one save,\n and later pushes add one save per commit.`);
1188
- }
1189
- else {
1190
- send(`error ${request.dst} the project "${slug}" already has ${state.versionCount} version${state.versionCount === 1 ? "" : "s"} that did not come from git; pushing would publish this history a second time`);
1191
- say(options.adopt
1192
- ? `\n The project has no line called "${branch}" to adopt. Push the branch it saves on, usually main.\n`
1193
- : `\n If this repository holds that project, save it on top and link the two:\n` +
1194
- ` git push -o adopt coderook ${branch}\n` +
1195
- ` Your git history is not replayed; the commit you push becomes one save,\n` +
1196
- ` and every push after it sends one save per commit.\n\n` +
1197
- ` Or start from the project instead: git clone coderook://${slug}\n`);
1198
- continue;
1199
- }
1200
- }
1201
- /*
1202
- A branch the project has never seen starts at the newest commit it
1203
- *has* seen — its fork point — rather than at the project head. Starting
1204
- a track at the head would give the branch every change made on the
1205
- line it forked away from, which is precisely the work the person
1206
- branched to avoid.
1207
- */
1208
- let fork = null;
1209
- if (!already && state && state.versionOfSha.size > 0) {
1210
- fork = forkPoint(tip, state.versionOfSha);
1211
- }
1212
- const from = already ?? fork?.sha ?? null;
1213
- const range = from ? `${from}..${tip}` : tip;
1214
- const commits = adopting
1215
- ? [tip]
1216
- : git(["rev-list", "--reverse", "--topo-order", range])
1217
- .split("\n")
1218
- .map((line) => line.trim())
1219
- .filter(Boolean);
1220
- if (!commits.length) {
1221
- /*
1222
- Nothing to publish does not mean nothing to do. A branch whose tip
1223
- the project already holds — one merged into another branch, most
1224
- often — still has to exist as a line, or the push reports a new
1225
- branch that is not there and the next push agrees it is up to date.
1226
- */
1227
- if (!already && fork && repositoryId) {
1228
- try {
1229
- await new tracks_js_1.Tracks(config_js_1.credentials).create(repositoryId, branch, fork.versionId);
1230
- say(` created line "${branch}" at ${fork.sha.slice(0, 8)} (already published)`);
1231
- }
1232
- catch (error) {
1233
- const text = error instanceof Error ? error.message : String(error);
1234
- if (!TRACK_EXISTS.test(text)) {
1235
- send(`error ${request.dst} ${text}`);
1236
- continue;
1237
- }
1238
- }
1239
- }
1240
- send(`ok ${request.dst}`);
1241
- continue;
1242
- }
1243
- /*
1244
- Said before the work starts, not after. Each commit becomes a save on
1245
- the project and saves are not free to make, so somebody pushing years
1246
- of history deserves the chance to stop and import a snapshot instead.
1247
-
1248
- "to publish as versions" is what this used to say, and it stopped
1249
- being true when commits and versions separated: a pushed commit is a
1250
- save that nobody outside the project can see. Publishing one is what
1251
- pushing a *tag* does, because a tag is a name and a named save is a
1252
- version.
1253
- */
1254
- const estimate = Math.round((commits.length * 11) / 60);
1255
- say(` ${commits.length} commit${commits.length === 1 ? "" : "s"} to send as save${commits.length === 1 ? "" : "s"}` +
1256
- (commits.length > 20 ? ` — roughly ${estimate} minute${estimate === 1 ? "" : "s"}` : ""));
1257
- /*
1258
- A push that continues a branch has to start from where the branch
1259
- actually is, in three separate senses, and getting any one of them
1260
- wrong fails differently:
1261
-
1262
- - `previous` is the commit the remote already holds. Diffing from the
1263
- empty tree instead would mark every file as added and republish the
1264
- whole project as though it were new.
1265
- - `baseVersionId` is the version this publish is based on. Sending
1266
- null claims the project is empty, and the service correctly refuses
1267
- rather than laying this history over somebody's work.
1268
- - `local`/`known` is what the remote holds now. Without it, a file
1269
- present in the version but not in our scratch tree is
1270
- indistinguishable from one this push deleted — and the service would
1271
- drop it.
1272
- */
1273
- let baseVersionId = null;
1274
- let manifest = {};
1275
- let local = {};
1276
- let previous = git_history_js_1.EMPTY_TREE;
1277
- let currentRepositoryId = repositoryId;
1278
- let published = 0;
1279
- if (adopting && repositoryId) {
1280
- baseVersionId = adopting.headVersionId;
1281
- const { Downloader } = await Promise.resolve().then(() => __importStar(require("../../cbx/src/core/download.js")));
1282
- const held = await new Downloader(config_js_1.credentials).files(repositoryId, baseVersionId);
1283
- manifest = Object.fromEntries(held.map((file) => [file.path, file.sha256]));
1284
- local = { ...manifest };
1285
- }
1286
- else if (from && repositoryId && state) {
1287
- previous = from;
1288
- if (already) {
1289
- const track = state.tracks.find((candidate) => candidate.name === branch && candidate.kind === "line");
1290
- if (!track?.headVersionId) {
1291
- send(`error ${request.dst} could not read the current head of "${branch}"`);
1292
- continue;
1293
- }
1294
- baseVersionId = track.headVersionId;
1295
- }
1296
- else if (fork) {
1297
- /*
1298
- The track has to exist before anything can be published onto it,
1299
- and it has to start at the fork point. `create` is allowed to fail
1300
- with "already exists" — another push may have made it — in which
1301
- case the existing one is what we wanted anyway.
1302
- */
1303
- baseVersionId = fork.versionId;
1304
- try {
1305
- await new tracks_js_1.Tracks(config_js_1.credentials).create(repositoryId, branch, fork.versionId);
1306
- say(` created line "${branch}" from ${fork.sha.slice(0, 8)}`);
1307
- }
1308
- catch (error) {
1309
- const text = error instanceof Error ? error.message : String(error);
1310
- if (!TRACK_EXISTS.test(text))
1311
- throw error;
1312
- }
1313
- }
1314
- const { Downloader } = await Promise.resolve().then(() => __importStar(require("../../cbx/src/core/download.js")));
1315
- const held = await new Downloader(config_js_1.credentials).files(repositoryId, baseVersionId);
1316
- manifest = Object.fromEntries(held.map((file) => [file.path, file.sha256]));
1317
- local = { ...manifest };
1318
- }
1319
- for (const sha of commits) {
1320
- const parents = git(["rev-list", "--parents", "-n", "1", sha])
1321
- .trim()
1322
- .split(/\s+/)
1323
- .slice(1);
1324
- if (parents.length > 1 && !warnedAboutMerges) {
1325
- warnedAboutMerges = true;
1326
- say(` note: a merge commit arrives as one save holding the merged ` +
1327
- `tree.\n The contents are exact; the branch shape is not kept.`);
1328
- }
1329
- const changes = await applyCommit(catFile, scratch, previous, sha);
1330
- previous = sha;
1331
- if (adopting) {
1332
- /*
1333
- The commit's tree is the whole truth: what the project holds and
1334
- the commit does not is removed, exactly as a later push would.
1335
- */
1336
- const inTree = new Set(git(["ls-tree", "-r", "-z", "--name-only", sha]).split("\0").filter(Boolean));
1337
- for (const file of Object.keys(manifest)) {
1338
- if (!inTree.has(file) && !changes.deleted.includes(file))
1339
- changes.deleted.push(file);
1340
- }
1341
- }
1342
- if (changes.skipped.length) {
1343
- say(` skipped ${changes.skipped.length} submodule path(s) in ${sha.slice(0, 8)}`);
1344
- }
1345
- if (!changes.written.length && !changes.deleted.length) {
1346
- // An empty commit, or one that only touched submodules. Nothing to
1347
- // publish, but the ref still has to end up pointing at it.
1348
- published += 1;
1349
- continue;
1350
- }
1351
- const subject = git(["log", "-1", "--format=%B", sha]).trim();
1352
- /*
1353
- Built by the shared description rather than assembled here. Every
1354
- sharp edge in that contract — deletions in both lists, `known`,
1355
- compare-and-swap on the base version — was learned once by
1356
- `cbx submit` and then learned again here, as a bug.
1357
- */
1358
- const uploadRequest = (0, publish_js_1.uploadRequestFor)({
1359
- localPath: scratch,
1360
- changed: changes.written,
1361
- deleted: changes.deleted,
1362
- message: (0, git_history_js_1.messageWithCommit)(subject || `Commit ${sha.slice(0, 8)}`, sha),
1363
- projectName: slug,
1364
- repositoryId: currentRepositoryId,
1365
- baseVersionId,
1366
- track: branch,
1367
- allowIgnored: true,
1368
- executable: changes.executable,
1369
- ...(Object.keys(manifest).length ? { known: local } : {}),
1370
- });
1371
- let result;
1372
- try {
1373
- const plan = await uploader.plan(uploadRequest, () => { });
1374
- result = await uploader.execute(uploadRequest, plan, () => { });
1375
- }
1376
- catch (error) {
1377
- const failure = (0, publish_js_1.classifyPublishFailure)(error);
1378
- if (failure?.kind === "interrupted") {
1379
- /*
1380
- Said rather than left to be assumed. The service records the
1381
- attempt, so pushing again is answered with the version it
1382
- already made — somebody not told this will assume the push half
1383
- happened and go looking for a way to undo it.
1384
- */
1385
- send(`error ${request.dst} the connection failed part way through`);
1386
- say(`
1387
- ${published} of ${commits.length} commits were published.
1388
- ` +
1389
- ` Push again — commits already published are not sent twice.
1390
- `);
1391
- throw error;
1392
- }
1393
- if (failure?.kind === "credentials") {
1394
- /*
1395
- The one refusal a push cannot answer. `cbx submit` can ask and
1396
- be told yes; git has nowhere to put that question, so the way
1397
- through is to take the key out — which is the better answer
1398
- anyway.
1399
- */
1400
- send(`error ${request.dst} this commit carries a credential`);
1401
- say(`
1402
- ${failure.message}
1403
- `);
1404
- /*
1405
- Deleting the file in a later commit does not help, and saying
1406
- "take it out and commit again" sends people in circles: a push
1407
- publishes every commit as its own version, so the commit that
1408
- introduced the key still carries it however many commits follow.
1409
- The history has to lose it.
1410
- */
1411
- say(` A later commit that deletes it is not enough — every commit` +
1412
- ` being pushed
1413
- becomes a version, and the one that added` +
1414
- ` the key still carries it.
1415
- ` +
1416
- ` Rewrite it out (git rebase -i, or git commit --amend if it` +
1417
- ` is the last one),
1418
- or publish this deliberately with` +
1419
- ` cbx submit --allow-secrets.
1420
- `);
1421
- /*
1422
- Reported already, and in more detail than the wrapper can. The
1423
- marker stops the bin printing the same paragraph a second time.
1424
- */
1425
- throw new AlreadyReported(failure.message);
1426
- }
1427
- if (failure?.kind === "conflict") {
1428
- send(`error ${request.dst} somebody published to "${branch}" while this push was running`);
1429
- say(`
1430
- git fetch, then push again.
1431
- `);
1432
- throw error;
1433
- }
1434
- throw error;
1435
- }
1436
- if (result.mergeTrack) {
1437
- send(`error ${request.dst} somebody else published to "${branch}" during this push; it is waiting on a merge`);
1438
- throw new Error("push interrupted by a concurrent publish");
1439
- }
1440
- currentRepositoryId = result.repositoryId;
1441
- baseVersionId = result.versionId;
1442
- /*
1443
- A note on the commit becomes what the version says about itself.
1444
-
1445
- CodeRook lets a save be described before anybody decides to publish
1446
- it, and git has exactly one place for text attached to a commit
1447
- without altering it. Sent after the publish rather than with it,
1448
- because a note is not part of what was saved and a failure to
1449
- record one must not fail the push.
1450
- */
1451
- const note = noteOn(sha);
1452
- if (note) {
1453
- try {
1454
- const { changeVersion } = await Promise.resolve().then(() => __importStar(require("./api.js")));
1455
- await changeVersion(result.repositoryId, result.versionId, {
1456
- notes: note,
1457
- });
1458
- }
1459
- catch {
1460
- say(` note: the description on ${sha.slice(0, 8)} could not be saved`);
1461
- }
1462
- }
1463
- /*
1464
- The version and the commit it came from are the same thing in this
1465
- repository from here on. Recorded so a later fetch does not rebuild
1466
- it as a second, different commit.
1467
- */
1468
- if (marks) {
1469
- const mark = nextPushMark++;
1470
- marks.ofVersion.set(result.versionId, mark);
1471
- marks.sha.set(mark, sha);
1472
- }
1473
- manifest = result.manifest;
1474
- local = result.local;
1475
- published += 1;
1476
- say(` [${published}/${commits.length}] v${result.sequence} ${sha.slice(0, 8)} ${subject.split("\n")[0].slice(0, 48)}`);
1477
- }
1478
- send(`ok ${request.dst}`);
1479
- }
1480
- }
1481
- finally {
1482
- catFile.close();
1483
- await (0, promises_1.rm)(scratch, { recursive: true, force: true });
1484
- if (marks)
1485
- await recordPushedCommits(marks);
1486
- }
1487
- send("");
1488
- }
1489
- /** Read stdin as lines. The push protocol is text throughout. */
1490
93
  async function* lines() {
1491
94
  let buffer = "";
1492
95
  for await (const chunk of node_process_1.default.stdin) {
@@ -1503,158 +106,48 @@ async function* lines() {
1503
106
  }
1504
107
  async function main(argv) {
1505
108
  const url = argv[1] ?? argv[0] ?? "";
1506
- /*
1507
- The real version, not the word "git-remote". This passed its own name
1508
- where the version belongs, so the service applied its version floor and
1509
- refused to serve files — `git clone` failed with a demand to update to a
1510
- release older than the one running. Push was unaffected, which is why it
1511
- went unnoticed until a clone.
1512
- */
1513
109
  (0, identify_js_1.declareClient)("cli", version_js_1.VERSION);
1514
110
  const pending = [];
1515
- const importing = [];
1516
- /*
1517
- Whether a fetch asked for something that is not there. Git reads "no
1518
- refs" as "an empty repository" and reports success, so without this a
1519
- clone of a project you cannot see left an empty folder and exited zero.
1520
- */
1521
- let unservable = false;
1522
- /** `git clone --depth N`, when git passed one. */
1523
- let depth = null;
1524
- /** `git push -o adopt`. */
1525
- let adopt = false;
111
+ let failed = false;
1526
112
  for await (const line of lines()) {
1527
113
  const command = line.trim();
1528
114
  if (command === "capabilities") {
1529
- // `push` rather than `export`, and `import` rather than `fetch`; see the
1530
- // note at the top of this file.
1531
- send("import");
1532
115
  send("push");
1533
- send("refspec refs/heads/*:refs/coderook/*");
1534
116
  send("option");
1535
117
  send("");
1536
118
  continue;
1537
119
  }
1538
120
  if (command.startsWith("option ")) {
1539
- /*
1540
- Only what is actually acted on is accepted: answering "ok" to anything
1541
- else would make git believe a setting took effect. Depth is honoured
1542
- by importing fewer versions; git passes it for `clone --depth`.
1543
- */
1544
- const [, name, value] = command.split(" ");
1545
- if (name === "depth" && /^[1-9][0-9]*$/.test(value ?? "")) {
1546
- depth = Number(value);
1547
- send("ok");
1548
- }
1549
- else if (name === "push-option" && value === "adopt") {
1550
- /* `git push -o adopt`: see the adopting note in doPush. */
1551
- adopt = true;
1552
- send("ok");
1553
- }
1554
- else {
1555
- send("unsupported");
1556
- }
121
+ send("unsupported");
1557
122
  continue;
1558
123
  }
1559
- if (command === "list" || command === "list for-push") {
124
+ if (command === "list") {
125
+ /* A fetch: plain git does that now, and this helper no longer can. */
126
+ const { owner, slug } = projectOf(url);
127
+ say("CodeRook's coderook:// remotes are retired: CodeRook speaks plain git now.\n" +
128
+ `Point this remote at https://coderook.com/${owner ?? "<you>"}/${slug}.git, for example:\n` +
129
+ ` git remote set-url origin https://coderook.com/${owner ?? "<you>"}/${slug}.git\n` +
130
+ "then run `coderook git setup` once, so pushes of any size work.");
131
+ failed = true;
132
+ break;
133
+ }
134
+ if (command === "list for-push") {
1560
135
  try {
1561
- const { owner, slug } = (0, git_history_js_1.parseRemoteUrl)(url);
1562
- const named = owner ? `${owner}/${slug}` : slug;
1563
- const project = await (0, api_js_1.findProject)(named);
1564
- /*
1565
- A fetch of something that is not there has to say so here.
1566
-
1567
- Git asks `list` first and only asks to import the refs it is
1568
- offered, so a project nobody can read never reaches the import at
1569
- all — it is simply a listing with nothing in it, which git reports
1570
- as an empty repository and calls a success. Refusing at this point
1571
- is the only place the answer can still be "no".
1572
-
1573
- `list for-push` is exempt: pushing to a name that does not exist
1574
- yet is how a project gets created.
1575
- */
1576
- if (command === "list" && !project) {
1577
- say(`No CodeRook project called "${named}", or you cannot read it.`);
1578
- unservable = true;
1579
- /*
1580
- The listing is deliberately left unterminated.
1581
-
1582
- An empty but well-formed list is a valid answer meaning "an empty
1583
- repository", and git takes it as one: it reports success, leaves
1584
- a folder with nothing but .git in it, and ignores whatever the
1585
- helper exits with. Ending the conversation instead is the only
1586
- answer git reads as a failure.
1587
- */
1588
- break;
1589
- }
1590
- if (command === "list for-push") {
1591
- const known = await remoteRefs(project?.id ?? null);
1592
- for (const [ref, sha] of known)
1593
- send(`${sha} ${ref}`);
1594
- send("");
1595
- continue;
1596
- }
1597
- /*
1598
- A line whose head this clone has imported before is advertised by
1599
- its real commit id; one it has not is advertised as `?`.
1600
-
1601
- `?` is the format's way of saying "I cannot tell you", and it is the
1602
- honest answer the first time: the git commits are built during the
1603
- import that follows, from versions that are not git commits, so their
1604
- ids do not exist yet. It is the wrong answer on every fetch after
1605
- that, because git cannot then see that nothing has changed and asks
1606
- for the history again. The mark table is what turns the second and
1607
- later answers into real ids.
1608
- */
1609
- const state = project ? await remoteState(project.id) : null;
1610
- const lines = (state?.tracks ?? []).filter((track) => track.kind === "line" && track.headVersionId);
1611
- const marks = await readMarks();
1612
- for (const track of lines) {
1613
- const mark = marks?.ofVersion.get(track.headVersionId);
1614
- const sha = mark === undefined ? undefined : marks?.sha.get(mark);
1615
- send(`${sha ?? "?"} refs/heads/${track.name}`);
1616
- }
1617
- /*
1618
- Which line a clone opens on.
1619
-
1620
- The project's own default first, then the conventional names, then
1621
- whatever has content. Looking only for `main` was wrong for a
1622
- transferred repository: creating a project always makes an empty
1623
- `main`, so a repository whose default is `master` ends up with a
1624
- `main` that holds nothing — and `main` is filtered out of `lines`
1625
- for exactly that reason, leaving HEAD to fall on whichever branch
1626
- happened to sort first. It landed on `master` by luck rather than
1627
- because anything chose it.
1628
- */
1629
- const preferred = [
1630
- project?.defaultBranch,
1631
- "main",
1632
- "master",
1633
- ].filter((name) => Boolean(name));
1634
- const head = preferred
1635
- .map((name) => lines.find((track) => track.name === name))
1636
- .find(Boolean) ?? lines[0];
1637
- if (head)
1638
- send(`@refs/heads/${head.name} HEAD`);
136
+ const token = await (0, config_js_1.loadToken)();
137
+ if (!token)
138
+ throw new Error("Not signed in. Run `cbx sign-in` first.");
139
+ const { address } = await gitAddress(url);
140
+ for (const [ref, sha] of await (0, git_bridge_js_1.remoteRefs)({ url: address, token, agent: `coderook-cli/${version_js_1.VERSION}` }))
141
+ send(`${sha} ${ref}`);
1639
142
  }
1640
143
  catch (error) {
1641
- say(`Could not read the remote: ${error.message}`);
144
+ say(`CodeRook: ${error.message}`);
145
+ failed = true;
146
+ break;
1642
147
  }
1643
148
  send("");
1644
149
  continue;
1645
150
  }
1646
- if (command.startsWith("import ")) {
1647
- /*
1648
- Deduplicated. Git asks for the same ref more than once in one batch —
1649
- observed twice for a clone, once for the branch and once resolving
1650
- HEAD — and importing it twice would rebuild and re-send the entire
1651
- history for no reason.
1652
- */
1653
- const ref = command.slice("import ".length).trim();
1654
- if (!importing.includes(ref))
1655
- importing.push(ref);
1656
- continue;
1657
- }
1658
151
  if (command.startsWith("push ")) {
1659
152
  const spec = command.slice("push ".length);
1660
153
  const force = spec.startsWith("+");
@@ -1662,46 +155,26 @@ async function main(argv) {
1662
155
  pending.push({ src: src ?? "", dst: dst ?? "", force });
1663
156
  continue;
1664
157
  }
1665
- if (command === "") {
1666
- if (importing.length) {
1667
- const batch = importing.splice(0, importing.length);
1668
- try {
1669
- await doImport(batch, url, depth);
1670
- }
1671
- catch (error) {
1672
- /*
1673
- A project that could not be found has already said so and closed
1674
- the stream. Anything else has not, and fast-import would wait on
1675
- a stream that never ends.
1676
- */
1677
- if (error instanceof ImportFailed) {
1678
- unservable = true;
1679
- }
1680
- else {
1681
- say(`Import failed: ${error instanceof Error ? error.message : String(error)}`);
1682
- send("done");
1683
- }
1684
- }
1685
- continue;
158
+ if (command === "" && pending.length) {
159
+ const batch = pending.splice(0, pending.length);
160
+ try {
161
+ const token = await (0, config_js_1.loadToken)();
162
+ if (!token)
163
+ throw new Error("Not signed in. Run `cbx sign-in` first.");
164
+ const { address } = await gitAddress(url);
165
+ for (const result of await (0, git_bridge_js_1.bridgePush)(batch, { url: address, token, say, agent: `coderook-cli/${version_js_1.VERSION}`, ...tuning() }))
166
+ send(result.error ? `error ${result.dst} ${result.error.replace(/\n/g, " ")}` : `ok ${result.dst}`);
1686
167
  }
1687
- if (pending.length) {
1688
- const batch = pending.splice(0, pending.length);
1689
- try {
1690
- const account = await (0, api_js_1.whoami)();
1691
- say(`Pushing to CodeRook as ${account.username || account.displayName}.`);
1692
- }
1693
- catch {
1694
- say("Not signed in. Run `cbx sign-in` first.");
1695
- for (const request of batch) {
1696
- send(`error ${request.dst} not signed in to CodeRook`);
1697
- }
1698
- send("");
1699
- continue;
1700
- }
1701
- await doPush(batch, url, { adopt });
168
+ catch (error) {
169
+ say(`CodeRook: ${error.message}`);
170
+ for (const request of batch)
171
+ send(`error ${request.dst} ${error.message.replace(/\n/g, " ")}`);
1702
172
  }
173
+ send("");
1703
174
  continue;
1704
175
  }
176
+ if (command === "")
177
+ break;
1705
178
  }
1706
- return unservable ? 1 : 0;
179
+ return failed ? 1 : 0;
1707
180
  }