The best way to control Claude Code, Codex and more from any computer or phone

main
ts 407 lines 13.5 KB
Raw
1 import type {
2 BranchNamingOptions,
3 VcsRef,
4 VcsStatusLocalResult,
5 VcsStatusRemoteResult,
6 VcsStatusResult,
7 VcsStatusStreamEvent,
8 } from "@t3tools/contracts";
9 import * as Arr from "effect/Array";
10 import * as Result from "effect/Result";
11
12 import { foldLatinDiacritics } from "./path.ts";
13
14 export const WORKTREE_BRANCH_PREFIX = "t3";
15 const TEMP_WORKTREE_HEX_TOKEN = "[0-9a-f]{8}";
16 const 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}";
18 const 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
22 export 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";
38 }
39
40 export 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;
55 }
56
57 export function sanitizeFeatureBranchName(raw: string): string {
58 const sanitized = sanitizeBranchFragment(raw);
59 return sanitized.includes("/") ? sanitized : `feature/${sanitized}`;
60 }
61
62 const AUTO_FEATURE_BRANCH_FALLBACK = "feature/update";
63
64 export 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;
93 }
94
95 export 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);
101 }
102
103 export 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}`;
111 }
112
113 /** Flatten temporary t3/<hex> refs because an existing t3 branch blocks nested refs. */
114 export 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}`;
119 }
120
121 export function isTemporaryWorktreeBranch(refName: string): boolean {
122 return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase());
123 }
124
125 const stripGitSuffix = (path: string) => path.replace(/\.git$/i, "");
126
127 function 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 }
134 }
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 */
140 export function canonicalRepositoryPath(path: string): string {
141 return path.split("/").map(canonicalPathSegment).join("/");
142 }
143
144 function lowerCaseRemote(value: string, dropSuffix = stripGitSuffix): string {
145 return dropSuffix(value.trim().replace(/\/+$/g, "")).toLowerCase();
146 }
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 */
153 export 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 }
192 }
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 */
199 export function normalizeGitRemoteUrl(value: string): string {
200 const repository = parseGitRemoteRepository(value);
201 return repository === null ? lowerCaseRemote(value) : `${repository.host}/${repository.path}`;
202 }
203
204 function* gitConfigLines(configText: string) {
205 let pending = "";
206 let quoted = false;
207 for (const line of configText.split(/\r?\n/)) {
208 let continued = false;
209 if (line.endsWith("\\") || pending.length > 0) {
210 for (const [token] of line.matchAll(/\\[\s\S]?|["#;]/g)) {
211 if (token === '"') quoted = !quoted;
212 else if (!quoted && (token === "#" || token === ";")) break;
213 else if (token === "\\") continued = true;
214 }
215 }
216 if (continued) {
217 pending += line.slice(0, -1);
218 continue;
219 }
220 if (!quoted) yield pending + line;
221 pending = "";
222 quoted = false;
223 }
224 if (pending.length > 0 && !quoted) yield pending;
225 }
226
227 function parseGitConfigValue(raw: string): string {
228 let out = "";
229 let quoted = false;
230 for (let index = 0; index < raw.length; index += 1) {
231 const char = raw[index]!;
232 if (char === "\\" && index + 1 < raw.length) {
233 out += raw[index + 1];
234 index += 1;
235 continue;
236 }
237 if (char === '"') {
238 quoted = !quoted;
239 continue;
240 }
241 if (!quoted && (char === "#" || char === ";")) break;
242 out += char;
243 }
244 return out.trim();
245 }
246
247 function isTrueGitConfigValue(value: string): boolean {
248 if (value === "true" || value === "yes" || value === "on") return true;
249 const numeric = /^([+-]?)(0x[0-9a-f]+|0[0-7]*|[1-9][0-9]*)([kmg]?)$/.exec(value);
250 if (numeric === null) return false;
251 const digits = numeric[2]!;
252 const magnitude = digits.startsWith("0x")
253 ? Number.parseInt(digits.slice(2), 16)
254 : Number.parseInt(digits, digits.startsWith("0") ? 8 : 10);
255 const scale =
256 numeric[3] === "k" ? 1024 : numeric[3] === "m" ? 1024 ** 2 : numeric[3] === "g" ? 1024 ** 3 : 1;
257 const number = magnitude * scale * (numeric[1] === "-" ? -1 : 1);
258 // Git's boolean parser accepts integers only within its signed 32-bit range.
259 return number !== 0 && number >= -2147483648 && number <= 2147483647;
260 }
261
262 export function isBareGitConfig(configText: string): boolean {
263 let inCore = false;
264 let bare = false;
265 for (const rawLine of gitConfigLines(configText)) {
266 let line = rawLine.trim();
267 // Git accepts the first setting on the section header's own line.
268 const header = /^\[\s*([^\]]*?)\s*\](.*)$/.exec(line);
269 if (header !== null) {
270 inCore = header[1]!.toLowerCase() === "core";
271 line = header[2]!.trim();
272 }
273 if (!inCore) continue;
274 const match = /^bare\s*(?:=(.*)|[#;].*)?$/i.exec(line);
275 if (match === null) continue;
276 const value = match[1] === undefined ? "true" : parseGitConfigValue(match[1]).toLowerCase();
277 bare = isTrueGitConfigValue(value);
278 }
279 return bare;
280 }
281
282 export function parseOriginUrlFromGitConfig(configText: string): string | null {
283 let section: string | null = null;
284 let originUrl: string | null = null;
285 let firstRemoteUrl: string | null = null;
286 for (const rawLine of gitConfigLines(configText)) {
287 let line = rawLine.trim();
288 if (line.length === 0 || line.startsWith("#") || line.startsWith(";")) continue;
289 // Git preserves case in quoted remote subsections but lowercases legacy dotted ones,
290 // and accepts the first setting on the section header's own line.
291 const header = /^\[\s*remote(?:\s+"([^"]+)"|\.([^\]\s]+))\s*\](.*)$/i.exec(line);
292 if (header) {
293 section = header[1] ?? header[2]?.toLowerCase() ?? null;
294 line = header[3]!.trim();
295 } else if (line.startsWith("[")) {
296 section = null;
297 continue;
298 }
299 if (section === null) continue;
300 const match = /^url\s*=\s*(.*)$/i.exec(line);
301 if (!match) continue;
302 const url = parseGitConfigValue(match[1] ?? "");
303 if (url.length === 0) continue;
304 if (section === "origin") {
305 originUrl ??= url;
306 } else {
307 firstRemoteUrl ??= url;
308 }
309 }
310 return originUrl ?? firstRemoteUrl;
311 }
312
313 // Replace only Git-rejected whitespace; nonbreaking spaces are valid ref characters.
314 export function sanitizeNewRefName(rawName: string): string {
315 return rawName.trim().replace(/[ \t\n\r\f\v]+/g, "-");
316 }
317
318 export function dedupeRemoteBranchesWithLocalMatches(
319 refs: ReadonlyArray<VcsRef>,
320 ): ReadonlyArray<VcsRef> {
321 const localBranchNames = new Set(
322 Arr.filterMap(refs, (refName) =>
323 refName.isRemote ? Result.failVoid : Result.succeed(refName.name),
324 ),
325 );
326
327 return refs.filter((refName) => {
328 if (!refName.isRemote || refName.remoteName !== "origin") {
329 return true;
330 }
331
332 const localBranchName = deriveLocalBranchNameFromRemoteRef(refName.name);
333 return localBranchName.length === 0 || !localBranchNames.has(localBranchName);
334 });
335 }
336
337 const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
338 hasUpstream: false,
339 aheadCount: 0,
340 behindCount: 0,
341 aheadOfDefaultCount: 0,
342 pr: null,
343 };
344
345 export function mergeGitStatusParts(
346 local: VcsStatusLocalResult,
347 remote: VcsStatusRemoteResult | null,
348 ): VcsStatusResult {
349 return {
350 ...local,
351 ...(remote ?? EMPTY_GIT_STATUS_REMOTE),
352 };
353 }
354
355 function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
356 return {
357 hasUpstream: status.hasUpstream,
358 aheadCount: status.aheadCount,
359 behindCount: status.behindCount,
360 ...(status.aheadOfDefaultCount === undefined
361 ? {}
362 : { aheadOfDefaultCount: status.aheadOfDefaultCount }),
363 pr: status.pr,
364 };
365 }
366
367 function toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult {
368 return {
369 isRepo: status.isRepo,
370 ...(status.sourceControlProvider
371 ? { sourceControlProvider: status.sourceControlProvider }
372 : {}),
373 hasPrimaryRemote: status.hasPrimaryRemote,
374 isDefaultRef: status.isDefaultRef,
375 refName: status.refName,
376 hasWorkingTreeChanges: status.hasWorkingTreeChanges,
377 workingTree: status.workingTree,
378 ...(status.branchChanges ? { branchChanges: status.branchChanges } : {}),
379 };
380 }
381
382 export function applyGitStatusStreamEvent(
383 current: VcsStatusResult | null,
384 event: VcsStatusStreamEvent,
385 ): VcsStatusResult {
386 switch (event._tag) {
387 case "snapshot":
388 return mergeGitStatusParts(event.local, event.remote);
389 case "localUpdated":
390 return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);
391 case "remoteUpdated":
392 if (current === null) {
393 return mergeGitStatusParts(
394 {
395 isRepo: true,
396 hasPrimaryRemote: false,
397 isDefaultRef: false,
398 refName: null,
399 hasWorkingTreeChanges: false,
400 workingTree: { files: [], insertions: 0, deletions: 0 },
401 },
402 event.remote,
403 );
404 }
405 return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
406 }
407 }