@coderook/cli 0.49.0 → 0.50.1

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.
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.commandGit = commandGit;
7
+ /**
8
+ * `coderook git setup`: plain git with CodeRook, any size, no other commands.
9
+ *
10
+ * After `npm install -g @coderook/cli` and `cbx sign-in`, one command sets
11
+ * git up so CodeRook is just another git host:
12
+ *
13
+ * - git signs in with this machine's CodeRook token (`coderook git
14
+ * credential`, a git credential helper scoped to CodeRook's addresses), so
15
+ * nobody pastes a token as a password;
16
+ * - pushes to CodeRook go through git-remote-coderook (git's pushInsteadOf),
17
+ * which sends large files beside the push so a push is never refused for
18
+ * passing Cloudflare's 100 MB request limit. Clones, fetches and pulls stay
19
+ * plain git.
20
+ *
21
+ * Only git's global settings for CodeRook's own addresses are touched, and
22
+ * `coderook git undo` takes them out again.
23
+ */
24
+ const node_child_process_1 = require("node:child_process");
25
+ const node_process_1 = __importDefault(require("node:process"));
26
+ const config_js_1 = require("./config.js");
27
+ function gitConfig(args) {
28
+ const result = (0, node_child_process_1.spawnSync)("git", ["config", "--global", ...args], { encoding: "utf8", windowsHide: true });
29
+ return { ok: result.status === 0, out: (result.stdout ?? "").trim() };
30
+ }
31
+ /* The addresses people use for CodeRook projects over git: the site's and the service's own. */
32
+ function addresses() {
33
+ const api = (0, config_js_1.apiOrigin)();
34
+ const site = (0, config_js_1.siteOrigin)(api);
35
+ return [...new Set([`${site ?? api}/`, `${api}/git/`])];
36
+ }
37
+ function hostsOf() {
38
+ return new Set(addresses().map((address) => new URL(address).host.toLowerCase()));
39
+ }
40
+ function gitInstalled() {
41
+ const result = (0, node_child_process_1.spawnSync)("git", ["--version"], { encoding: "utf8", windowsHide: true });
42
+ return result.status === 0 ? (result.stdout ?? "").trim() : null;
43
+ }
44
+ function installAdvice() {
45
+ if (node_process_1.default.platform === "win32")
46
+ return "winget install --id Git.Git -e";
47
+ if (node_process_1.default.platform === "darwin")
48
+ return "xcode-select --install (or: brew install git)";
49
+ return "sudo apt install git (Fedora: sudo dnf install git, Arch: sudo pacman -S git)";
50
+ }
51
+ function undo() {
52
+ for (const address of addresses()) {
53
+ gitConfig(["--unset-all", `credential.${address.replace(/\/git\/$/, "/").replace(/\/$/, "")}.helper`]);
54
+ gitConfig(["--unset-all", `url.coderook::${address}.pushInsteadOf`]);
55
+ }
56
+ }
57
+ async function commandGit(action, operation) {
58
+ /* Run by git itself, as `coderook git credential get` (see setup below). */
59
+ if (action === "credential")
60
+ return credential(operation ?? "");
61
+ if (action === "undo") {
62
+ undo();
63
+ console.log("Git no longer uses CodeRook's sign-in or push helper. Plain git with a token as the password still works.");
64
+ return 0;
65
+ }
66
+ if (action !== "setup") {
67
+ console.error("Use `coderook git setup` to set git up for CodeRook, or `coderook git undo` to take it out again.");
68
+ return 1;
69
+ }
70
+ const version = gitInstalled();
71
+ if (!version) {
72
+ console.error(`Git is not installed. Install it, then run this again:\n ${installAdvice()}`);
73
+ return 1;
74
+ }
75
+ if (!(await (0, config_js_1.loadToken)())) {
76
+ console.error("This machine is not signed in to CodeRook. Run `cbx sign-in` first, then this again.");
77
+ return 1;
78
+ }
79
+ undo();
80
+ for (const address of addresses()) {
81
+ const scope = address.replace(/\/git\/$/, "/").replace(/\/$/, "");
82
+ /* An empty helper first clears any other helper for these addresses, so no sign-in window opens over this one. */
83
+ gitConfig(["--add", `credential.${scope}.helper`, ""]);
84
+ gitConfig(["--add", `credential.${scope}.helper`, "!coderook git credential"]);
85
+ gitConfig(["--add", `url.coderook::${address}.pushInsteadOf`, address]);
86
+ }
87
+ const site = (0, config_js_1.siteOrigin)((0, config_js_1.apiOrigin)()) ?? (0, config_js_1.apiOrigin)();
88
+ console.log(`${version}: set up for CodeRook.\n\n` +
89
+ "Use git as you would with any host:\n" +
90
+ ` git clone ${site}/<owner>/<project>.git\n` +
91
+ " git push / git pull / git fetch\n\n" +
92
+ "Pushes of any size work: large files go beside the push, in pieces.\n" +
93
+ "Commit ids stay exactly yours. To take this out again: coderook git undo");
94
+ return 0;
95
+ }
96
+ /**
97
+ * Git's credential helper protocol: git writes `key=value` lines, and on
98
+ * `get` this answers with the token for CodeRook's own hosts and nothing
99
+ * for any other.
100
+ */
101
+ async function credential(operation) {
102
+ if (operation !== "get")
103
+ return 0;
104
+ let input = "";
105
+ for await (const chunk of node_process_1.default.stdin)
106
+ input += chunk.toString("utf8");
107
+ const fields = new Map(input.split(/\r?\n/).filter(Boolean).map((line) => [line.slice(0, line.indexOf("=")), line.slice(line.indexOf("=") + 1)]));
108
+ const host = (fields.get("host") ?? "").toLowerCase();
109
+ if (!hostsOf().has(host))
110
+ return 0;
111
+ const token = await (0, config_js_1.loadToken)();
112
+ if (!token)
113
+ return 0;
114
+ node_process_1.default.stdout.write(`username=coderook\npassword=${token}\n`);
115
+ return 0;
116
+ }
@@ -299,12 +299,13 @@ function howToSave(folder, slug) {
299
299
  /* Not a git repository. */
300
300
  }
301
301
  if (config !== null) {
302
- const remote = config.match(/\[remote "([^"]+)"\][^[]*?url\s*=\s*coderook:/);
302
+ const remote = config.match(/\[remote "([^"]+)"\][^[]*?url\s*=\s*(?:coderook:|https:\/\/(?:api\.)?coderook\.com\/)/);
303
303
  if (remote)
304
304
  return `To save: commit, then git push ${remote[1]} <branch> (ask first).`;
305
305
  return (`This is a git repository with no CodeRook remote. To save each commit: ` +
306
- `git remote add coderook coderook://${slug ?? "<project>"}, then git push coderook <branch> ` +
307
- `(git push -o adopt the first time if the project was saved with cbx submit). Ask first.`);
306
+ `coderook git setup, then git remote add coderook https://coderook.com/<owner>/${slug ?? "<project>"}.git ` +
307
+ `and git push coderook <branch> (git pull coderook main --allow-unrelated-histories first if the project ` +
308
+ `was saved with cbx submit). Ask first.`);
308
309
  }
309
310
  if (slug)
310
311
  return `To save: cbx submit -m "…" (ask first).`;
@@ -37,7 +37,7 @@ exports.GROUP_ORDER = [
37
37
  * from this list still appears, after the ones that are in it.
38
38
  */
39
39
  exports.LISTING_ORDER = [
40
- "sign-in", "whoami", "sign-out", "doctor", "update", "projects", "clone", "link", "unlink", "import", "transfer",
40
+ "sign-in", "whoami", "sign-out", "doctor", "git", "update", "projects", "clone", "link", "unlink", "import", "transfer",
41
41
  "status", "submit", "diff", "get", "track", "ignore", "licence",
42
42
  "init", "save", "log", "restore", "switch", "push", "pull",
43
43
  "tracks", "line-rules", "merges", "merge", "propose", "proposals", "pr",
@@ -14,15 +14,16 @@ exports.commandTransfer = commandTransfer;
14
14
  *
15
15
  * ## It uses the public route on purpose
16
16
  *
17
- * The history goes across by running `git push` against the CodeRook remote —
18
- * the same command anybody else would type, through the same helper. Nothing
19
- * here reaches past it into a private path.
17
+ * The history goes across as plain git pushes to the project's git address,
18
+ * through the same code `git push` uses after `coderook git setup`
19
+ * (git_bridge.ts): a long history in steps, large files beside the push.
20
+ * Nothing here reaches past it into a private path.
20
21
  *
21
22
  * That is deliberate, because the claim being made is interoperability. A
22
23
  * transfer that worked through a back door would prove only that a back door
23
- * exists. This one works because `git push coderook --all` works; if that ever
24
- * breaks, this breaks with it, loudly, rather than quietly diverging from what
25
- * users are told to do.
24
+ * exists. This one works because `git push` works; if that ever breaks, this
25
+ * breaks with it, loudly, rather than quietly diverging from what users are
26
+ * told to do. Commit ids arrive unchanged.
26
27
  *
27
28
  * ## What crosses, and what cannot
28
29
  *
@@ -47,6 +48,9 @@ const node_os_1 = __importDefault(require("node:os"));
47
48
  const node_path_1 = __importDefault(require("node:path"));
48
49
  const node_process_1 = __importDefault(require("node:process"));
49
50
  const api_js_1 = require("./api.js");
51
+ const config_js_1 = require("./config.js");
52
+ const git_bridge_js_1 = require("./git_bridge.js");
53
+ const version_js_1 = require("./version.js");
50
54
  const forge_url_js_1 = require("./forge_url.js");
51
55
  const import_command_js_1 = require("./import_command.js");
52
56
  const colour_js_1 = require("./colour.js");
@@ -153,21 +157,6 @@ async function commandTransfer(parsed) {
153
157
  console.error((0, colour_js_1.red)("Transferring needs git on this machine."));
154
158
  return 1;
155
159
  }
156
- /*
157
- The push goes through the remote helper, which git finds on PATH by name.
158
- Checking now turns a confusing failure halfway through a clone into one
159
- sentence before anything is downloaded.
160
- */
161
- if (!run("git", ["remote-coderook", "--probe"]).ok) {
162
- const help = run("git", ["help", "-a"]);
163
- if (!/remote-coderook/.test(help.out)) {
164
- console.error((0, colour_js_1.red)("git cannot find `git-remote-coderook` on this machine."));
165
- console.error("It ships with this tool, so this usually means cbx was run from a\n" +
166
- "checkout rather than installed. Install it globally and try again:\n" +
167
- ` ${(0, colour_js_1.accent)("npm install --global @coderook/cli")}`);
168
- return 1;
169
- }
170
- }
171
160
  const wanted = (typeof parsed.flags.get("name") === "string"
172
161
  ? String(parsed.flags.get("name"))
173
162
  : forge.repo).toLowerCase();
@@ -240,27 +229,67 @@ async function commandTransfer(parsed) {
240
229
  console.log((0, colour_js_1.dim)(` Each commit becomes a version, so this will take a while —\n` +
241
230
  ` roughly ${Math.round((commits * 11) / 60)} minutes. It resumes if interrupted.`));
242
231
  }
243
- run("git", ["remote", "add", "coderook", `coderook://${wanted}`], checkout);
244
- console.log(`\n${(0, colour_js_1.dim)("Publishing the history…")}`);
245
- const pushed = run("git", ["push", "coderook", "--all"], checkout);
246
- node_process_1.default.stderr.write(pushed.out);
247
- if (!pushed.ok) {
248
- console.error((0, colour_js_1.red)("\nThe history did not transfer completely."));
232
+ /* The project first, private; the history then goes in as plain git pushes. */
233
+ const owner = (await (0, api_js_1.whoami)()).username ?? "";
234
+ if (!owner) {
235
+ console.error((0, colour_js_1.red)("\nThis account has no username yet; choose one on coderook.com, then try again."));
249
236
  return 1;
250
237
  }
251
- report.push(`${commits} commits across ${remoteBranches.length} branch(es)`);
252
- if (tags.length) {
253
- const pushedTags = run("git", ["push", "coderook", "--tags"], checkout);
254
- node_process_1.default.stderr.write(pushedTags.out);
255
- report.push(pushedTags.ok
256
- ? `${tags.length} tag(s) as releases`
257
- : `tags were refused — see above`);
258
- }
238
+ await (0, api_js_1.callApi)("/v1/repositories", {
239
+ method: "POST",
240
+ body: { slug: wanted, displayName: forge.repo, description: "", visibility: "private" },
241
+ });
259
242
  const project = await (0, api_js_1.findProject)(wanted);
260
243
  if (!project) {
261
244
  console.error((0, colour_js_1.red)("\nThe project was not created. Nothing else was changed."));
262
245
  return 1;
263
246
  }
247
+ /* Merges go across as merges: a merged branch that no longer exists becomes a line named merged/… (service.ts). */
248
+ const merges = Number(run("git", ["rev-list", "--merges", "--count", "--all"], checkout).out.trim() || "0");
249
+ console.log(`\n${(0, colour_js_1.dim)("Publishing the history…")}`);
250
+ const results = await (0, git_bridge_js_1.bridgePush)(remoteBranches.map((branch) => ({ src: `refs/heads/${branch}`, dst: `refs/heads/${branch}`, force: false })), {
251
+ url: `${(0, config_js_1.apiOrigin)()}/git/${encodeURIComponent(owner)}/${encodeURIComponent(project.slug ?? wanted)}.git`,
252
+ token: await (0, config_js_1.loadToken)(),
253
+ cwd: checkout,
254
+ say: (text) => console.error((0, colour_js_1.dim)(` ${text}`)),
255
+ agent: `coderook-cli/${version_js_1.VERSION}`,
256
+ });
257
+ const failedLines = results.filter((one) => one.error);
258
+ for (const one of failedLines)
259
+ console.error((0, colour_js_1.red)(` ${one.dst.replace(/^refs\/heads\//, "")}: ${one.error}`));
260
+ if (failedLines.length) {
261
+ console.error((0, colour_js_1.red)("\nThe history did not transfer completely. Run the same command with --name to try again into a new project."));
262
+ return 1;
263
+ }
264
+ report.push(`${commits} commits across ${remoteBranches.length} branch(es)`);
265
+ if (merges)
266
+ report.push(`${merges} merge(s), kept as merges; branches merged and since deleted are lines named merged/…`);
267
+ if (tags.length) {
268
+ /* A tag names the version its commit became: a release, with an annotated tag's message as its notes. */
269
+ const byCommit = new Map();
270
+ for (const version of await (0, api_js_1.versions)(project.id)) {
271
+ const marker = /CodeRook-Git-Commit: ([0-9a-f]{40})/.exec(version.message);
272
+ if (marker)
273
+ byCommit.set(marker[1], version.id);
274
+ }
275
+ let named = 0;
276
+ for (const tag of tags) {
277
+ const commit = run("git", ["rev-parse", "--verify", `refs/tags/${tag}^{commit}`], checkout).out.trim();
278
+ const versionId = byCommit.get(commit);
279
+ if (!versionId)
280
+ continue;
281
+ const annotated = run("git", ["cat-file", "-t", `refs/tags/${tag}`], checkout).out.trim() === "tag";
282
+ const notes = annotated ? run("git", ["tag", "-l", "--format=%(contents)", "--", tag], checkout).out.trim() : "";
283
+ try {
284
+ await (0, api_js_1.markRelease)(project.id, versionId, tag, notes || null);
285
+ named++;
286
+ }
287
+ catch (error) {
288
+ console.error((0, colour_js_1.red)(` tag ${tag}: ${error instanceof Error ? error.message : String(error)}`));
289
+ }
290
+ }
291
+ report.push(`${named} of ${tags.length} tag(s) as releases`);
292
+ }
264
293
  // What the repository says about itself.
265
294
  const facts = await describeSource(forge, token);
266
295
  if (facts) {
@@ -353,7 +382,7 @@ async function commandTransfer(parsed) {
353
382
  : []),
354
383
  ].join("\n"));
355
384
  console.log(`\nFetch it anywhere with ${(0, colour_js_1.accent)(`cbx clone ${project.slug}`)}` +
356
- `${(0, colour_js_1.dim)(", or ")}${(0, colour_js_1.accent)(`git clone coderook://${project.slug}`)}${(0, colour_js_1.dim)(".")}`);
385
+ `${(0, colour_js_1.dim)(", or ")}${(0, colour_js_1.accent)(`git clone ${(0, config_js_1.siteOrigin)() ?? (0, config_js_1.apiOrigin)()}/${owner}/${project.slug}.git`)}${(0, colour_js_1.dim)(".")}`);
357
386
  return 0;
358
387
  }
359
388
  finally {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coderook/cli",
3
- "version": "0.49.0",
3
+ "version": "0.50.1",
4
4
  "description": "The command line for CodeRook (coderook.com): version control and project hosting for projects of any size. Every save is a compressed snapshot, private or public, never used to train AI.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://coderook.com",
@@ -12,7 +12,7 @@ around it, and there is no staging area, no branches to rebase and no history
12
12
  to rewrite.
13
13
 
14
14
  Everything here is the `cbx` command line (also installed as `coderook`), or
15
- git itself through CodeRook's remote helper. Run them with Bash.
15
+ plain git against the project's git address. Run them with Bash.
16
16
 
17
17
  **Which one to use.** If the folder is a git repository (`git rev-parse` works
18
18
  in it), prefer git — see *Working in a git repository* below. Each commit then
@@ -105,28 +105,44 @@ upload?".
105
105
 
106
106
  ## Working in a git repository
107
107
 
108
- CodeRook is a git remote. `npm install --global @coderook/cli` puts the helper
109
- (`git-remote-coderook`) on PATH; the plugin and `npx` do not, so check with
110
- `git ls-remote coderook://<project>` before relying on it.
108
+ CodeRook is a plain git host:
109
+
110
+ - **The address:** `https://coderook.com/<owner>/<project>.git`
111
+ (or `https://api.coderook.com/git/<owner>/<project>.git`). Git asks for a
112
+ username and password: any username, and a CodeRook access token as the
113
+ password (a read-only token can fetch but not push). Use the person's
114
+ credential helper or a CI secret; never write a token into a command line or
115
+ a file yourself. Clone, fetch, pull, push and `--depth` work; each pushed
116
+ commit becomes a save and keeps its commit id.
117
+ - **`coderook git setup`** (needs `npm install --global @coderook/cli`, once,
118
+ and changes git's global settings for CodeRook's addresses, so ask first):
119
+ git then signs in with the machine's CodeRook sign-in, and pushes of any size
120
+ work. Without it a push over 100 MB fails with "the remote end hung up";
121
+ that is Cloudflare's request limit, and setup is the fix. `coderook git undo`
122
+ reverses it.
111
123
 
112
124
  ```bash
113
- git remote -v # is there a coderook:// remote already?
114
- git remote add coderook coderook://<project> # if not
115
- git push coderook main # each new commit becomes a save
116
- git push coderook <branch> # a branch becomes a line
117
- git push coderook v1.2.0 # a tag names a version
118
- git fetch coderook # bring other people's saves in
125
+ git remote -v # is there a CodeRook remote already?
126
+ git remote add coderook https://coderook.com/<owner>/<project>.git # if not
127
+ git push coderook main # each new commit becomes a save
128
+ git push coderook <branch> # a branch becomes a line
129
+ git pull coderook main # bring other people's saves in
119
130
  ```
120
131
 
121
- If the project was started with `cbx submit` or the desktop app, the first push
122
- is refused with a message saying so. When the repository holds that project,
123
- `git push -o adopt coderook main` saves the current commit on top of what is
124
- there, once; plain pushes work from then on. **Ask before adopting** — it is a
125
- save like any other. If the project is somebody else's work under the same
126
- name, push to a new name instead.
132
+ If the project was started with `cbx submit` or the desktop app, its saves are
133
+ not in the repository's history, so the first push is refused with "fetch
134
+ first". `git pull coderook main --allow-unrelated-histories` once brings them
135
+ in, then pushes work. **Ask before doing that** — it merges two histories. If
136
+ the project is somebody else's work under the same name, push to a new name
137
+ instead.
138
+
139
+ Tags are refused (CodeRook names a version with `cbx release <name>`), and an
140
+ old `coderook://` remote is retired: a fetch through it prints the
141
+ `git remote set-url` command that moves it to the plain address.
127
142
 
128
143
  Git's limits here: no force pushes or branch deletions (saves are permanent), a
129
- merge commit arrives as one save holding the merged tree, and a commit holding
144
+ merge arrives as a merge (a merged branch CodeRook never had becomes a line
145
+ named `merged/<branch>`), and a commit holding
130
146
  a credential is refused — take the key out of history rather than looking for
131
147
  a way round.
132
148