@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,322 +0,0 @@
1
- "use strict";
2
- /**
3
- * The decisions the git remote helper makes, with nothing plugged in.
4
- *
5
- * Ordering a version graph, reading and writing the commit marker, parsing a
6
- * remote URL, quoting a path for fast-import: none of it needs a network, a
7
- * token, an upload engine or a git binary, and all of it is where a mistake is
8
- * silent rather than loud. Kept apart so a test can exercise it directly —
9
- * importing the helper itself drags in the uploader and the downloader, which
10
- * is why this file exists at all.
11
- */
12
- Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.MESSAGE_LIMIT = exports.TRAILER = exports.EMPTY_TREE = void 0;
14
- exports.parseRemoteUrl = parseRemoteUrl;
15
- exports.commitFromMessage = commitFromMessage;
16
- exports.messageWithCommit = messageWithCommit;
17
- exports.messageWithoutMarker = messageWithoutMarker;
18
- exports.tagOf = tagOf;
19
- exports.branchOf = branchOf;
20
- exports.versionsInOrder = versionsInOrder;
21
- exports.stamp = stamp;
22
- exports.importRef = importRef;
23
- exports.quotePath = quotePath;
24
- exports.refPlacements = refPlacements;
25
- exports.withinDepth = withinDepth;
26
- exports.historyLeftOut = historyLeftOut;
27
- /**
28
- * Git's constant hash for the empty tree.
29
- *
30
- * Diffing a root commit against this gives the same "everything is added"
31
- * answer as a normal parent diff, so the first commit is not a special case
32
- * with its own code path to get wrong.
33
- */
34
- exports.EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
35
- /**
36
- * The line that ties a CodeRook version back to the git commit it came from.
37
- *
38
- * Written into the version message because it has to survive somewhere both
39
- * machines can see. A file under `.git/` would be invisible to a colleague and
40
- * to this same person on another laptop, and the consequence of losing the
41
- * mapping is not a missing feature — it is re-pushing a history the project
42
- * already holds, as a second copy. `git-svn` and `git-p4` put their marker in
43
- * the message for the same reason.
44
- */
45
- exports.TRAILER = "CodeRook-Git-Commit:";
46
- /** `coderook://project`, `coderook://owner/project`, `coderook::project`. */
47
- function parseRemoteUrl(url) {
48
- let rest = url.trim();
49
- for (const prefix of ["coderook://", "coderook::", "coderook:"]) {
50
- if (rest.startsWith(prefix)) {
51
- rest = rest.slice(prefix.length);
52
- break;
53
- }
54
- }
55
- rest = rest.replace(/^\/+/, "").replace(/\/+$/, "");
56
- /*
57
- The owner is carried, and what it is used for differs by direction.
58
- Fetching honours it, because `coderook://somebody/their-project` is the
59
- line printed on every public project page and it has to reach their
60
- project rather than look for that name on yours. Pushing still ignores
61
- it: the token says who you are, and quietly publishing to an account the
62
- URL named instead would be the worse mistake of the two.
63
- */
64
- const parts = rest.split("/").filter(Boolean);
65
- const slug = parts[parts.length - 1] ?? "";
66
- const owner = parts.length > 1 ? parts[parts.length - 2] : "";
67
- if (!slug)
68
- throw new Error(`Not a CodeRook remote URL: ${url}`);
69
- return { owner, slug };
70
- }
71
- /**
72
- * Pull the git commit id back out of a version message, if it carries one.
73
- *
74
- * The *last* marker wins. A message can hold more than one after a round trip
75
- * — clone a project, push it back, and the message carries the marker it was
76
- * imported with plus the one this publish adds. Taking the first would name
77
- * the commit from the original repository rather than the one just published,
78
- * and every incremental push after that would compute its range from a commit
79
- * this repository has never heard of.
80
- */
81
- function commitFromMessage(message) {
82
- const all = [
83
- ...message.matchAll(new RegExp(`${exports.TRAILER}\\s*([0-9a-f]{40})\\b`, "g")),
84
- ];
85
- return all.length ? all[all.length - 1][1] : null;
86
- }
87
- /**
88
- * What a version message may hold, matching the service.
89
- *
90
- * Not a guess and not a safety margin: the publish endpoint trims and then
91
- * refuses anything longer, so exceeding it fails the whole push rather than
92
- * being quietly shortened somewhere along the way.
93
- */
94
- exports.MESSAGE_LIMIT = 240;
95
- /**
96
- * Attach the marker to a commit message, within what the service will accept.
97
- *
98
- * The marker is not decoration — it is how a version is tied back to the
99
- * commit it came from, and losing it means a later push republishes history
100
- * the project already holds. So when the two together are too long, the
101
- * message gives way and the marker survives.
102
- *
103
- * Git's own convention decides how: the first line is the summary and the rest
104
- * is detail, so as much as fits is kept and the remainder is cut on a word
105
- * boundary. A repository with a two-paragraph commit message would otherwise
106
- * fail the push outright — which is what it did, on a real transfer, with an
107
- * error naming a limit the person had never heard of.
108
- */
109
- function messageWithCommit(message, sha) {
110
- const trailer = `\n\n${exports.TRAILER} ${sha}`;
111
- const room = exports.MESSAGE_LIMIT - trailer.length;
112
- const body = message.replace(/\s+$/, "");
113
- if (body.length <= room)
114
- return `${body}${trailer}`;
115
- /*
116
- Cut on a word boundary when one is reasonably near the end, so the result
117
- reads as a shortened sentence rather than a severed one. The ellipsis is
118
- what tells a reader there was more.
119
- */
120
- const kept = body.slice(0, room - 1);
121
- const tidy = kept.replace(/\s+\S*$/, "");
122
- const shortened = (tidy.length > room / 2 ? tidy : kept).trimEnd();
123
- /*
124
- A message of nothing but whitespace would leave an empty string, which the
125
- service refuses for its own reason: it requires at least one character.
126
- */
127
- return `${shortened || sha.slice(0, 8)}…${trailer}`;
128
- }
129
- /**
130
- * The message as a person wrote it, with our bookkeeping taken back out.
131
- *
132
- * Used when rebuilding git commits: the marker names the commit a version came
133
- * *from*, which is not the commit being created here, so leaving it in would
134
- * stamp every imported commit with a false identity.
135
- */
136
- function messageWithoutMarker(message) {
137
- return message
138
- .replace(new RegExp(`^\\s*${exports.TRAILER}\\s*[0-9a-f]{40}\\s*$`, "gm"), "")
139
- .replace(/\n{3,}/g, "\n\n")
140
- .trim();
141
- }
142
- /** `refs/tags/v1.0` -> `v1.0`. Anything else is not a tag. */
143
- function tagOf(ref) {
144
- return ref.startsWith("refs/tags/") ? ref.slice("refs/tags/".length) : null;
145
- }
146
- /** `refs/heads/main` -> `main`. Anything else is not a branch. */
147
- function branchOf(ref) {
148
- return ref.startsWith("refs/heads/") ? ref.slice("refs/heads/".length) : null;
149
- }
150
- /**
151
- * Every version reachable from these heads, oldest first.
152
- *
153
- * A plain sort by sequence would look right and be wrong: sequences are handed
154
- * out per project as versions are made, so two lines interleave in a way that
155
- * has nothing to do with ancestry. Walking `parentVersionIds` and emitting a
156
- * version only once all of its parents have been emitted is what makes a
157
- * commit's parents exist by the time git is told about them — fast-import
158
- * refuses a mark it has not seen, so getting this wrong fails loudly, which is
159
- * the one mercy of it.
160
- */
161
- function versionsInOrder(heads, all) {
162
- const byId = new Map(all.map((version) => [version.id, version]));
163
- // Everything the heads can reach. Iterative rather than recursive: a long
164
- // project is thousands of versions deep and a stack is not.
165
- const reachable = new Set();
166
- const pending = [...heads];
167
- while (pending.length) {
168
- const id = pending.pop();
169
- if (!id || reachable.has(id) || !byId.has(id))
170
- continue;
171
- reachable.add(id);
172
- for (const parent of byId.get(id).parentVersionIds)
173
- pending.push(parent);
174
- }
175
- const emitted = new Set();
176
- const order = [];
177
- /*
178
- Depth-first with an explicit stack, visiting parents before the child. The
179
- `expanded` flag is what separates "I have queued this one's parents" from
180
- "its parents are done", without which a diamond history emits the join
181
- twice.
182
- */
183
- const stack = heads
184
- .filter((id) => reachable.has(id))
185
- .map((id) => ({ id, expanded: false }));
186
- while (stack.length) {
187
- const frame = stack.pop();
188
- if (emitted.has(frame.id))
189
- continue;
190
- const version = byId.get(frame.id);
191
- if (!version)
192
- continue;
193
- if (frame.expanded) {
194
- emitted.add(frame.id);
195
- order.push(version);
196
- continue;
197
- }
198
- stack.push({ id: frame.id, expanded: true });
199
- for (const parent of version.parentVersionIds) {
200
- if (reachable.has(parent) && !emitted.has(parent)) {
201
- stack.push({ id: parent, expanded: false });
202
- }
203
- }
204
- }
205
- return order;
206
- }
207
- /** Seconds since the epoch, for a fast-import person stamp. */
208
- function stamp(when) {
209
- const at = Date.parse(when);
210
- return Number.isFinite(at) ? Math.floor(at / 1000) : Math.floor(Date.now() / 1000);
211
- }
212
- /**
213
- * Where an imported branch is written.
214
- *
215
- * Into the helper's own namespace rather than `refs/heads/*`, matching the
216
- * `refspec` advertised in `capabilities`. Writing straight to `refs/heads/*`
217
- * would have this remote overwrite local branches of the same name on every
218
- * fetch.
219
- */
220
- function importRef(ref) {
221
- const branch = branchOf(ref);
222
- return branch ? `refs/coderook/${branch}` : ref;
223
- }
224
- /** fast-import wants a path C-quoted when it holds a quote or a newline. */
225
- function quotePath(filePath) {
226
- const normalised = filePath.replaceAll("\\", "/");
227
- if (!/["\n\r]/.test(normalised))
228
- return normalised;
229
- return `"${normalised
230
- .replaceAll("\\", "\\\\")
231
- .replaceAll('"', '\\"')
232
- .replaceAll("\n", "\\n")
233
- .replaceAll("\r", "\\r")}"`;
234
- }
235
- /**
236
- * Where each ref git asked for has to be pointed, once the commits exist.
237
- *
238
- * Git holds the helper to the whole batch: it names the refs it wants, and
239
- * if any one of them does not exist when the stream ends it aborts the fetch
240
- * — `could not read ref refs/coderook/<name>` — and the clone fails with
241
- * nothing to show for it.
242
- *
243
- * Emitting commits is not enough to guarantee that, because a commit is
244
- * written once per *version* while refs are per *line*. Two lines can share
245
- * one version — making a line from where another already is does exactly
246
- * that — so a single commit is expected to satisfy two refs, and only the
247
- * first is written. A line whose version arrived in an earlier fetch has no
248
- * commit emitted for it at all, and lands in the same hole.
249
- *
250
- * So each ref is stated separately rather than inferred from the commits.
251
- * A ref whose head has no mark is reported rather than guessed at: pointing
252
- * it somewhere plausible would hand back a branch that is quietly not the
253
- * one asked for.
254
- */
255
- function refPlacements(wanted, markOfVersion) {
256
- const placed = [];
257
- const unplaceable = [];
258
- for (const [ref, head] of wanted) {
259
- const mark = markOfVersion.get(head);
260
- if (mark === undefined)
261
- unplaceable.push(ref);
262
- else
263
- placed.push({ ref, mark });
264
- }
265
- return { placed, unplaceable };
266
- }
267
- /**
268
- * The versions within `depth` generations of these heads: 1 is the heads
269
- * alone, 2 adds their parents, and so on.
270
- *
271
- * What `git clone --depth` means here. The oldest version taken is imported
272
- * with no parent, so it becomes a root commit — which also means its commit id
273
- * differs from the same version's id in a full clone, because a commit's id
274
- * covers its parents. That is the same trade git's own shallow clones make.
275
- */
276
- function withinDepth(heads, all, depth) {
277
- const byId = new Map(all.map((version) => [version.id, version]));
278
- const kept = new Set();
279
- let level = heads.filter((id) => byId.has(id));
280
- for (let generation = 0; generation < depth && level.length; generation += 1) {
281
- const next = [];
282
- for (const id of level) {
283
- if (kept.has(id))
284
- continue;
285
- kept.add(id);
286
- for (const parent of byId.get(id).parentVersionIds) {
287
- if (byId.has(parent) && !kept.has(parent))
288
- next.push(parent);
289
- }
290
- }
291
- level = next;
292
- }
293
- return kept;
294
- }
295
- /**
296
- * History an earlier shallow clone chose not to take.
297
- *
298
- * Every ancestor of something already imported that was not itself imported.
299
- * A full clone imported every ancestor, so for it this is always empty; for a
300
- * shallow one it is everything below the cut. Without it the first ordinary
301
- * `git fetch` after a `--depth 1` clone would import the whole history anyway,
302
- * as a second, disconnected line of commits nobody asked for.
303
- */
304
- function historyLeftOut(all, imported) {
305
- const byId = new Map(all.map((version) => [version.id, version]));
306
- const have = new Set(imported);
307
- const left = new Set();
308
- const pending = [];
309
- for (const id of have) {
310
- for (const parent of byId.get(id)?.parentVersionIds ?? [])
311
- pending.push(parent);
312
- }
313
- while (pending.length) {
314
- const id = pending.pop();
315
- if (have.has(id) || left.has(id) || !byId.has(id))
316
- continue;
317
- left.add(id);
318
- for (const parent of byId.get(id).parentVersionIds)
319
- pending.push(parent);
320
- }
321
- return left;
322
- }