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

git.ts

390 lines12.9 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​
12export const WORKTREE_BRANCH_PREFIX = "t3";
13const TEMP_WORKTREE_HEX_TOKEN = "[0-9a-f]{8}";
14const TEMP_WORKTREE_UUID_V4_TOKEN =
15 "[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}";
16const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(
17 `^(?:${WORKTREE_BRANCH_PREFIX}[-/]${TEMP_WORKTREE_HEX_TOKEN}|t3code(?:[-/]${TEMP_WORKTREE_HEX_TOKEN}|\\/${TEMP_WORKTREE_UUID_V4_TOKEN}))$`,
18);
19​
20export function sanitizeBranchFragment(raw: string): string {
21 const normalized = raw
22 .normalize("NFKD")
23 .replace(/[̀-ͯ]/g, "")
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 lowerCaseRemote(value: string, dropSuffix = stripGitSuffix): string {
128 return dropSuffix(value.trim().replace(/\/+$/g, "")).toLowerCase();
130​
131/**
132 * The host and repository path a remote names, lower case and without a port, or null for a
133 * remote that names no host, such as a local path. Most hosts serve `name.git` as `name`, so the
134 * path drops that suffix unless `keepGitSuffix` asks for the name as written.
135 */
136export function parseGitRemoteRepository(
137 value: string,
138 options?: { readonly keepGitSuffix?: boolean },
139): { readonly host: string; readonly path: string } | null {
140 const dropSuffix = options?.keepGitSuffix ? (path: string) => path : stripGitSuffix;
141 const normalized = lowerCaseRemote(value, dropSuffix);
142​
143 if (/^(?:ssh|https?|git):\/\//i.test(normalized)) {
144 try {
145 // Apply suffix policy to the path: `.git` may sit before a query or fragment.
146 const url = new URL(value.trim().toLowerCase());
147 const repositorySegments = dropSuffix(url.pathname.replace(/\/+$/, ""))
148 .split("/")
149 .filter((segment) => segment.length > 0);
150 if (url.hostname && repositorySegments.length > 1) {
151 return { host: url.hostname, path: repositorySegments.join("/") };
152 }
153 } catch {
154 return null;
155 }
156 }
157​
158 // A userless one-letter prefix is a Windows drive, not an SCP host.
159 const scpStyleHostAndPath = /^[a-z]:/i.test(normalized)
160 ? null
161 : /^(?:[a-zA-Z0-9._-]+@)?(\[[0-9a-f:.]+\]|[^@:/\\\s[\]]+):\/?([^/\s]+(?:\/[^/\s]+)+)$/i.exec(
162 normalized,
163 );
164 const scpHost = scpStyleHostAndPath?.[1];
165 const scpPath = scpStyleHostAndPath?.[2];
166 if (!scpHost || !scpPath) return null;
167 if (!scpHost.startsWith("[")) return { host: scpHost, path: scpPath };
168 try {
169 // Spell an IPv6 host as the URL branch does, so `[::1]:a/b` and `ssh://[::1]/a/b` share a key.
170 return { host: new URL(`ssh://${scpHost}`).hostname, path: scpPath };
171 } catch {
172 return null;
173 }
175​
176/**
177 * `host/path` for a remote that names a host, otherwise the remote itself, lower case. A host that
178 * spells repositories differently over SSH or treats `.git` literally has its source control registry's
179 * `repositoryKeyFromRemote` rewrite this, so persisted keys come from that, not from here.
180 */
181export function normalizeGitRemoteUrl(value: string): string {
182 const repository = parseGitRemoteRepository(value);
183 return repository === null ? lowerCaseRemote(value) : `${repository.host}/${repository.path}`;
185​
186function* gitConfigLines(configText: string) {
187 let pending = "";
188 let quoted = false;
189 for (const line of configText.split(/\r?\n/)) {
190 let continued = false;
191 if (line.endsWith("\\") || pending.length > 0) {
192 for (const [token] of line.matchAll(/\\[\s\S]?|["#;]/g)) {
193 if (token === '"') quoted = !quoted;
194 else if (!quoted && (token === "#" || token === ";")) break;
195 else if (token === "\\") continued = true;
196 }
197 }
198 if (continued) {
199 pending += line.slice(0, -1);
200 continue;
201 }
202 if (!quoted) yield pending + line;
203 pending = "";
204 quoted = false;
205 }
206 if (pending.length > 0 && !quoted) yield pending;
208​
209function parseGitConfigValue(raw: string): string {
210 let out = "";
211 let quoted = false;
212 for (let index = 0; index < raw.length; index += 1) {
213 const char = raw[index]!;
214 if (char === "\\" && index + 1 < raw.length) {
215 out += raw[index + 1];
216 index += 1;
217 continue;
218 }
219 if (char === '"') {
220 quoted = !quoted;
221 continue;
222 }
223 if (!quoted && (char === "#" || char === ";")) break;
224 out += char;
225 }
226 return out.trim();
228​
229function isTrueGitConfigValue(value: string): boolean {
230 if (value === "true" || value === "yes" || value === "on") return true;
231 const numeric = /^([+-]?)(0x[0-9a-f]+|0[0-7]*|[1-9][0-9]*)([kmg]?)$/.exec(value);
232 if (numeric === null) return false;
233 const digits = numeric[2]!;
234 const magnitude = digits.startsWith("0x")
235 ? Number.parseInt(digits.slice(2), 16)
236 : Number.parseInt(digits, digits.startsWith("0") ? 8 : 10);
237 const scale =
238 numeric[3] === "k" ? 1024 : numeric[3] === "m" ? 1024 ** 2 : numeric[3] === "g" ? 1024 ** 3 : 1;
239 const number = magnitude * scale * (numeric[1] === "-" ? -1 : 1);
240 // Git's boolean parser accepts integers only within its signed 32-bit range.
241 return number !== 0 && number >= -2147483648 && number <= 2147483647;
243​
244export function isBareGitConfig(configText: string): boolean {
245 let inCore = false;
246 let bare = false;
247 for (const rawLine of gitConfigLines(configText)) {
248 let line = rawLine.trim();
249 // Git accepts the first setting on the section header's own line.
250 const header = /^\[\s*([^\]]*?)\s*\](.*)$/.exec(line);
251 if (header !== null) {
252 inCore = header[1]!.toLowerCase() === "core";
253 line = header[2]!.trim();
254 }
255 if (!inCore) continue;
256 const match = /^bare\s*(?:=(.*)|[#;].*)?$/i.exec(line);
257 if (match === null) continue;
258 const value = match[1] === undefined ? "true" : parseGitConfigValue(match[1]).toLowerCase();
259 bare = isTrueGitConfigValue(value);
260 }
261 return bare;
263​
264export function parseOriginUrlFromGitConfig(configText: string): string | null {
265 let section: string | null = null;
266 let originUrl: string | null = null;
267 let firstRemoteUrl: string | null = null;
268 const joined = configText.replace(/\\\r?\n[ \t]*/g, "");
269 for (const rawLine of joined.split(/\r?\n/)) {
270 let line = rawLine.trim();
271 if (line.length === 0 || line.startsWith("#") || line.startsWith(";")) continue;
272 // Git preserves case in quoted remote subsections but lowercases legacy dotted ones,
273 // and accepts the first setting on the section header's own line.
274 const header = /^\[\s*remote(?:\s+"([^"]+)"|\.([^\]\s]+))\s*\](.*)$/i.exec(line);
275 if (header) {
276 section = header[1] ?? header[2]?.toLowerCase() ?? null;
277 line = header[3]!.trim();
278 } else if (line.startsWith("[")) {
279 section = null;
280 continue;
281 }
282 if (section === null) continue;
283 const match = /^url\s*=\s*(.*)$/i.exec(line);
284 if (!match) continue;
285 const url = parseGitConfigValue(match[1] ?? "");
286 if (url.length === 0) continue;
287 if (section === "origin") {
288 originUrl ??= url;
289 } else {
290 firstRemoteUrl ??= url;
291 }
292 }
293 return originUrl ?? firstRemoteUrl;
295​
296// Replace only Git-rejected whitespace; nonbreaking spaces are valid ref characters.
297export function sanitizeNewRefName(rawName: string): string {
298 return rawName.trim().replace(/[ \t\n\r\f\v]+/g, "-");
300​
301export function dedupeRemoteBranchesWithLocalMatches(
302 refs: ReadonlyArray<VcsRef>,
303): ReadonlyArray<VcsRef> {
304 const localBranchNames = new Set(
305 Arr.filterMap(refs, (refName) =>
306 refName.isRemote ? Result.failVoid : Result.succeed(refName.name),
307 ),
308 );
309​
310 return refs.filter((refName) => {
311 if (!refName.isRemote || refName.remoteName !== "origin") {
312 return true;
313 }
314​
315 const localBranchName = deriveLocalBranchNameFromRemoteRef(refName.name);
316 return localBranchName.length === 0 || !localBranchNames.has(localBranchName);
317 });
319​
320const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
321 hasUpstream: false,
322 aheadCount: 0,
323 behindCount: 0,
324 aheadOfDefaultCount: 0,
325 pr: null,
326};
327​
328export function mergeGitStatusParts(
329 local: VcsStatusLocalResult,
330 remote: VcsStatusRemoteResult | null,
331): VcsStatusResult {
332 return {
333 ...local,
334 ...(remote ?? EMPTY_GIT_STATUS_REMOTE),
335 };
337​
338function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
339 return {
340 hasUpstream: status.hasUpstream,
341 aheadCount: status.aheadCount,
342 behindCount: status.behindCount,
343 ...(status.aheadOfDefaultCount === undefined
344 ? {}
345 : { aheadOfDefaultCount: status.aheadOfDefaultCount }),
346 pr: status.pr,
347 };
349​
350function toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult {
351 return {
352 isRepo: status.isRepo,
353 ...(status.sourceControlProvider
354 ? { sourceControlProvider: status.sourceControlProvider }
355 : {}),
356 hasPrimaryRemote: status.hasPrimaryRemote,
357 isDefaultRef: status.isDefaultRef,
358 refName: status.refName,
359 hasWorkingTreeChanges: status.hasWorkingTreeChanges,
360 workingTree: status.workingTree,
361 ...(status.branchChanges ? { branchChanges: status.branchChanges } : {}),
362 };
364​
365export function applyGitStatusStreamEvent(
366 current: VcsStatusResult | null,
367 event: VcsStatusStreamEvent,
368): VcsStatusResult {
369 switch (event._tag) {
370 case "snapshot":
371 return mergeGitStatusParts(event.local, event.remote);
372 case "localUpdated":
373 return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);
374 case "remoteUpdated":
375 if (current === null) {
376 return mergeGitStatusParts(
377 {
378 isRepo: true,
379 hasPrimaryRemote: false,
380 isDefaultRef: false,
381 refName: null,
382 hasWorkingTreeChanges: false,
383 workingTree: { files: [], insertions: 0, deletions: 0 },
384 },
385 event.remote,
386 );
387 }
388 return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
389 }