Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import type { VcsStatusRemoteResult, VcsStatusResult } from "@t3tools/contracts";
3import { describe, expect, it } from "vite-plus/test";
4
5import {
6 applyGitStatusStreamEvent,
7 formatGeneratedBranchName,
8 buildTemporaryWorktreeBranchName,
9 flattenTemporaryWorktreeBranchName,
10 isBareGitConfig,
11 isTemporaryWorktreeBranch,
12 normalizeGitRemoteUrl,
13 parseGitRemoteRepository,
14 parseOriginUrlFromGitConfig,
15 resolveAutoFeatureBranchName,
16 sanitizeFeatureBranchName,
17 WORKTREE_BRANCH_PREFIX,
18} from "./git.ts";
19
20describe("normalizeGitRemoteUrl", () => {
21 it.each([
22 ["/home/me/project/.git", "/home/me/project/.git"],
23 ["/home/me/project/.git/", "/home/me/project/%2Egit"],
24 ["/project/.git", "/project/.git"],
25 ])("matches SCP checkout path %s to SSH URL path %s", (scpPath, sshPath) => {
26 expect(normalizeGitRemoteUrl(`git@forge.example:${scpPath}`)).toBe(
27 normalizeGitRemoteUrl(`ssh://git@forge.example${sshPath}`),
28 );
29 });
30
31 it.each(["/team//repo.git", "team//repo.git", "team//repo%2Egit"])(
32 "matches SCP path %s to its SSH URL with a repeated separator",
33 (path) => {
34 expect(normalizeGitRemoteUrl(`git@forge.example:${path}`)).toBe(
35 normalizeGitRemoteUrl("ssh://git@forge.example/team//repo.git"),
36 );
37 },
38 );
39
40 it.each(["git@forge.example://", "[::1]:///"])("keeps the fallback for %s", (prefix) => {
41 expect(normalizeGitRemoteUrl(`${prefix}team/repo.git`)).toBe(`${prefix}team/repo`);
42 });
43
44 it("decodes percent-encoded SCP paths like their ssh:// spelling", () => {
45 expect(normalizeGitRemoteUrl("git@ssh.dev.azure.com:v3/Org/My%20Project/My%20Repo")).toBe(
46 normalizeGitRemoteUrl("ssh://git@ssh.dev.azure.com/v3/Org/My%20Project/My%20Repo"),
47 );
48 });
49
50 it("canonicalizes equivalent GitHub remotes across protocol variants", () => {
51 expect(normalizeGitRemoteUrl("git@github.com:T3Tools/T3Code.git")).toBe(
52 "github.com/t3tools/t3code",
53 );
54 expect(normalizeGitRemoteUrl("https://github.com/T3Tools/T3Code.git")).toBe(
55 "github.com/t3tools/t3code",
56 );
57 expect(normalizeGitRemoteUrl("ssh://git@github.com/T3Tools/T3Code")).toBe(
58 "github.com/t3tools/t3code",
59 );
60 expect(normalizeGitRemoteUrl("https://github.com/T3Tools/T3Code.git?view=compact")).toBe(
61 "github.com/t3tools/t3code",
62 );
63 expect(normalizeGitRemoteUrl("https://github.com/T3Tools/T3Code.git#section")).toBe(
64 "github.com/t3tools/t3code",
65 );
66 expect(normalizeGitRemoteUrl("https://code.example.test/team/%C3%84pp.git")).toBe(
67 normalizeGitRemoteUrl("git@code.example.test:team/Äpp.git"),
68 );
69 expect(normalizeGitRemoteUrl("ssh://git@code.example.test/owner/repo.git.git")).toBe(
70 normalizeGitRemoteUrl("git@code.example.test:owner/repo.git.git"),
71 );
72 });
73
74 it.each([
75 "git@[2001:db8::1]:team/repo.git",
76 "[2001:db8::1]:team/repo.git",
77 "git@[2001:DB8:0::1]:team/repo.git",
78 ])("canonicalizes an IPv6 SCP remote like its SSH URL: %s", (remote) => {
79 expect(normalizeGitRemoteUrl(remote)).toBe(
80 normalizeGitRemoteUrl("ssh://git@[2001:db8::1]/team/repo.git"),
81 );
82 });
83
84 it("preserves nested group paths for providers like GitLab", () => {
85 expect(normalizeGitRemoteUrl("git@gitlab.com:T3Tools/platform/T3Code.git")).toBe(
86 "gitlab.com/t3tools/platform/t3code",
87 );
88 expect(normalizeGitRemoteUrl("https://gitlab.com/T3Tools/platform/T3Code.git")).toBe(
89 "gitlab.com/t3tools/platform/t3code",
90 );
91 });
92
93 it("drops explicit ports from URL-shaped remotes", () => {
94 expect(normalizeGitRemoteUrl("https://gitlab.company.com:8443/team/project.git")).toBe(
95 "gitlab.company.com/team/project",
96 );
97 expect(normalizeGitRemoteUrl("ssh://git@gitlab.company.com:2222/team/project.git")).toBe(
98 "gitlab.company.com/team/project",
99 );
100 });
101
102 it("normalizes SCP-like remotes with non-git SSH users", () => {
103 expect(normalizeGitRemoteUrl("gitlab@gitlab.example.com:group/project.git")).toBe(
104 "gitlab.example.com/group/project",
105 );
106 expect(normalizeGitRemoteUrl("deploy@bitbucket.org:workspace/repo.git")).toBe(
107 "bitbucket.org/workspace/repo",
108 );
109 expect(normalizeGitRemoteUrl("code.example.test:team/repo.git")).toBe(
110 "code.example.test/team/repo",
111 );
112 expect(normalizeGitRemoteUrl("git@code.example.test:/team/repo.git")).toBe(
113 "code.example.test/team/repo",
114 );
115 expect(normalizeGitRemoteUrl("C:/repos/project")).toBe("c:/repos/project");
116 expect(normalizeGitRemoteUrl("git@x:team/project.git")).toBe("x/team/project");
117 expect(normalizeGitRemoteUrl("alice+ci@github.com:Owner/Repo.git")).toBe(
118 "github.com/owner/repo",
119 );
120 expect(normalizeGitRemoteUrl("alice@corp.com@github.com:Owner/Repo.git")).toBe(
121 "github.com/owner/repo",
122 );
123 });
124
125 it("keys an SCP-like remote with spaces in its path like its URL spelling", () => {
126 expect(normalizeGitRemoteUrl("git@forge.example:team/My Repo.git")).toBe(
127 normalizeGitRemoteUrl("ssh://git@forge.example/team/My Repo.git"),
128 );
129 expect(normalizeGitRemoteUrl("forge.example:team/My Repo.git")).toBe(
130 "forge.example/team/my%20repo",
131 );
132 });
133
134 it("keys a one-segment URL remote by what names the repository", () => {
135 expect(normalizeGitRemoteUrl("https://deploy:s3cr3ttok@git.example.com/Repo.git")).toBe(
136 "https://git.example.com/repo",
137 );
138 expect(normalizeGitRemoteUrl("https://alice@corp.com:s3cr3ttok@git.example.com/repo.git")).toBe(
139 "https://git.example.com/repo",
140 );
141 expect(normalizeGitRemoteUrl("https://0123abcd@git.example.com/repo.git?key=0123abcd#x")).toBe(
142 "https://git.example.com/repo",
143 );
144 expect(normalizeGitRemoteUrl("ftp://deploy:s3cr3ttok@git.example.com/team/repo.git")).toBe(
145 "ftp://git.example.com/team/repo",
146 );
147 expect(normalizeGitRemoteUrl("ssh://git:s3cr3ttok@git.example.com:2222/repo.git")).toBe(
148 "ssh://git@git.example.com:2222/repo",
149 );
150 expect(normalizeGitRemoteUrl("ssh://alice@corp.com:s3cr3ttok@git.example.com/repo.git")).toBe(
151 "ssh://alice@corp.com@git.example.com/repo",
152 );
153 expect(normalizeGitRemoteUrl("ssh://git@git.example.com/repo.git")).toBe(
154 "ssh://git@git.example.com/repo",
155 );
156 expect(normalizeGitRemoteUrl("https://git.example.com/repo.git")).toBe(
157 "https://git.example.com/repo",
158 );
159 expect(normalizeGitRemoteUrl("https://git.example.com/repo@v2.git")).toBe(
160 "https://git.example.com/repo@v2",
161 );
162 expect(normalizeGitRemoteUrl("/srv/git/Repo.git")).toBe("/srv/git/repo");
163 });
164});
165
166describe("parseGitRemoteRepository", () => {
167 it("drops an encoded .git suffix like a literal one", () => {
168 expect(parseGitRemoteRepository("ssh://git@gitlab.com/team/repo%2Egit")).toEqual({
169 host: "gitlab.com",
170 path: "team/repo",
171 });
172 // A non-bare repository's `.git` directory names the checkout it sits in.
173 for (const remote of [
174 "ssh://me@myserver/home/me/project/.git",
175 "ssh://me@myserver/home/me/project/%2Egit/",
176 ]) {
177 expect(parseGitRemoteRepository(remote)).toEqual({
178 host: "myserver",
179 path: "home/me/project",
180 });
181 }
182 });
183});
184
185describe("isBareGitConfig", () => {
186 it("reads Git's numeric booleans without accepting invalid or overflowing values", () => {
187 for (const value of [
188 "true",
189 "yes",
190 "on",
191 "1",
192 "2",
193 "-1",
194 "+1",
195 "01",
196 "0x10",
197 "1k",
198 "1m",
199 "1g",
200 "2147483647",
201 "-2147483648",
202 ]) {
203 expect(isBareGitConfig(`[core]\nbare = ${value}\n`), value).toBe(true);
204 }
205 for (const value of [
206 "false",
207 "no",
208 "off",
209 "0",
210 "-0",
211 "00",
212 "0x0",
213 "0k",
214 "08",
215 "1.5",
216 "2no",
217 "2g",
218 "2147483648",
219 "-2147483649",
220 ]) {
221 expect(isBareGitConfig(`[core]\nbare = ${value}\n`), value).toBe(false);
222 }
223 expect(isBareGitConfig("[core]\nbare = 2\nbare = 0\n")).toBe(false);
224 expect(isBareGitConfig("[core]\nbare = false\nbare = -2\n")).toBe(true);
225 });
226
227 it("reads continued bare values after comments and at end of input", () => {
228 const config = ["[core] bare = false # ignored backslash \\", 'bare = "tr\\', 'ue"'].join("\n");
229
230 expect(isBareGitConfig(config)).toBe(true);
231 expect(isBareGitConfig("[core]\nbare = tr\\\nue\\")).toBe(true);
232 expect(isBareGitConfig('[core]\nbare = "true\\')).toBe(false);
233 expect(isBareGitConfig('[core]\nbare = "true\\\n')).toBe(false);
234 });
235});
236
237describe("parseOriginUrlFromGitConfig", () => {
238 it("reads the origin url and ignores other remotes", () => {
239 const config = [
240 "[core]",
241 "\trepositoryformatversion = 0",
242 '[remote "upstream"]',
243 "\turl = https://github.com/other/repo.git",
244 '[remote "origin"]',
245 "\turl = git@github.com:pingdotgg/t3code.git",
246 "\tfetch = +refs/heads/*:refs/remotes/origin/*",
247 '[branch "main"]',
248 "\tremote = origin",
249 ].join("\n");
250 expect(parseOriginUrlFromGitConfig(config)).toBe("git@github.com:pingdotgg/t3code.git");
251 });
252
253 it("strips inline comments and quotes from the url value", () => {
254 expect(
255 parseOriginUrlFromGitConfig(
256 '[remote "origin"]\n\turl = https://github.com/acme/repo.git # mirror\n',
257 ),
258 ).toBe("https://github.com/acme/repo.git");
259 expect(
260 parseOriginUrlFromGitConfig('[remote "origin"]\n\turl = "git@github.com:acme/repo.git"\n'),
261 ).toBe("git@github.com:acme/repo.git");
262 for (const newline of ["\n", "\r\n"]) {
263 for (const comment of ["#", ";"]) {
264 const config = [
265 '[remote "upstream"]',
266 `url = https://github.com/other/repo.git ${comment} ignored backslash \\`,
267 '[remote "origin"]',
268 `url = https://github.com/acme/repo.git ${comment} ignored backslash \\`,
269 `${comment} ignored backslash \\`,
270 '[remote "fork"]',
271 "url = https://github.com/me/repo.git",
272 ].join(newline);
273 expect(parseOriginUrlFromGitConfig(config)).toBe("https://github.com/acme/repo.git");
274 }
275 }
276 });
277
278 it("accepts legacy dotted headers, header comments, and line continuations", () => {
279 expect(parseOriginUrlFromGitConfig("[remote.origin]\n\turl = git@github.com:a/b.git\n")).toBe(
280 "git@github.com:a/b.git",
281 );
282 expect(parseOriginUrlFromGitConfig("[remote.Origin]\n\turl = git@github.com:a/b.git\n")).toBe(
283 "git@github.com:a/b.git",
284 );
285 expect(
286 parseOriginUrlFromGitConfig(
287 '[remote "Origin"]\n\turl = git@github.com:x/y.git\n[remote "origin"]\n\turl = git@github.com:a/b.git\n',
288 ),
289 ).toBe("git@github.com:a/b.git");
290 expect(
291 parseOriginUrlFromGitConfig('[remote "origin"] # primary\n\turl = git@github.com:a/b.git\n'),
292 ).toBe("git@github.com:a/b.git");
293 expect(
294 parseOriginUrlFromGitConfig(
295 '[remote "origin"]\n\turl = https://github.com/acme/\\\n\t\trepo.git\n',
296 ),
297 ).toBe("https://github.com/acme/\t\trepo.git");
298 });
299
300 it.each(["\u2028", "\u2029"])(
301 "preserves Unicode line separators in remote urls: %j",
302 (separator) => {
303 const url = `ssh://git@forge.example/org/first${separator}last.git${separator}`;
304 for (const gap of ["\n", "\r\n", " "]) {
305 expect(parseOriginUrlFromGitConfig(`[remote "origin"]${gap}url = ${url}\n`)).toBe(url);
306 expect(parseOriginUrlFromGitConfig(`[remote "origin"]${gap}url = "${url}"\n`)).toBe(url);
307 }
308 },
309 );
310
311 // A quadratic trim blocks for tens of seconds here, well past the test timeout.
312 it("trims long whitespace runs in linear time", () => {
313 const url = "ssh://git@forge.example/org/repo.git";
314 const padding = " ".repeat(200_000);
315 expect(
316 parseOriginUrlFromGitConfig(`[remote "origin"]\nurl = ${padding}${url}${padding}\n`),
317 ).toBe(url);
318 });
319
320 it("reads settings on the remote header line", () => {
321 const upstream = '\n[remote "upstream"]\n\turl = https://github.com/other/source.git\n';
322 expect(
323 parseOriginUrlFromGitConfig(`[remote "origin"] url = git@github.com:a/b.git${upstream}`),
324 ).toBe("git@github.com:a/b.git");
325 expect(parseOriginUrlFromGitConfig("[remote.Origin]url=git@github.com:a/b.git\n")).toBe(
326 "git@github.com:a/b.git",
327 );
328 expect(
329 parseOriginUrlFromGitConfig(
330 `[remote "origin"] fetch = +refs/heads/*:refs/remotes/origin/*\n\turl = git@github.com:a/b.git${upstream}`,
331 ),
332 ).toBe("git@github.com:a/b.git");
333 });
334
335 it.each(["upstream", String.raw`team\"mirror`])(
336 "falls back to the first remote when there is no origin: %s",
337 (remoteName) => {
338 const config = [
339 `[remote "${remoteName}"]`,
340 "\turl = https://github.com/acme/repo.git",
341 '[remote "fork"]',
342 "\turl = https://github.com/me/repo.git",
343 ].join("\n");
344 expect(parseOriginUrlFromGitConfig(config)).toBe("https://github.com/acme/repo.git");
345 },
346 );
347});
348
349describe("isTemporaryWorktreeBranch", () => {
350 it("matches generated temporary worktree refs", () => {
351 expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/deadbeef`)).toBe(true);
352 expect(isTemporaryWorktreeBranch(` ${WORKTREE_BRANCH_PREFIX}/deadbeef `)).toBe(true);
353 expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/DEADBEEF`)).toBe(true);
354 });
355
356 it("normalizes a UUID-shaped random callback to the canonical 8-hex form", () => {
357 expect(buildTemporaryWorktreeBranchName(() => "f4ae4e0e-f971-4d48-b4f2-9cf0aa54ab12")).toBe(
358 `${WORKTREE_BRANCH_PREFIX}/f4ae4e0e`,
359 );
360 });
361
362 it("matches legacy t3code temporary worktree refs", () => {
363 expect(isTemporaryWorktreeBranch("t3code/deadbeef")).toBe(true);
364 expect(isTemporaryWorktreeBranch("t3code-deadbeef")).toBe(true);
365 expect(isTemporaryWorktreeBranch("t3code/f4ae4e0e-f971-4d48-b4f2-9cf0aa54ab12")).toBe(true);
366 expect(
367 isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/f4ae4e0e-f971-4d48-b4f2-9cf0aa54ab12`),
368 ).toBe(false);
369 });
370
371 it("rejects UUID-shaped refs that are not RFC 4122 v4", () => {
372 expect(isTemporaryWorktreeBranch("t3code/f4ae4e0e-f971-1d48-b4f2-9cf0aa54ab12")).toBe(false);
373 expect(isTemporaryWorktreeBranch("t3code/f4ae4e0e-f971-4d48-c4f2-9cf0aa54ab12")).toBe(false);
374 });
375
376 it("matches the flat fallback used when a plain t3 branch exists", () => {
377 const flat = flattenTemporaryWorktreeBranchName(`${WORKTREE_BRANCH_PREFIX}/deadbeef`);
378 expect(flat).toBe(`${WORKTREE_BRANCH_PREFIX}-deadbeef`);
379 expect(isTemporaryWorktreeBranch(flat)).toBe(true);
380 expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}-deadbeef-extra`)).toBe(false);
381 expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}-feature`)).toBe(false);
382 expect(flattenTemporaryWorktreeBranchName("t3code/f4ae4e0e-f971-4d48-b4f2-9cf0aa54ab12")).toBe(
383 `${WORKTREE_BRANCH_PREFIX}-f4ae4e0e`,
384 );
385 expect(flattenTemporaryWorktreeBranchName("t3code-deadbeef")).toBe(
386 `${WORKTREE_BRANCH_PREFIX}-deadbeef`,
387 );
388 expect(flattenTemporaryWorktreeBranchName("t3code/deadbeef")).toBe(
389 `${WORKTREE_BRANCH_PREFIX}-deadbeef`,
390 );
391 });
392
393 it("rejects non-temporary refName names", () => {
394 expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/feature/demo`)).toBe(false);
395 expect(isTemporaryWorktreeBranch("main")).toBe(false);
396 expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/deadbeef-extra`)).toBe(false);
397 });
398});
399
400describe("applyGitStatusStreamEvent", () => {
401 it("treats a remote-only update as a repository when local state is missing", () => {
402 const remote: VcsStatusRemoteResult = {
403 hasUpstream: true,
404 aheadCount: 2,
405 behindCount: 1,
406 pr: null,
407 };
408
409 expect(applyGitStatusStreamEvent(null, { _tag: "remoteUpdated", remote })).toEqual({
410 isRepo: true,
411 hasPrimaryRemote: false,
412 isDefaultRef: false,
413 refName: null,
414 hasWorkingTreeChanges: false,
415 workingTree: { files: [], insertions: 0, deletions: 0 },
416 hasUpstream: true,
417 aheadCount: 2,
418 behindCount: 1,
419 pr: null,
420 });
421 });
422
423 it("preserves local-only fields when applying a remote update", () => {
424 const current: VcsStatusResult = {
425 isRepo: true,
426 sourceControlProvider: {
427 kind: SourceControlProviderKind.make("github"),
428 name: "GitHub",
429 baseUrl: "https://github.com",
430 },
431 hasPrimaryRemote: true,
432 isDefaultRef: false,
433 refName: "feature/demo",
434 hasWorkingTreeChanges: true,
435 workingTree: {
436 files: [{ path: "src/demo.ts", insertions: 1, deletions: 0 }],
437 insertions: 1,
438 deletions: 0,
439 },
440 hasUpstream: false,
441 aheadCount: 0,
442 behindCount: 0,
443 pr: null,
444 };
445
446 const remote: VcsStatusRemoteResult = {
447 hasUpstream: true,
448 aheadCount: 2,
449 behindCount: 1,
450 pr: null,
451 };
452
453 expect(applyGitStatusStreamEvent(current, { _tag: "remoteUpdated", remote })).toEqual({
454 ...current,
455 hasUpstream: true,
456 aheadCount: 2,
457 behindCount: 1,
458 pr: null,
459 });
460 });
461});
462
463describe("sanitizeFeatureBranchName", () => {
464 it("sanitizes an explicit namespace before preserving it", () => {
465 expect(sanitizeFeatureBranchName(' "FIX//Calendar recruitment filter" ')).toBe(
466 "fix/calendar-recruitment-filter",
467 );
468 });
469
470 // regression: #15615 generated branch namespaces are preserved
471 it.each([
472 ["refine toolbar", "feature/refine-toolbar"],
473 [" /?. / ", "feature/update"],
474 ["fix///", "feature/fix"],
475 ])("keeps the fallback for unprefixed input %s", (input, expected) => {
476 expect(sanitizeFeatureBranchName(input)).toBe(expected);
477 });
478
479 it("keeps accented letters as their plain letters", () => {
480 expect(sanitizeFeatureBranchName("fix/Añadir validación del café")).toBe(
481 "fix/anadir-validacion-del-cafe",
482 );
483 });
484
485 it("keeps words with letters that have no Unicode decomposition whole", () => {
486 expect(sanitizeFeatureBranchName("Größe der Straße korrigieren")).toBe(
487 "feature/grosse-der-strasse-korrigieren",
488 );
489 expect(sanitizeFeatureBranchName("fix/Đặt tên")).toBe("fix/dat-ten");
490 expect(sanitizeFeatureBranchName("Napraw błąd w żółtym przycisku")).toBe(
491 "feature/napraw-blad-w-zoltym-przycisku",
492 );
493 });
494});
495
496describe("resolveAutoFeatureBranchName", () => {
497 it("resolves case-insensitive collisions within the generated namespace", () => {
498 expect(
499 resolveAutoFeatureBranchName(
500 ["FIX/refine-toolbar", "fix/refine-toolbar-2"],
501 "fix/refine-toolbar",
502 ),
503 ).toBe("fix/refine-toolbar-3");
504 });
505
506 // regression: #15615 generated branch namespaces are preserved
507 it.each([
508 ["fix/name", ["fix"], "fix-2/name"],
509 ["fix/name", ["fix/name/child"], "fix/name-2"],
510 ["fix/name", ["fixes", "fix/name-extra/child"], "fix/name"],
511 ])("resolves %s against namespace blockers %j", (preferredBranch, existingNames, expected) => {
512 expect(resolveAutoFeatureBranchName(existingNames, preferredBranch)).toBe(expected);
513 });
514});
515
516describe("formatGeneratedBranchName", () => {
517 it.each([
518 [" Team / Jules.lock/", "Team/Jules-lock/add-search"],
519 ["-team//feature@{new}", "team/feature-new/add-search"],
520 [" /?. / ", "add-search"],
521 ])("normalizes invalid static prefix %s", (prefix, expected) => {
522 expect(
523 formatGeneratedBranchName("Add Search", { mode: "static", prefix, instructions: "" }),
524 ).toBe(expected);
525 });
526 it("uses the model's semantic prefix without the stored static prefix", () => {
527 expect(
528 formatGeneratedBranchName("feat/Add Search", {
529 mode: "semantic",
530 prefix: "t3code",
531 instructions: "",
532 }),
533 ).toBe("feat/add-search");
534 });
535});