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

git.ts

414 lines14.0 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​
95export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
96 const firstSeparatorIndex = branchName.indexOf("/");
97 if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
98 return branchName;
99 }
100 return branchName.slice(firstSeparatorIndex + 1);
102​
103export function buildTemporaryWorktreeBranchName(
104 randomHex: (byteLength: number) => string,
105): string {
106 const token = randomHex(4)
107 .toLowerCase()
108 .replace(/[^0-9a-f]/g, "")
109 .slice(0, 8);
110 return `${WORKTREE_BRANCH_PREFIX}/${token}`;
112​
113/** Flatten temporary t3/<hex> refs because an existing t3 branch blocks nested refs. */
114export function flattenTemporaryWorktreeBranchName(refName: string): string {
115 const normalized = refName.trim().toLowerCase();
116 const tokenStart = normalized.search(/[-/]/) + 1;
117 const token = normalized.slice(tokenStart, tokenStart + 8);
118 return `${WORKTREE_BRANCH_PREFIX}-${token}`;
120​
121export function isTemporaryWorktreeBranch(refName: string): boolean {
122 return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase());
124​
125const stripGitSuffix = (path: string) => path.replace(/\.git$/i, "");
126​
127function canonicalPathSegment(segment: string): string {
128 try {
129 // Lowercase before encoding: lowercasing the escape `%C3%84` never reaches the `Ä` it names.
130 return encodeURIComponent(decodeURIComponent(segment).toLowerCase()).toLowerCase();
131 } catch {
132 return segment.toLowerCase();
133 }
135​
136/**
137 * A repository path in one lower-case spelling. Remotes, browsers and agents escape a name
138 * differently (`a%20(b)`, `a%20%28b%29`, `a (b)`), and keys built from them are compared as text.
139 */
140export function canonicalRepositoryPath(path: string): string {
141 return path.split("/").map(canonicalPathSegment).join("/");
143​
144function lowerCaseRemote(value: string, dropSuffix = stripGitSuffix): string {
145 return dropSuffix(value.trim().replace(/\/+$/g, "")).toLowerCase();
147​
148/**
149 * The host and repository path a remote names, lower case and without a port, or null for a
150 * remote that names no host, such as a local path. Most hosts serve `name.git` as `name`, so the
151 * path drops that suffix unless `keepGitSuffix` asks for the name as written.
152 */
153export function parseGitRemoteRepository(
154 value: string,
155 options?: { readonly keepGitSuffix?: boolean },
156): { readonly host: string; readonly path: string } | null {
157 const dropSuffix = options?.keepGitSuffix ? (path: string) => path : stripGitSuffix;
158 const normalized = lowerCaseRemote(value, dropSuffix);
159​
160 if (/^(?:ssh|https?|git):\/\//i.test(normalized)) {
161 try {
162 // Apply suffix policy to the path: `.git` may sit before a query or fragment.
163 const url = new URL(value.trim().toLowerCase());
164 const repositorySegments = dropSuffix(url.pathname.replace(/\/+$/, ""))
165 .split("/")
166 .filter((segment) => segment.length > 0);
167 if (url.hostname && repositorySegments.length > 1) {
168 return { host: url.hostname, path: canonicalRepositoryPath(repositorySegments.join("/")) };
169 }
170 } catch {
171 return null;
172 }
173 }
174​
175 // A userless one-letter prefix is a Windows drive, not an SCP host.
176 const scpStyleHostAndPath = /^[a-z]:/i.test(normalized)
177 ? null
178 : /^(?:[a-zA-Z0-9._-]+@)?(\[[0-9a-f:.]+\]|[^@:/\\\s[\]]+):\/?([^/\s]+(?:\/[^/\s]+)+)$/i.exec(
179 normalized,
180 );
181 const scpHost = scpStyleHostAndPath?.[1];
182 const scpPath = scpStyleHostAndPath?.[2];
183 if (!scpHost || !scpPath) return null;
184 const path = canonicalRepositoryPath(scpPath);
185 if (!scpHost.startsWith("[")) return { host: scpHost, path };
186 try {
187 // Spell an IPv6 host as the URL branch does, so `[::1]:a/b` and `ssh://[::1]/a/b` share a key.
188 return { host: new URL(`ssh://${scpHost}`).hostname, path };
189 } catch {
190 return null;
191 }
193​
194/**
195 * `host/path` for a remote that names a host, otherwise the remote itself, lower case. A host that
196 * spells repositories differently over SSH or treats `.git` literally has its source control registry's
197 * `repositoryKeyFromRemote` rewrite this, so persisted keys come from that, not from here.
198 */
199export function normalizeGitRemoteUrl(value: string): string {
200 const repository = parseGitRemoteRepository(value);
201 if (repository !== null) return `${repository.host}/${repository.path}`;
202 // The key is shown to clients and persisted, so a URL it cannot parse keeps only what names the
203 // repository: no password, query or fragment, and a user only over SSH, where it is a login name.
204 const remote = lowerCaseRemote(value);
205 const url = /^([a-z][a-z0-9+.-]*):\/\/(?:([^/?#:@]*)(?::[^/?#]*)?@)?([^?#]*)/.exec(remote);
206 if (url === null) return remote;
207 const [, scheme = "", user = "", rest = ""] = url;
208 return lowerCaseRemote(`${scheme}://${scheme === "ssh" && user ? `${user}@` : ""}${rest}`);
210​
211function* gitConfigLines(configText: string) {
212 let pending = "";
213 let quoted = false;
214 for (const line of configText.split(/\r?\n/)) {
215 let continued = false;
216 if (line.endsWith("\\") || pending.length > 0) {
217 for (const [token] of line.matchAll(/\\[\s\S]?|["#;]/g)) {
218 if (token === '"') quoted = !quoted;
219 else if (!quoted && (token === "#" || token === ";")) break;
220 else if (token === "\\") continued = true;
221 }
222 }
223 if (continued) {
224 pending += line.slice(0, -1);
225 continue;
226 }
227 if (!quoted) yield pending + line;
228 pending = "";
229 quoted = false;
230 }
231 if (pending.length > 0 && !quoted) yield pending;
233​
234function parseGitConfigValue(raw: string): string {
235 let out = "";
236 let quoted = false;
237 for (let index = 0; index < raw.length; index += 1) {
238 const char = raw[index]!;
239 if (char === "\\" && index + 1 < raw.length) {
240 out += raw[index + 1];
241 index += 1;
242 continue;
243 }
244 if (char === '"') {
245 quoted = !quoted;
246 continue;
247 }
248 if (!quoted && (char === "#" || char === ";")) break;
249 out += char;
250 }
251 return out.trim();
253​
254function isTrueGitConfigValue(value: string): boolean {
255 if (value === "true" || value === "yes" || value === "on") return true;
256 const numeric = /^([+-]?)(0x[0-9a-f]+|0[0-7]*|[1-9][0-9]*)([kmg]?)$/.exec(value);
257 if (numeric === null) return false;
258 const digits = numeric[2]!;
259 const magnitude = digits.startsWith("0x")
260 ? Number.parseInt(digits.slice(2), 16)
261 : Number.parseInt(digits, digits.startsWith("0") ? 8 : 10);
262 const scale =
263 numeric[3] === "k" ? 1024 : numeric[3] === "m" ? 1024 ** 2 : numeric[3] === "g" ? 1024 ** 3 : 1;
264 const number = magnitude * scale * (numeric[1] === "-" ? -1 : 1);
265 // Git's boolean parser accepts integers only within its signed 32-bit range.
266 return number !== 0 && number >= -2147483648 && number <= 2147483647;
268​
269export function isBareGitConfig(configText: string): boolean {
270 let inCore = false;
271 let bare = false;
272 for (const rawLine of gitConfigLines(configText)) {
273 let line = rawLine.trim();
274 // Git accepts the first setting on the section header's own line.
275 const header = /^\[\s*([^\]]*?)\s*\](.*)$/.exec(line);
276 if (header !== null) {
277 inCore = header[1]!.toLowerCase() === "core";
278 line = header[2]!.trim();
279 }
280 if (!inCore) continue;
281 const match = /^bare\s*(?:=(.*)|[#;].*)?$/i.exec(line);
282 if (match === null) continue;
283 const value = match[1] === undefined ? "true" : parseGitConfigValue(match[1]).toLowerCase();
284 bare = isTrueGitConfigValue(value);
285 }
286 return bare;
288​
289export function parseOriginUrlFromGitConfig(configText: string): string | null {
290 let section: string | null = null;
291 let originUrl: string | null = null;
292 let firstRemoteUrl: string | null = null;
293 for (const rawLine of gitConfigLines(configText)) {
294 let line = rawLine.trim();
295 if (line.length === 0 || line.startsWith("#") || line.startsWith(";")) continue;
296 // Git preserves case in quoted remote subsections but lowercases legacy dotted ones,
297 // and accepts the first setting on the section header's own line.
298 const header = /^\[\s*remote(?:\s+"([^"]+)"|\.([^\]\s]+))\s*\](.*)$/i.exec(line);
299 if (header) {
300 section = header[1] ?? header[2]?.toLowerCase() ?? null;
301 line = header[3]!.trim();
302 } else if (line.startsWith("[")) {
303 section = null;
304 continue;
305 }
306 if (section === null) continue;
307 const match = /^url\s*=\s*(.*)$/i.exec(line);
308 if (!match) continue;
309 const url = parseGitConfigValue(match[1] ?? "");
310 if (url.length === 0) continue;
311 if (section === "origin") {
312 originUrl ??= url;
313 } else {
314 firstRemoteUrl ??= url;
315 }
316 }
317 return originUrl ?? firstRemoteUrl;
319​
320// Replace only Git-rejected whitespace; nonbreaking spaces are valid ref characters.
321export function sanitizeNewRefName(rawName: string): string {
322 return rawName.trim().replace(/[ \t\n\r\f\v]+/g, "-");
324​
325export function dedupeRemoteBranchesWithLocalMatches(
326 refs: ReadonlyArray<VcsRef>,
327): ReadonlyArray<VcsRef> {
328 const localBranchNames = new Set(
329 Arr.filterMap(refs, (refName) =>
330 refName.isRemote ? Result.failVoid : Result.succeed(refName.name),
331 ),
332 );
333​
334 return refs.filter((refName) => {
335 if (!refName.isRemote || refName.remoteName !== "origin") {
336 return true;
337 }
338​
339 const localBranchName = deriveLocalBranchNameFromRemoteRef(refName.name);
340 return localBranchName.length === 0 || !localBranchNames.has(localBranchName);
341 });
343​
344const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
345 hasUpstream: false,
346 aheadCount: 0,
347 behindCount: 0,
348 aheadOfDefaultCount: 0,
349 pr: null,
350};
351​
352export function mergeGitStatusParts(
353 local: VcsStatusLocalResult,
354 remote: VcsStatusRemoteResult | null,
355): VcsStatusResult {
356 return {
357 ...local,
358 ...(remote ?? EMPTY_GIT_STATUS_REMOTE),
359 };
361​
362function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
363 return {
364 hasUpstream: status.hasUpstream,
365 aheadCount: status.aheadCount,
366 behindCount: status.behindCount,
367 ...(status.aheadOfDefaultCount === undefined
368 ? {}
369 : { aheadOfDefaultCount: status.aheadOfDefaultCount }),
370 pr: status.pr,
371 };
373​
374function toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult {
375 return {
376 isRepo: status.isRepo,
377 ...(status.sourceControlProvider
378 ? { sourceControlProvider: status.sourceControlProvider }
379 : {}),
380 hasPrimaryRemote: status.hasPrimaryRemote,
381 isDefaultRef: status.isDefaultRef,
382 refName: status.refName,
383 hasWorkingTreeChanges: status.hasWorkingTreeChanges,
384 workingTree: status.workingTree,
385 ...(status.branchChanges ? { branchChanges: status.branchChanges } : {}),
386 };
388​
389export function applyGitStatusStreamEvent(
390 current: VcsStatusResult | null,
391 event: VcsStatusStreamEvent,
392): VcsStatusResult {
393 switch (event._tag) {
394 case "snapshot":
395 return mergeGitStatusParts(event.local, event.remote);
396 case "localUpdated":
397 return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);
398 case "remoteUpdated":
399 if (current === null) {
400 return mergeGitStatusParts(
401 {
402 isRepo: true,
403 hasPrimaryRemote: false,
404 isDefaultRef: false,
405 refName: null,
406 hasWorkingTreeChanges: false,
407 workingTree: { files: [], insertions: 0, deletions: 0 },
408 },
409 event.remote,
410 );
411 }
412 return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
413 }