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