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

git.ts

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