Open History to see the last commit
1import type {
2 BranchNamingOptions,
3 VcsRef,
4 SourceControlProviderInfo,
5 VcsStatusLocalResult,
6 VcsStatusRemoteResult,
7 VcsStatusResult,
8 VcsStatusStreamEvent,
9} from "@t3tools/contracts";
10import * as Arr from "effect/Array";
11import * as Result from "effect/Result";
12import { detectSourceControlProviderFromRemoteUrl } from "./sourceControl.ts";
13
14export const WORKTREE_BRANCH_PREFIX = "t3";
15// Canonical form is `t3/<8 hex>`. `t3-<8 hex>` is the fallback when a plain `t3`
16// branch blocks the namespace. The matcher also accepts every legacy shape, so
17// existing threads stay eligible for branch regeneration: `t3code/<8 hex>` and
18// `t3code-<8 hex>` from before the prefix was shortened, and `t3code/<uuid>` from
19// older mobile builds that used Crypto.randomUUID() (always RFC 4122 v4, so version
20// nibble `4` and variant nibble `[89ab]`). Nothing looser than what was generated.
21const TEMP_WORKTREE_HEX_TOKEN = "[0-9a-f]{8}";
22const TEMP_WORKTREE_UUID_V4_TOKEN =
23 "[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}";
24const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(
25 `^(?:${WORKTREE_BRANCH_PREFIX}[-/]${TEMP_WORKTREE_HEX_TOKEN}|t3code(?:[-/]${TEMP_WORKTREE_HEX_TOKEN}|\\/${TEMP_WORKTREE_UUID_V4_TOKEN}))$`,
26);
27
28/**
29 * Sanitize an arbitrary string into a valid, lowercase git refName fragment.
30 * Strips quotes, collapses separators, limits to 64 chars.
31 */
32export function sanitizeBranchFragment(raw: string): string {
33 const normalized = raw
34 .trim()
35 .toLowerCase()
36 .replace(/['"`]/g, "")
37 .replace(/^[./\s_-]+|[./\s_-]+$/g, "");
38
39 const branchFragment = normalized
40 .replace(/[^a-z0-9/_-]+/g, "-")
41 .replace(/\/+/g, "/")
42 .replace(/-+/g, "-")
43 .replace(/^[./_-]+|[./_-]+$/g, "")
44 .slice(0, 64)
45 .replace(/[./_-]+$/g, "");
46
47 return branchFragment.length > 0 ? branchFragment : "update";
48}
49
50/** Custom naming preserves the model's complete ref; Git validates it on rename. */
51export function formatGeneratedBranchName(raw: string, naming?: BranchNamingOptions): string {
52 if (naming?.mode === "custom") return raw.trim();
53 const branch = sanitizeBranchFragment(raw);
54 if (naming?.mode !== "static") return branch;
55 const prefix = naming.prefix
56 .split("/")
57 .map((part) =>
58 part
59 .replace(/[^a-zA-Z0-9_-]+/g, "-")
60 .replace(/-+/g, "-")
61 .replace(/^-+|-+$/g, ""),
62 )
63 .filter(Boolean)
64 .join("/");
65 return prefix ? `${prefix}/${branch}` : branch;
66}
67
68/**
69 * Sanitize a string into a `feature/…` refName name.
70 * Preserves an existing `feature/` prefix or slash-separated namespace.
71 */
72export function sanitizeFeatureBranchName(raw: string): string {
73 const sanitized = sanitizeBranchFragment(raw);
74 if (sanitized.includes("/")) {
75 return sanitized.startsWith("feature/") ? sanitized : `feature/${sanitized}`;
76 }
77 return `feature/${sanitized}`;
78}
79
80const AUTO_FEATURE_BRANCH_FALLBACK = "feature/update";
81
82/**
83 * Resolve a unique `feature/…` refName name that doesn't collide with
84 * any existing refName. Appends a numeric suffix when needed.
85 */
86export function resolveAutoFeatureBranchName(
87 existingBranchNames: readonly string[],
88 preferredBranch?: string,
89): string {
90 const preferred = preferredBranch?.trim();
91 const resolvedBase = sanitizeFeatureBranchName(
92 preferred && preferred.length > 0 ? preferred : AUTO_FEATURE_BRANCH_FALLBACK,
93 );
94 const existingNames = new Set(existingBranchNames.map((refName) => refName.toLowerCase()));
95
96 if (!existingNames.has(resolvedBase)) {
97 return resolvedBase;
98 }
99
100 let suffix = 2;
101 while (existingNames.has(`${resolvedBase}-${suffix}`)) {
102 suffix += 1;
103 }
104
105 return `${resolvedBase}-${suffix}`;
106}
107
108/**
109 * Strip the remote prefix from a remote ref such as `origin/feature/demo`.
110 */
111export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
112 const firstSeparatorIndex = branchName.indexOf("/");
113 if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
114 return branchName;
115 }
116 return branchName.slice(firstSeparatorIndex + 1);
117}
118
119export function buildTemporaryWorktreeBranchName(
120 randomHex: (byteLength: number) => string,
121): string {
122 // Normalize to exactly 8 lowercase hex chars so a UUID-shaped callback
123 // still produces the canonical temporary branch form.
124 const token = randomHex(4)
125 .toLowerCase()
126 .replace(/[^0-9a-f]/g, "")
127 .slice(0, 8);
128 return `${WORKTREE_BRANCH_PREFIX}/${token}`;
129}
130
131/**
132 * Git stores refs as paths, so a plain `t3` branch makes every `t3/<hex>`
133 * ref impossible. This moves a temporary name to the flat `t3-<hex>` sibling.
134 */
135export function flattenTemporaryWorktreeBranchName(refName: string): string {
136 // Keep only the canonical 8-hex token so legacy `t3code/` and UUID names map cleanly.
137 const normalized = refName.trim().toLowerCase();
138 const tokenStart = normalized.search(/[-/]/) + 1;
139 const token = normalized.slice(tokenStart, tokenStart + 8);
140 return `${WORKTREE_BRANCH_PREFIX}-${token}`;
141}
142
143export function isTemporaryWorktreeBranch(refName: string): boolean {
144 return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase());
145}
146
147/**
148 * The web spelling of an Azure DevOps repository reached over SSH, or null for anything else.
149 *
150 * Azure alone addresses one repository under two names that share no part: `ssh.dev.azure.com` and
151 * `v3/{org}/{project}/{repo}` over SSH, against `dev.azure.com` and `{org}/{project}/_git/{repo}`
152 * everywhere a person sees it. A project cloned over SSH would otherwise be a different repository
153 * to every comparison made against a pull request URL, which arrives in the web spelling. So the
154 * web spelling is the one both are keyed by.
155 */
156function azureDevOpsRepositoryKey(host: string, segments: ReadonlyArray<string>): string | null {
157 if (host !== "ssh.dev.azure.com" && host !== "vs-ssh.visualstudio.com") return null;
158 const [marker, organization, project, repository] = segments;
159 if (segments.length !== 4 || marker !== "v3") return null;
160 if (!organization || !project || !repository) return null;
161 return host === "ssh.dev.azure.com"
162 ? `dev.azure.com/${organization}/${project}/_git/${repository}`
163 : `${organization}.visualstudio.com/${project}/_git/${repository}`;
164}
165
166/**
167 * Normalize a git remote URL into a stable comparison key.
168 */
169export function normalizeGitRemoteUrl(value: string): string {
170 const normalized = value
171 .trim()
172 .replace(/\/+$/g, "")
173 .replace(/\.git$/i, "")
174 .toLowerCase();
175
176 if (/^(?:ssh|https?|git):\/\//i.test(normalized)) {
177 try {
178 const url = new URL(normalized);
179 const repositorySegments = url.pathname.split("/").filter((segment) => segment.length > 0);
180 if (url.hostname && repositorySegments.length > 1) {
181 return (
182 azureDevOpsRepositoryKey(url.hostname, repositorySegments) ??
183 `${url.hostname}/${repositorySegments.join("/")}`
184 );
185 }
186 } catch {
187 return normalized;
188 }
189 }
190
191 const scpStyleHostAndPath = /^[a-zA-Z0-9._-]+@([^:/\s]+):([^/\s]+(?:\/[^/\s]+)+)$/i.exec(
192 normalized,
193 );
194 const scpHost = scpStyleHostAndPath?.[1];
195 const scpPath = scpStyleHostAndPath?.[2];
196 if (scpHost && scpPath) {
197 return azureDevOpsRepositoryKey(scpHost, scpPath.split("/")) ?? `${scpHost}/${scpPath}`;
198 }
199
200 return normalized;
201}
202
203/**
204 * Unquote a git config value: strip an inline `#` or `;` comment outside
205 * quotes, then drop surrounding quotes and backslash escapes.
206 */
207function parseGitConfigValue(raw: string): string {
208 let out = "";
209 let quoted = false;
210 for (let index = 0; index < raw.length; index += 1) {
211 const char = raw[index]!;
212 if (char === "\\" && index + 1 < raw.length) {
213 out += raw[index + 1];
214 index += 1;
215 continue;
216 }
217 if (char === '"') {
218 quoted = !quoted;
219 continue;
220 }
221 if (!quoted && (char === "#" || char === ";")) break;
222 out += char;
223 }
224 return out.trim();
225}
226
227/**
228 * Read the primary remote URL from raw `.git/config` text without spawning
229 * git. Prefers `remote.origin.url` and falls back to the first remote so
230 * clones made with `git clone --origin <name>` still resolve.
231 */
232export function parseOriginUrlFromGitConfig(configText: string): string | null {
233 let section: string | null = null;
234 let originUrl: string | null = null;
235 let firstRemoteUrl: string | null = null;
236 // A trailing backslash continues the value on the next line.
237 const joined = configText.replace(/\\\r?\n[ \t]*/g, "");
238 for (const rawLine of joined.split(/\r?\n/)) {
239 const line = rawLine.trim();
240 if (line.length === 0 || line.startsWith("#") || line.startsWith(";")) continue;
241 // Both `[remote "origin"]` and the legacy `[remote.origin]` form, with an
242 // optional trailing comment. Git keeps quoted subsections case-sensitive
243 // but folds the dotted form to lowercase.
244 const header = /^\[\s*remote(?:\s+"([^"]+)"|\.([^\]\s]+))\s*\](?:\s*[#;].*)?$/i.exec(line);
245 if (header) {
246 section = header[1] ?? header[2]?.toLowerCase() ?? null;
247 continue;
248 }
249 if (line.startsWith("[")) {
250 section = null;
251 continue;
252 }
253 if (section === null) continue;
254 const match = /^url\s*=\s*(.*)$/i.exec(line);
255 if (!match) continue;
256 const url = parseGitConfigValue(match[1] ?? "");
257 if (url.length === 0) continue;
258 if (section === "origin") {
259 originUrl ??= url;
260 } else {
261 firstRemoteUrl ??= url;
262 }
263 }
264 return originUrl ?? firstRemoteUrl;
265}
266
267/**
268 * Best-effort parse of a GitHub `owner/repo` identifier from common remote URL shapes.
269 */
270export function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {
271 const trimmed = url?.trim() ?? "";
272 if (trimmed.length === 0) {
273 return null;
274 }
275
276 const match =
277 /^(?:git@github\.com:|ssh:\/\/(?:git@)?github\.com\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(
278 trimmed,
279 );
280 const repositoryNameWithOwner = match?.[1]?.trim() ?? "";
281 return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;
282}
283
284function deriveLocalBranchNameCandidatesFromRemoteRef(
285 branchName: string,
286 remoteName?: string,
287): ReadonlyArray<string> {
288 const candidates = new Set<string>();
289 const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
290 if (firstSlashCandidate.length > 0) {
291 candidates.add(firstSlashCandidate);
292 }
293
294 if (remoteName) {
295 const remotePrefix = `${remoteName}/`;
296 if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
297 candidates.add(branchName.slice(remotePrefix.length));
298 }
299 }
300
301 return [...candidates];
302}
303
304// Git rejects ASCII space and the ASCII control characters (tab, newline and
305// friends) in ref names, so the picker's "Create new ref" entry can only fail
306// for a typed name like "new branch". Replacing runs of those with a dash makes
307// the name usable without reimplementing check-ref-format: names invalid for
308// other reasons still surface the git error. Only the whitespace git actually
309// rejects is replaced — git accepts U+00A0 and friends, and rewriting those
310// would silently create a ref the user never asked for. Case and existing
311// dashes are left alone, since ref names are case sensitive and consecutive
312// dashes are valid.
313export function sanitizeNewRefName(rawName: string): string {
314 return rawName.trim().replace(/[ \t\n\r\f\v]+/g, "-");
315}
316
317/**
318 * Hide `origin/*` remote refs when a matching local refName already exists.
319 */
320export function dedupeRemoteBranchesWithLocalMatches(
321 refs: ReadonlyArray<VcsRef>,
322): ReadonlyArray<VcsRef> {
323 const localBranchNames = new Set(
324 Arr.filterMap(refs, (refName) =>
325 refName.isRemote ? Result.failVoid : Result.succeed(refName.name),
326 ),
327 );
328
329 return refs.filter((refName) => {
330 if (!refName.isRemote) {
331 return true;
332 }
333
334 if (refName.remoteName !== "origin") {
335 return true;
336 }
337
338 const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
339 refName.name,
340 refName.remoteName,
341 );
342 return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
343 });
344}
345
346export function detectSourceControlProviderFromGitRemoteUrl(
347 remoteUrl: string,
348): SourceControlProviderInfo | null {
349 return detectSourceControlProviderFromRemoteUrl(remoteUrl);
350}
351
352const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
353 hasUpstream: false,
354 aheadCount: 0,
355 behindCount: 0,
356 aheadOfDefaultCount: 0,
357 pr: null,
358};
359
360export function mergeGitStatusParts(
361 local: VcsStatusLocalResult,
362 remote: VcsStatusRemoteResult | null,
363): VcsStatusResult {
364 return {
365 ...local,
366 ...(remote ?? EMPTY_GIT_STATUS_REMOTE),
367 };
368}
369
370function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
371 return {
372 hasUpstream: status.hasUpstream,
373 aheadCount: status.aheadCount,
374 behindCount: status.behindCount,
375 ...(status.aheadOfDefaultCount === undefined
376 ? {}
377 : { aheadOfDefaultCount: status.aheadOfDefaultCount }),
378 pr: status.pr,
379 };
380}
381
382function toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult {
383 return {
384 isRepo: status.isRepo,
385 ...(status.sourceControlProvider
386 ? { sourceControlProvider: status.sourceControlProvider }
387 : {}),
388 hasPrimaryRemote: status.hasPrimaryRemote,
389 isDefaultRef: status.isDefaultRef,
390 refName: status.refName,
391 hasWorkingTreeChanges: status.hasWorkingTreeChanges,
392 workingTree: status.workingTree,
393 ...(status.branchChanges ? { branchChanges: status.branchChanges } : {}),
394 };
395}
396
397export function applyGitStatusStreamEvent(
398 current: VcsStatusResult | null,
399 event: VcsStatusStreamEvent,
400): VcsStatusResult {
401 switch (event._tag) {
402 case "snapshot":
403 return mergeGitStatusParts(event.local, event.remote);
404 case "localUpdated":
405 return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);
406 case "remoteUpdated":
407 if (current === null) {
408 return mergeGitStatusParts(
409 {
410 isRepo: true,
411 hasPrimaryRemote: false,
412 isDefaultRef: false,
413 refName: null,
414 hasWorkingTreeChanges: false,
415 workingTree: { files: [], insertions: 0, deletions: 0 },
416 },
417 event.remote,
418 );
419 }
420 return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
421 }
422}