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

git.ts

421 lines14.3 KB

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";
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;
56​
57export function sanitizeFeatureBranchName(raw: string): string {
58 const sanitized = sanitizeBranchFragment(raw);
59 return sanitized.includes("/") ? sanitized : `feature/${sanitized}`;
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;
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);
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}`;
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}`;
127​
128export function isTemporaryWorktreeBranch(refName: string): boolean {
129 return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase());
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 }
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("/");
150​
151function lowerCaseRemote(value: string, dropSuffix = stripGitSuffix): string {
152 return dropSuffix(value.trim().replace(/\/+$/g, "")).toLowerCase();
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, dropSuffix);
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 repositorySegments = dropSuffix(url.pathname.replace(/\/+$/, ""))
172 .split("/")
173 .filter((segment) => segment.length > 0);
174 if (url.hostname && repositorySegments.length > 1) {
175 return { host: url.hostname, path: canonicalRepositoryPath(repositorySegments.join("/")) };
176 }
177 } catch {
178 return null;
179 }
180 }
181​
182 // A userless one-letter prefix is a Windows drive, not an SCP host.
183 const scpStyleHostAndPath = /^[a-z]:/i.test(normalized)
184 ? null
185 : /^(?:[a-zA-Z0-9._-]+@)?(\[[0-9a-f:.]+\]|[^@:/\\\s[\]]+):\/?([^/\s]+(?:\/[^/\s]+)+)$/i.exec(
186 normalized,
187 );
188 const scpHost = scpStyleHostAndPath?.[1];
189 const scpPath = scpStyleHostAndPath?.[2];
190 if (!scpHost || !scpPath) return null;
191 const path = canonicalRepositoryPath(scpPath);
192 if (!scpHost.startsWith("[")) return { host: scpHost, path };
193 try {
194 // Spell an IPv6 host as the URL branch does, so `[::1]:a/b` and `ssh://[::1]/a/b` share a key.
195 return { host: new URL(`ssh://${scpHost}`).hostname, path };
196 } catch {
197 return null;
198 }
200​
201/**
202 * `host/path` for a remote that names a host, otherwise the remote itself, lower case. A host that
203 * spells repositories differently over SSH or treats `.git` literally has its source control registry's
204 * `repositoryKeyFromRemote` rewrite this, so persisted keys come from that, not from here.
205 */
206export function normalizeGitRemoteUrl(value: string): string {
207 const repository = parseGitRemoteRepository(value);
208 if (repository !== null) return `${repository.host}/${repository.path}`;
209 // The key is shown to clients and persisted, so a URL it cannot parse keeps only what names the
210 // repository: no password, query or fragment, and a user only over SSH, where it is a login name.
211 const remote = lowerCaseRemote(value);
212 const url = /^([a-z][a-z0-9+.-]*):\/\/(?:([^/?#:@]*)(?::[^/?#]*)?@)?([^?#]*)/.exec(remote);
213 if (url === null) return remote;
214 const [, scheme = "", user = "", rest = ""] = url;
215 return lowerCaseRemote(`${scheme}://${scheme === "ssh" && user ? `${user}@` : ""}${rest}`);
217​
218function* gitConfigLines(configText: string) {
219 let pending = "";
220 let quoted = false;
221 for (const line of configText.split(/\r?\n/)) {
222 let continued = false;
223 if (line.endsWith("\\") || pending.length > 0) {
224 for (const [token] of line.matchAll(/\\[\s\S]?|["#;]/g)) {
225 if (token === '"') quoted = !quoted;
226 else if (!quoted && (token === "#" || token === ";")) break;
227 else if (token === "\\") continued = true;
228 }
229 }
230 if (continued) {
231 pending += line.slice(0, -1);
232 continue;
233 }
234 if (!quoted) yield pending + line;
235 pending = "";
236 quoted = false;
237 }
238 if (pending.length > 0 && !quoted) yield pending;
240​
241function parseGitConfigValue(raw: string): string {
242 let out = "";
243 let quoted = false;
244 for (let index = 0; index < raw.length; index += 1) {
245 const char = raw[index]!;
246 if (char === "\\" && index + 1 < raw.length) {
247 out += raw[index + 1];
248 index += 1;
249 continue;
250 }
251 if (char === '"') {
252 quoted = !quoted;
253 continue;
254 }
255 if (!quoted && (char === "#" || char === ";")) break;
256 out += char;
257 }
258 return out.trim();
260​
261function isTrueGitConfigValue(value: string): boolean {
262 if (value === "true" || value === "yes" || value === "on") return true;
263 const numeric = /^([+-]?)(0x[0-9a-f]+|0[0-7]*|[1-9][0-9]*)([kmg]?)$/.exec(value);
264 if (numeric === null) return false;
265 const digits = numeric[2]!;
266 const magnitude = digits.startsWith("0x")
267 ? Number.parseInt(digits.slice(2), 16)
268 : Number.parseInt(digits, digits.startsWith("0") ? 8 : 10);
269 const scale =
270 numeric[3] === "k" ? 1024 : numeric[3] === "m" ? 1024 ** 2 : numeric[3] === "g" ? 1024 ** 3 : 1;
271 const number = magnitude * scale * (numeric[1] === "-" ? -1 : 1);
272 // Git's boolean parser accepts integers only within its signed 32-bit range.
273 return number !== 0 && number >= -2147483648 && number <= 2147483647;
275​
276export function isBareGitConfig(configText: string): boolean {
277 let inCore = false;
278 let bare = false;
279 for (const rawLine of gitConfigLines(configText)) {
280 let line = rawLine.trim();
281 // Git accepts the first setting on the section header's own line.
282 const header = /^\[\s*([^\]]*?)\s*\](.*)$/.exec(line);
283 if (header !== null) {
284 inCore = header[1]!.toLowerCase() === "core";
285 line = header[2]!.trim();
286 }
287 if (!inCore) continue;
288 const match = /^bare\s*(?:=(.*)|[#;].*)?$/i.exec(line);
289 if (match === null) continue;
290 const value = match[1] === undefined ? "true" : parseGitConfigValue(match[1]).toLowerCase();
291 bare = isTrueGitConfigValue(value);
292 }
293 return bare;
295​
296export function parseOriginUrlFromGitConfig(configText: string): string | null {
297 let section: string | null = null;
298 let originUrl: string | null = null;
299 let firstRemoteUrl: string | null = null;
300 for (const rawLine of gitConfigLines(configText)) {
301 let line = rawLine.trim();
302 if (line.length === 0 || line.startsWith("#") || line.startsWith(";")) continue;
303 // Git preserves case in quoted remote subsections but lowercases legacy dotted ones,
304 // and accepts the first setting on the section header's own line.
305 const header = /^\[\s*remote(?:\s+"([^"]+)"|\.([^\]\s]+))\s*\](.*)$/i.exec(line);
306 if (header) {
307 section = header[1] ?? header[2]?.toLowerCase() ?? null;
308 line = header[3]!.trim();
309 } else if (line.startsWith("[")) {
310 section = null;
311 continue;
312 }
313 if (section === null) continue;
314 const match = /^url\s*=\s*(.*)$/i.exec(line);
315 if (!match) continue;
316 const url = parseGitConfigValue(match[1] ?? "");
317 if (url.length === 0) continue;
318 if (section === "origin") {
319 originUrl ??= url;
320 } else {
321 firstRemoteUrl ??= url;
322 }
323 }
324 return originUrl ?? firstRemoteUrl;
326​
327// Replace only Git-rejected whitespace; nonbreaking spaces are valid ref characters.
328export function sanitizeNewRefName(rawName: string): string {
329 return rawName.trim().replace(/[ \t\n\r\f\v]+/g, "-");
331​
332export function dedupeRemoteBranchesWithLocalMatches(
333 refs: ReadonlyArray<VcsRef>,
334): ReadonlyArray<VcsRef> {
335 const localBranchNames = new Set(
336 Arr.filterMap(refs, (refName) =>
337 refName.isRemote ? Result.failVoid : Result.succeed(refName.name),
338 ),
339 );
340​
341 return refs.filter((refName) => {
342 if (!refName.isRemote || refName.remoteName !== "origin") {
343 return true;
344 }
345​
346 const localBranchName = deriveLocalBranchNameFromRemoteRef(refName.name);
347 return localBranchName.length === 0 || !localBranchNames.has(localBranchName);
348 });
350​
351const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
352 hasUpstream: false,
353 aheadCount: 0,
354 behindCount: 0,
355 aheadOfDefaultCount: 0,
356 pr: null,
357};
358​
359export function mergeGitStatusParts(
360 local: VcsStatusLocalResult,
361 remote: VcsStatusRemoteResult | null,
362): VcsStatusResult {
363 return {
364 ...local,
365 ...(remote ?? EMPTY_GIT_STATUS_REMOTE),
366 };
368​
369function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
370 return {
371 hasUpstream: status.hasUpstream,
372 aheadCount: status.aheadCount,
373 behindCount: status.behindCount,
374 ...(status.aheadOfDefaultCount === undefined
375 ? {}
376 : { aheadOfDefaultCount: status.aheadOfDefaultCount }),
377 pr: status.pr,
378 };
380​
381function toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult {
382 return {
383 isRepo: status.isRepo,
384 ...(status.sourceControlProvider
385 ? { sourceControlProvider: status.sourceControlProvider }
386 : {}),
387 hasPrimaryRemote: status.hasPrimaryRemote,
388 isDefaultRef: status.isDefaultRef,
389 refName: status.refName,
390 hasWorkingTreeChanges: status.hasWorkingTreeChanges,
391 workingTree: status.workingTree,
392 ...(status.branchChanges ? { branchChanges: status.branchChanges } : {}),
393 };
395​
396export function applyGitStatusStreamEvent(
397 current: VcsStatusResult | null,
398 event: VcsStatusStreamEvent,
399): VcsStatusResult {
400 switch (event._tag) {
401 case "snapshot":
402 return mergeGitStatusParts(event.local, event.remote);
403 case "localUpdated":
404 return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);
405 case "remoteUpdated":
406 if (current === null) {
407 return mergeGitStatusParts(
408 {
409 isRepo: true,
410 hasPrimaryRemote: false,
411 isDefaultRef: false,
412 refName: null,
413 hasWorkingTreeChanges: false,
414 workingTree: { files: [], insertions: 0, deletions: 0 },
415 },
416 event.remote,
417 );
418 }
419 return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
420 }