Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

git.ts

441 lines15.2 KB

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