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";
15const TEMP_WORKTREE_HEX_TOKEN = "[0-9a-f]{8}";
16const 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}";
18const 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
22export function sanitizeBranchFragment(raw: string): string {
23 const normalized = 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
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;
55}
56
57export function sanitizeFeatureBranchName(raw: string): string {
58 const sanitized = sanitizeBranchFragment(raw);
59 return sanitized.includes("/") ? sanitized : `feature/${sanitized}`;
60}
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;
93}
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);
101}
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}`;
111}
112
113/**
114 * Git stores refs as paths, so a plain `t3` branch makes every `t3/<hex>`
115 * ref impossible. This moves a temporary name to the flat `t3-<hex>` sibling.
116 */
117export function flattenTemporaryWorktreeBranchName(refName: string): string {
118 const normalized = refName.trim().toLowerCase();
119 const tokenStart = normalized.search(/[-/]/) + 1;
120 const token = normalized.slice(tokenStart, tokenStart + 8);
121 return `${WORKTREE_BRANCH_PREFIX}-${token}`;
122}
123
124export function isTemporaryWorktreeBranch(refName: string): boolean {
125 return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase());
126}
127
128/**
129 * Azure alone addresses one repository under two names that share no part: `ssh.dev.azure.com` and
130 * `v3/{org}/{project}/{repo}` over SSH, against `dev.azure.com` and `{org}/{project}/_git/{repo}`
131 * everywhere a person sees it. A project cloned over SSH would otherwise be a different repository
132 * to every comparison made against a pull request URL, which arrives in the web spelling.
133 */
134function azureDevOpsRepositoryKey(host: string, segments: ReadonlyArray<string>): string | null {
135 if (host !== "ssh.dev.azure.com" && host !== "vs-ssh.visualstudio.com") return null;
136 const [marker, organization, project, repository] = segments;
137 if (segments.length !== 4 || marker !== "v3") return null;
138 if (!organization || !project || !repository) return null;
139 return host === "ssh.dev.azure.com"
140 ? `dev.azure.com/${organization}/${project}/_git/${repository}`
141 : `${organization}.visualstudio.com/${project}/_git/${repository}`;
142}
143
144// `[user@]host:path`, git's SCP-like spelling of an SSH remote.
145const SCP_REMOTE_PATTERN = /^(?:([a-z0-9._-]+)@)?([^:/\s@]+):([^/\s]+(?:\/[^/\s]+)+)$/i;
146
147/**
148 * Normalize a git remote URL into a stable comparison key.
149 */
150export function normalizeGitRemoteUrl(value: string): string {
151 const normalized = value
152 .trim()
153 .replace(/\/+$/g, "")
154 .replace(/\.git$/i, "")
155 .toLowerCase();
156
157 if (/^(?:ssh|git\+ssh|ssh\+git|https?|git):\/\//i.test(normalized)) {
158 try {
159 const url = new URL(normalized);
160 const repositorySegments = url.pathname.split("/").filter((segment) => segment.length > 0);
161 if (url.hostname && repositorySegments.length > 1) {
162 return (
163 azureDevOpsRepositoryKey(url.hostname, repositorySegments) ??
164 `${url.hostname}/${repositorySegments.join("/")}`
165 );
166 }
167 } catch {
168 return normalized;
169 }
170 }
171
172 const [, scpUser, scpHost, scpPath] = SCP_REMOTE_PATTERN.exec(normalized) ?? [];
173 // A userless one-letter host is a Windows drive path.
174 if (scpHost && scpPath && (scpUser || scpHost.length > 1)) {
175 return azureDevOpsRepositoryKey(scpHost, scpPath.split("/")) ?? `${scpHost}/${scpPath}`;
176 }
177
178 return normalized;
179}
180
181function parseGitConfigValue(raw: string): string {
182 let out = "";
183 let quoted = false;
184 for (let index = 0; index < raw.length; index += 1) {
185 const char = raw[index]!;
186 if (char === "\\" && index + 1 < raw.length) {
187 out += raw[index + 1];
188 index += 1;
189 continue;
190 }
191 if (char === '"') {
192 quoted = !quoted;
193 continue;
194 }
195 if (!quoted && (char === "#" || char === ";")) break;
196 out += char;
197 }
198 return out.trim();
199}
200
201export function parseOriginUrlFromGitConfig(configText: string): string | null {
202 let section: string | null = null;
203 let originUrl: string | null = null;
204 let firstRemoteUrl: string | null = null;
205 // A trailing backslash continues the value on the next line.
206 const joined = configText.replace(/\\\r?\n[ \t]*/g, "");
207 for (const rawLine of joined.split(/\r?\n/)) {
208 const line = rawLine.trim();
209 if (line.length === 0 || line.startsWith("#") || line.startsWith(";")) continue;
210 // Both `[remote "origin"]` and the legacy `[remote.origin]` form, with an
211 // optional trailing comment. Git keeps quoted subsections case-sensitive
212 // but folds the dotted form to lowercase.
213 const header = /^\[\s*remote(?:\s+"([^"]+)"|\.([^\]\s]+))\s*\](?:\s*[#;].*)?$/i.exec(line);
214 if (header) {
215 section = header[1] ?? header[2]?.toLowerCase() ?? null;
216 continue;
217 }
218 if (line.startsWith("[")) {
219 section = null;
220 continue;
221 }
222 if (section === null) continue;
223 const match = /^url\s*=\s*(.*)$/i.exec(line);
224 if (!match) continue;
225 const url = parseGitConfigValue(match[1] ?? "");
226 if (url.length === 0) continue;
227 if (section === "origin") {
228 originUrl ??= url;
229 } else {
230 firstRemoteUrl ??= url;
231 }
232 }
233 return originUrl ?? firstRemoteUrl;
234}
235
236export function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {
237 const trimmed = url?.trim() ?? "";
238 if (trimmed.length === 0) {
239 return null;
240 }
241
242 const match =
243 /^(?:git@github\.com:|ssh:\/\/(?:git@)?github\.com\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(
244 trimmed,
245 );
246 const repositoryNameWithOwner = match?.[1]?.trim() ?? "";
247 return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;
248}
249
250function deriveLocalBranchNameCandidatesFromRemoteRef(
251 branchName: string,
252 remoteName?: string,
253): ReadonlyArray<string> {
254 const candidates = new Set<string>();
255 const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
256 if (firstSlashCandidate.length > 0) {
257 candidates.add(firstSlashCandidate);
258 }
259
260 if (remoteName) {
261 const remotePrefix = `${remoteName}/`;
262 if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
263 candidates.add(branchName.slice(remotePrefix.length));
264 }
265 }
266
267 return [...candidates];
268}
269
270// Only the whitespace git actually rejects is replaced — git accepts U+00A0 and
271// friends, and rewriting those would silently create a ref the user never asked
272// for.
273export function sanitizeNewRefName(rawName: string): string {
274 return rawName.trim().replace(/[ \t\n\r\f\v]+/g, "-");
275}
276
277export function dedupeRemoteBranchesWithLocalMatches(
278 refs: ReadonlyArray<VcsRef>,
279): ReadonlyArray<VcsRef> {
280 const localBranchNames = new Set(
281 Arr.filterMap(refs, (refName) =>
282 refName.isRemote ? Result.failVoid : Result.succeed(refName.name),
283 ),
284 );
285
286 return refs.filter((refName) => {
287 if (!refName.isRemote) {
288 return true;
289 }
290
291 if (refName.remoteName !== "origin") {
292 return true;
293 }
294
295 const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
296 refName.name,
297 refName.remoteName,
298 );
299 return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
300 });
301}
302
303export function detectSourceControlProviderFromGitRemoteUrl(
304 remoteUrl: string,
305): SourceControlProviderInfo | null {
306 return detectSourceControlProviderFromRemoteUrl(remoteUrl);
307}
308
309const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
310 hasUpstream: false,
311 aheadCount: 0,
312 behindCount: 0,
313 aheadOfDefaultCount: 0,
314 pr: null,
315};
316
317export function mergeGitStatusParts(
318 local: VcsStatusLocalResult,
319 remote: VcsStatusRemoteResult | null,
320): VcsStatusResult {
321 return {
322 ...local,
323 ...(remote ?? EMPTY_GIT_STATUS_REMOTE),
324 };
325}
326
327function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
328 return {
329 hasUpstream: status.hasUpstream,
330 aheadCount: status.aheadCount,
331 behindCount: status.behindCount,
332 ...(status.aheadOfDefaultCount === undefined
333 ? {}
334 : { aheadOfDefaultCount: status.aheadOfDefaultCount }),
335 pr: status.pr,
336 };
337}
338
339function toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult {
340 return {
341 isRepo: status.isRepo,
342 ...(status.sourceControlProvider
343 ? { sourceControlProvider: status.sourceControlProvider }
344 : {}),
345 hasPrimaryRemote: status.hasPrimaryRemote,
346 isDefaultRef: status.isDefaultRef,
347 refName: status.refName,
348 hasWorkingTreeChanges: status.hasWorkingTreeChanges,
349 workingTree: status.workingTree,
350 ...(status.branchChanges ? { branchChanges: status.branchChanges } : {}),
351 };
352}
353
354export function applyGitStatusStreamEvent(
355 current: VcsStatusResult | null,
356 event: VcsStatusStreamEvent,
357): VcsStatusResult {
358 switch (event._tag) {
359 case "snapshot":
360 return mergeGitStatusParts(event.local, event.remote);
361 case "localUpdated":
362 return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);
363 case "remoteUpdated":
364 if (current === null) {
365 return mergeGitStatusParts(
366 {
367 isRepo: true,
368 hasPrimaryRemote: false,
369 isDefaultRef: false,
370 refName: null,
371 hasWorkingTreeChanges: false,
372 workingTree: { files: [], insertions: 0, deletions: 0 },
373 },
374 event.remote,
375 );
376 }
377 return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
378 }
379}