Open History to see the last commit
1import type {
2 BranchNamingOptions,
3 VcsRef,
4 VcsStatusLocalResult,
5 VcsStatusRemoteResult,
6 VcsStatusResult,
7 VcsStatusStreamEvent,
8} from "@t3tools/contracts";
9import * as Arr from "effect/Array";
10import * as Result from "effect/Result";
11
12import { foldLatinDiacritics } from "./path.ts";
13
14export const WORKTREE_BRANCH_PREFIX = "t3";
15const TEMP_WORKTREE_HEX_TOKEN = "[0-9a-f]{8}";
16const TEMP_WORKTREE_UUID_V4_TOKEN =
17 "[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}";
18const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(
19 `^(?:${WORKTREE_BRANCH_PREFIX}[-/]${TEMP_WORKTREE_HEX_TOKEN}|t3code(?:[-/]${TEMP_WORKTREE_HEX_TOKEN}|\\/${TEMP_WORKTREE_UUID_V4_TOKEN}))$`,
20);
21
22export function sanitizeBranchFragment(raw: string): string {
23 const normalized = foldLatinDiacritics(raw)
24 .trim()
25 .toLowerCase()
26 .replace(/['"`]/g, "")
27 .replace(/^[./\s_-]+|[./\s_-]+$/g, "");
28
29 const branchFragment = normalized
30 .replace(/[^a-z0-9/_-]+/g, "-")
31 .replace(/\/+/g, "/")
32 .replace(/-+/g, "-")
33 .replace(/^[./_-]+|[./_-]+$/g, "")
34 .slice(0, 64)
35 .replace(/[./_-]+$/g, "");
36
37 return branchFragment.length > 0 ? branchFragment : "update";
38}
39
40export function formatGeneratedBranchName(raw: string, naming?: BranchNamingOptions): string {
41 if (naming?.mode === "custom") return raw.trim();
42 const branch = sanitizeBranchFragment(raw);
43 if (naming?.mode !== "static") return branch;
44 const prefix = naming.prefix
45 .split("/")
46 .map((part) =>
47 part
48 .replace(/[^a-zA-Z0-9_-]+/g, "-")
49 .replace(/-+/g, "-")
50 .replace(/^-+|-+$/g, ""),
51 )
52 .filter(Boolean)
53 .join("/");
54 return prefix ? `${prefix}/${branch}` : branch;
55}
56
57export function sanitizeFeatureBranchName(raw: string): string {
58 const sanitized = sanitizeBranchFragment(raw);
59 return sanitized.includes("/") ? sanitized : `feature/${sanitized}`;
60}
61
62const AUTO_FEATURE_BRANCH_FALLBACK = "feature/update";
63
64export function resolveAutoFeatureBranchName(
65 existingBranchNames: readonly string[],
66 preferredBranch?: string,
67): string {
68 const preferred = preferredBranch?.trim();
69 const resolvedBase = sanitizeFeatureBranchName(
70 preferred && preferred.length > 0 ? preferred : AUTO_FEATURE_BRANCH_FALLBACK,
71 );
72 const existingNames = existingBranchNames.map((refName) => refName.toLowerCase());
73 const existingRefs = new Set(existingNames);
74 const parts = resolvedBase.split("/");
75 let resolved = "";
76
77 for (const [index, part] of parts.entries()) {
78 const base = resolved ? `${resolved}/${part}` : part;
79 let candidate = base;
80 let suffix = 2;
81 while (
82 existingRefs.has(candidate) ||
83 (index === parts.length - 1 &&
84 existingNames.some((refName) => refName.startsWith(`${candidate}/`)))
85 ) {
86 candidate = `${base}-${suffix}`;
87 suffix += 1;
88 }
89 resolved = candidate;
90 }
91
92 return resolved;
93}
94
95// A remote name can itself contain slashes; the known remote name beats guessing at the first one.
96export function deriveLocalBranchNameFromRemoteRef(
97 branchName: string,
98 remoteName?: string,
99): string {
100 if (remoteName && branchName.startsWith(`${remoteName}/`)) {
101 return branchName.slice(remoteName.length + 1);
102 }
103 const firstSeparatorIndex = branchName.indexOf("/");
104 if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
105 return branchName;
106 }
107 return branchName.slice(firstSeparatorIndex + 1);
108}
109
110export function buildTemporaryWorktreeBranchName(
111 randomHex: (byteLength: number) => string,
112): string {
113 const token = randomHex(4)
114 .toLowerCase()
115 .replace(/[^0-9a-f]/g, "")
116 .slice(0, 8);
117 return `${WORKTREE_BRANCH_PREFIX}/${token}`;
118}
119
120/** Flatten temporary t3/<hex> refs because an existing t3 branch blocks nested refs. */
121export function flattenTemporaryWorktreeBranchName(refName: string): string {
122 const normalized = refName.trim().toLowerCase();
123 const tokenStart = normalized.search(/[-/]/) + 1;
124 const token = normalized.slice(tokenStart, tokenStart + 8);
125 return `${WORKTREE_BRANCH_PREFIX}-${token}`;
126}
127
128export function isTemporaryWorktreeBranch(refName: string): boolean {
129 return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase());
130}
131
132const stripGitSuffix = (path: string) => path.replace(/\.git$/i, "");
133
134function canonicalPathSegment(segment: string): string {
135 try {
136 // Lowercase before encoding: lowercasing the escape `%C3%84` never reaches the `Ä` it names.
137 return encodeURIComponent(decodeURIComponent(segment).toLowerCase()).toLowerCase();
138 } catch {
139 return segment.toLowerCase();
140 }
141}
142
143/**
144 * A repository path in one lower-case spelling. Remotes, browsers and agents escape a name
145 * differently (`a%20(b)`, `a%20%28b%29`, `a (b)`), and keys built from them are compared as text.
146 */
147export function canonicalRepositoryPath(path: string): string {
148 return path.split("/").map(canonicalPathSegment).join("/");
149}
150
151function lowerCaseRemote(value: string, dropSuffix = stripGitSuffix): string {
152 return dropSuffix(value.trim().replace(/\/+$/g, "")).toLowerCase();
153}
154
155/**
156 * The host and repository path a remote names, lower case and without a port, or null for a
157 * remote that names no host, such as a local path. Most hosts serve `name.git` as `name`, so the
158 * path drops that suffix unless `keepGitSuffix` asks for the name as written.
159 */
160export function parseGitRemoteRepository(
161 value: string,
162 options?: { readonly keepGitSuffix?: boolean },
163): { readonly host: string; readonly path: string } | null {
164 const dropSuffix = options?.keepGitSuffix ? (path: string) => path : stripGitSuffix;
165 const normalized = lowerCaseRemote(value, (remote) => remote);
166
167 if (/^(?:ssh|https?|git):\/\//i.test(normalized)) {
168 try {
169 // Apply suffix policy to the path: `.git` may sit before a query or fragment.
170 const url = new URL(value.trim().toLowerCase());
171 const path = canonicalRepositoryPath(url.pathname.replace(/\/+$/, ""));
172 const repositorySegments = path.split("/").filter((segment) => segment.length > 0);
173 if (url.hostname && repositorySegments.length > 1) {
174 return {
175 host: url.hostname,
176 path: dropSuffix(repositorySegments.join("/")).replace(/\/+$/, ""),
177 };
178 }
179 } catch {
180 return null;
181 }
182 }
183
184 // A userless one-letter prefix is a Windows drive, not an SCP host.
185 const scpStyleHostAndPath = /^[a-z]:/i.test(normalized)
186 ? null
187 : /^(?:[^-@/\\:\s][^/\\:\s]*@)?(\[[0-9a-f:.]+\]|[^@:/\\\s[\]]+):\/?((?:[^/\s]| )+(?:\/+(?:[^/\s]| )+)+)$/i.exec(
188 normalized,
189 );
190 const scpHost = scpStyleHostAndPath?.[1];
191 const scpPath = scpStyleHostAndPath?.[2];
192 if (!scpHost || !scpPath) return null;
193 const path = dropSuffix(canonicalRepositoryPath(scpPath.replace(/\/+/g, "/"))).replace(
194 /\/+$/,
195 "",
196 );
197 if (!scpHost.startsWith("[")) return { host: scpHost, path };
198 try {
199 // Spell an IPv6 host as the URL branch does, so `[::1]:a/b` and `ssh://[::1]/a/b` share a key.
200 return { host: new URL(`ssh://${scpHost}`).hostname, path };
201 } catch {
202 return null;
203 }
204}
205
206/**
207 * `host/path` for a remote that names a host, otherwise the remote itself, lower case. A host that
208 * spells repositories differently over SSH or treats `.git` literally has its source control registry's
209 * `repositoryKeyFromRemote` rewrite this, so persisted keys come from that, not from here.
210 */
211export function normalizeGitRemoteUrl(value: string): string {
212 const repository = parseGitRemoteRepository(value);
213 if (repository !== null) return `${repository.host}/${repository.path}`;
214 // The key is shown to clients and persisted, so a URL it cannot parse keeps only what names the
215 // repository: no password, query or fragment, and a user only over SSH, where it is a login name.
216 const remote = lowerCaseRemote(value);
217 const url = /^([a-z][a-z0-9+.-]*):\/\/(?:([^/?#]*)@)?([^?#]*)/.exec(remote);
218 if (url === null) return remote;
219 const [, scheme = "", userinfo = "", rest = ""] = url;
220 const colonIndex = userinfo.indexOf(":");
221 const user = colonIndex === -1 ? userinfo : userinfo.slice(0, colonIndex);
222 return lowerCaseRemote(`${scheme}://${scheme === "ssh" && user ? `${user}@` : ""}${rest}`);
223}
224
225function* gitConfigLines(configText: string) {
226 let pending = "";
227 let quoted = false;
228 for (const line of configText.split(/\r?\n/)) {
229 let continued = false;
230 if (line.endsWith("\\") || pending.length > 0) {
231 for (const [token] of line.matchAll(/\\[\s\S]?|["#;]/g)) {
232 if (token === '"') quoted = !quoted;
233 else if (!quoted && (token === "#" || token === ";")) break;
234 else if (token === "\\") continued = true;
235 }
236 }
237 if (continued) {
238 pending += line.slice(0, -1);
239 continue;
240 }
241 if (!quoted) yield pending + line;
242 pending = "";
243 quoted = false;
244 }
245 if (pending.length > 0 && !quoted) yield pending;
246}
247
248function parseGitConfigValue(raw: string): string {
249 let out = "";
250 let quoted = false;
251 for (let index = 0; index < raw.length; index += 1) {
252 const char = raw[index]!;
253 if (char === "\\" && index + 1 < raw.length) {
254 out += raw[index + 1];
255 index += 1;
256 continue;
257 }
258 if (char === '"') {
259 quoted = !quoted;
260 continue;
261 }
262 if (!quoted && (char === "#" || char === ";")) break;
263 out += char;
264 }
265 return trimGitWhitespace(out);
266}
267
268// Git trims only ASCII whitespace; String#trim would also drop U+2028/U+2029 from a value.
269function trimGitWhitespace(value: string): string {
270 let start = 0;
271 let end = value.length;
272 while (start < end && GIT_WHITESPACE.has(value[start]!)) start += 1;
273 while (end > start && GIT_WHITESPACE.has(value[end - 1]!)) end -= 1;
274 return value.slice(start, end);
275}
276
277const GIT_WHITESPACE = new Set([" ", "\t", "\n", "\r", "\f", "\v"]);
278
279function isTrueGitConfigValue(value: string): boolean {
280 if (value === "true" || value === "yes" || value === "on") return true;
281 const numeric = /^([+-]?)(0x[0-9a-f]+|0[0-7]*|[1-9][0-9]*)([kmg]?)$/.exec(value);
282 if (numeric === null) return false;
283 const digits = numeric[2]!;
284 const magnitude = digits.startsWith("0x")
285 ? Number.parseInt(digits.slice(2), 16)
286 : Number.parseInt(digits, digits.startsWith("0") ? 8 : 10);
287 const scale =
288 numeric[3] === "k" ? 1024 : numeric[3] === "m" ? 1024 ** 2 : numeric[3] === "g" ? 1024 ** 3 : 1;
289 const number = magnitude * scale * (numeric[1] === "-" ? -1 : 1);
290 // Git's boolean parser accepts integers only within its signed 32-bit range.
291 return number !== 0 && number >= -2147483648 && number <= 2147483647;
292}
293
294export function isBareGitConfig(configText: string): boolean {
295 let inCore = false;
296 let bare = false;
297 for (const rawLine of gitConfigLines(configText)) {
298 let line = rawLine.trim();
299 // Git accepts the first setting on the section header's own line.
300 const header = /^\[\s*([^\]]*?)\s*\](.*)$/.exec(line);
301 if (header !== null) {
302 inCore = header[1]!.toLowerCase() === "core";
303 line = header[2]!.trim();
304 }
305 if (!inCore) continue;
306 const match = /^bare\s*(?:=(.*)|[#;].*)?$/i.exec(line);
307 if (match === null) continue;
308 const value = match[1] === undefined ? "true" : parseGitConfigValue(match[1]).toLowerCase();
309 bare = isTrueGitConfigValue(value);
310 }
311 return bare;
312}
313
314export function parseOriginUrlFromGitConfig(configText: string): string | null {
315 let section: string | null = null;
316 let originUrl: string | null = null;
317 let firstRemoteUrl: string | null = null;
318 for (const rawLine of gitConfigLines(configText)) {
319 let line = trimGitWhitespace(rawLine);
320 if (line.length === 0 || line.startsWith("#") || line.startsWith(";")) continue;
321 // Git preserves case in quoted remote subsections but lowercases legacy dotted ones,
322 // and accepts the first setting on the section header's own line.
323 const header = /^\[\s*remote(?:\s+"((?:\\.|[^"\\])+)"|\.([^\]\s]+))\s*\](.*)$/is.exec(line);
324 if (header) {
325 section = header[1]?.replace(/\\(.)/g, "$1") ?? header[2]?.toLowerCase() ?? null;
326 line = trimGitWhitespace(header[3]!);
327 } else if (line.startsWith("[")) {
328 section = null;
329 continue;
330 }
331 if (section === null) continue;
332 const match = /^url\s*=\s*(.*)$/is.exec(line);
333 if (!match) continue;
334 const url = parseGitConfigValue(match[1] ?? "");
335 if (url.length === 0) continue;
336 if (section === "origin") {
337 originUrl ??= url;
338 } else {
339 firstRemoteUrl ??= url;
340 }
341 }
342 return originUrl ?? firstRemoteUrl;
343}
344
345// Replace only Git-rejected whitespace; nonbreaking spaces are valid ref characters.
346export function sanitizeNewRefName(rawName: string): string {
347 return rawName.trim().replace(/[ \t\n\r\f\v]+/g, "-");
348}
349
350export function dedupeRemoteBranchesWithLocalMatches(
351 refs: ReadonlyArray<VcsRef>,
352): ReadonlyArray<VcsRef> {
353 const localBranchNames = new Set(
354 Arr.filterMap(refs, (refName) =>
355 refName.isRemote ? Result.failVoid : Result.succeed(refName.name),
356 ),
357 );
358
359 return refs.filter((refName) => {
360 if (!refName.isRemote || refName.remoteName !== "origin") {
361 return true;
362 }
363
364 const localBranchName = deriveLocalBranchNameFromRemoteRef(refName.name);
365 return localBranchName.length === 0 || !localBranchNames.has(localBranchName);
366 });
367}
368
369const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
370 hasUpstream: false,
371 aheadCount: 0,
372 behindCount: 0,
373 aheadOfDefaultCount: 0,
374 pr: null,
375};
376
377export function mergeGitStatusParts(
378 local: VcsStatusLocalResult,
379 remote: VcsStatusRemoteResult | null,
380): VcsStatusResult {
381 return {
382 ...local,
383 ...(remote ?? EMPTY_GIT_STATUS_REMOTE),
384 };
385}
386
387function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
388 return {
389 hasUpstream: status.hasUpstream,
390 aheadCount: status.aheadCount,
391 behindCount: status.behindCount,
392 ...(status.aheadOfDefaultCount === undefined
393 ? {}
394 : { aheadOfDefaultCount: status.aheadOfDefaultCount }),
395 pr: status.pr,
396 };
397}
398
399function toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult {
400 return {
401 isRepo: status.isRepo,
402 ...(status.sourceControlProvider
403 ? { sourceControlProvider: status.sourceControlProvider }
404 : {}),
405 hasPrimaryRemote: status.hasPrimaryRemote,
406 isDefaultRef: status.isDefaultRef,
407 refName: status.refName,
408 hasWorkingTreeChanges: status.hasWorkingTreeChanges,
409 workingTree: status.workingTree,
410 ...(status.branchChanges ? { branchChanges: status.branchChanges } : {}),
411 };
412}
413
414export function applyGitStatusStreamEvent(
415 current: VcsStatusResult | null,
416 event: VcsStatusStreamEvent,
417): VcsStatusResult {
418 switch (event._tag) {
419 case "snapshot":
420 return mergeGitStatusParts(event.local, event.remote);
421 case "localUpdated":
422 return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);
423 case "remoteUpdated":
424 if (current === null) {
425 return mergeGitStatusParts(
426 {
427 isRepo: true,
428 hasPrimaryRemote: false,
429 isDefaultRef: false,
430 refName: null,
431 hasWorkingTreeChanges: false,
432 workingTree: { files: [], insertions: 0, deletions: 0 },
433 },
434 event.remote,
435 );
436 }
437 return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
438 }
439}