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