Open History to see the last commit
1import type {
2 BranchNamingOptions,
3 VcsRef,
4 VcsStatusLocalResult,
5 VcsStatusRemoteResult,
6 VcsStatusResult,
7 VcsStatusStreamEvent,
8} from "@t3tools/contracts";
9import * as Arr from "effect/Array";
10import * as Result from "effect/Result";
11
12export const WORKTREE_BRANCH_PREFIX = "t3";
13const TEMP_WORKTREE_HEX_TOKEN = "[0-9a-f]{8}";
14const TEMP_WORKTREE_UUID_V4_TOKEN =
15 "[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}";
16const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(
17 `^(?:${WORKTREE_BRANCH_PREFIX}[-/]${TEMP_WORKTREE_HEX_TOKEN}|t3code(?:[-/]${TEMP_WORKTREE_HEX_TOKEN}|\\/${TEMP_WORKTREE_UUID_V4_TOKEN}))$`,
18);
19
20export function sanitizeBranchFragment(raw: string): string {
21 const normalized = raw
22 .trim()
23 .toLowerCase()
24 .replace(/['"`]/g, "")
25 .replace(/^[./\s_-]+|[./\s_-]+$/g, "");
26
27 const branchFragment = normalized
28 .replace(/[^a-z0-9/_-]+/g, "-")
29 .replace(/\/+/g, "/")
30 .replace(/-+/g, "-")
31 .replace(/^[./_-]+|[./_-]+$/g, "")
32 .slice(0, 64)
33 .replace(/[./_-]+$/g, "");
34
35 return branchFragment.length > 0 ? branchFragment : "update";
36}
37
38export function formatGeneratedBranchName(raw: string, naming?: BranchNamingOptions): string {
39 if (naming?.mode === "custom") return raw.trim();
40 const branch = sanitizeBranchFragment(raw);
41 if (naming?.mode !== "static") return branch;
42 const prefix = naming.prefix
43 .split("/")
44 .map((part) =>
45 part
46 .replace(/[^a-zA-Z0-9_-]+/g, "-")
47 .replace(/-+/g, "-")
48 .replace(/^-+|-+$/g, ""),
49 )
50 .filter(Boolean)
51 .join("/");
52 return prefix ? `${prefix}/${branch}` : branch;
53}
54
55export function sanitizeFeatureBranchName(raw: string): string {
56 const sanitized = sanitizeBranchFragment(raw);
57 return sanitized.includes("/") ? sanitized : `feature/${sanitized}`;
58}
59
60const AUTO_FEATURE_BRANCH_FALLBACK = "feature/update";
61
62export function resolveAutoFeatureBranchName(
63 existingBranchNames: readonly string[],
64 preferredBranch?: string,
65): string {
66 const preferred = preferredBranch?.trim();
67 const resolvedBase = sanitizeFeatureBranchName(
68 preferred && preferred.length > 0 ? preferred : AUTO_FEATURE_BRANCH_FALLBACK,
69 );
70 const existingNames = existingBranchNames.map((refName) => refName.toLowerCase());
71 const existingRefs = new Set(existingNames);
72 const parts = resolvedBase.split("/");
73 let resolved = "";
74
75 for (const [index, part] of parts.entries()) {
76 const base = resolved ? `${resolved}/${part}` : part;
77 let candidate = base;
78 let suffix = 2;
79 while (
80 existingRefs.has(candidate) ||
81 (index === parts.length - 1 &&
82 existingNames.some((refName) => refName.startsWith(`${candidate}/`)))
83 ) {
84 candidate = `${base}-${suffix}`;
85 suffix += 1;
86 }
87 resolved = candidate;
88 }
89
90 return resolved;
91}
92
93export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
94 const firstSeparatorIndex = branchName.indexOf("/");
95 if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
96 return branchName;
97 }
98 return branchName.slice(firstSeparatorIndex + 1);
99}
100
101export function buildTemporaryWorktreeBranchName(
102 randomHex: (byteLength: number) => string,
103): string {
104 const token = randomHex(4)
105 .toLowerCase()
106 .replace(/[^0-9a-f]/g, "")
107 .slice(0, 8);
108 return `${WORKTREE_BRANCH_PREFIX}/${token}`;
109}
110
111/**
112 * Git stores refs as paths, so a plain `t3` branch makes every `t3/<hex>`
113 * ref impossible. This moves a temporary name to the flat `t3-<hex>` sibling.
114 */
115export function flattenTemporaryWorktreeBranchName(refName: string): string {
116 const normalized = refName.trim().toLowerCase();
117 const tokenStart = normalized.search(/[-/]/) + 1;
118 const token = normalized.slice(tokenStart, tokenStart + 8);
119 return `${WORKTREE_BRANCH_PREFIX}-${token}`;
120}
121
122export function isTemporaryWorktreeBranch(refName: string): boolean {
123 return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase());
124}
125
126function lowerCaseRemote(value: string): string {
127 return value
128 .trim()
129 .replace(/\/+$/g, "")
130 .replace(/\.git$/i, "")
131 .toLowerCase();
132}
133
134/**
135 * The host and repository path a remote names, lower case and without a port, or null for a
136 * remote that names no host, such as a local path.
137 */
138export function parseGitRemoteRepository(
139 value: string,
140): { readonly host: string; readonly path: string } | null {
141 const normalized = lowerCaseRemote(value);
142
143 if (/^(?:ssh|https?|git):\/\//i.test(normalized)) {
144 try {
145 const url = new URL(normalized);
146 const repositorySegments = url.pathname.split("/").filter((segment) => segment.length > 0);
147 if (url.hostname && repositorySegments.length > 1) {
148 return { host: url.hostname, path: repositorySegments.join("/") };
149 }
150 } catch {
151 return null;
152 }
153 }
154
155 // A userless one-letter prefix is a Windows drive, not an SCP host.
156 const scpStyleHostAndPath = /^[a-z]:/i.test(normalized)
157 ? null
158 : /^(?:[a-zA-Z0-9._-]+@)?([^@:/\\\s]+):\/?([^/\s]+(?:\/[^/\s]+)+)$/i.exec(normalized);
159 const scpHost = scpStyleHostAndPath?.[1];
160 const scpPath = scpStyleHostAndPath?.[2];
161 return scpHost && scpPath ? { host: scpHost, path: scpPath } : null;
162}
163
164/**
165 * `host/path` for a remote that names a host, otherwise the remote itself, lower case. A host that
166 * spells repositories differently over SSH has its source control registry's
167 * `repositoryKeyFromRemote` rewrite this, so persisted keys come from that, not from here.
168 */
169export function normalizeGitRemoteUrl(value: string): string {
170 const repository = parseGitRemoteRepository(value);
171 return repository === null ? lowerCaseRemote(value) : `${repository.host}/${repository.path}`;
172}
173
174function parseGitConfigValue(raw: string): string {
175 let out = "";
176 let quoted = false;
177 for (let index = 0; index < raw.length; index += 1) {
178 const char = raw[index]!;
179 if (char === "\\" && index + 1 < raw.length) {
180 out += raw[index + 1];
181 index += 1;
182 continue;
183 }
184 if (char === '"') {
185 quoted = !quoted;
186 continue;
187 }
188 if (!quoted && (char === "#" || char === ";")) break;
189 out += char;
190 }
191 return out.trim();
192}
193
194export function isBareGitConfig(configText: string): boolean {
195 let inCore = false;
196 let bare = false;
197 for (const rawLine of configText.split(/\r?\n/)) {
198 let line = rawLine.trim();
199 // Git accepts the first setting on the section header's own line.
200 const header = /^\[\s*([^\]]*?)\s*\](.*)$/.exec(line);
201 if (header !== null) {
202 inCore = header[1]!.toLowerCase() === "core";
203 line = header[2]!.trim();
204 }
205 if (!inCore) continue;
206 const match = /^bare\s*(?:=(.*)|[#;].*)?$/i.exec(line);
207 if (match === null) continue;
208 const value = match[1] === undefined ? "true" : parseGitConfigValue(match[1]).toLowerCase();
209 bare = value === "true" || value === "yes" || value === "on" || value === "1";
210 }
211 return bare;
212}
213
214export function parseOriginUrlFromGitConfig(configText: string): string | null {
215 let section: string | null = null;
216 let originUrl: string | null = null;
217 let firstRemoteUrl: string | null = null;
218 // A trailing backslash continues the value on the next line.
219 const joined = configText.replace(/\\\r?\n[ \t]*/g, "");
220 for (const rawLine of joined.split(/\r?\n/)) {
221 const line = rawLine.trim();
222 if (line.length === 0 || line.startsWith("#") || line.startsWith(";")) continue;
223 // Both `[remote "origin"]` and the legacy `[remote.origin]` form, with an
224 // optional trailing comment. Git keeps quoted subsections case-sensitive
225 // but folds the dotted form to lowercase.
226 const header = /^\[\s*remote(?:\s+"([^"]+)"|\.([^\]\s]+))\s*\](?:\s*[#;].*)?$/i.exec(line);
227 if (header) {
228 section = header[1] ?? header[2]?.toLowerCase() ?? null;
229 continue;
230 }
231 if (line.startsWith("[")) {
232 section = null;
233 continue;
234 }
235 if (section === null) continue;
236 const match = /^url\s*=\s*(.*)$/i.exec(line);
237 if (!match) continue;
238 const url = parseGitConfigValue(match[1] ?? "");
239 if (url.length === 0) continue;
240 if (section === "origin") {
241 originUrl ??= url;
242 } else {
243 firstRemoteUrl ??= url;
244 }
245 }
246 return originUrl ?? firstRemoteUrl;
247}
248
249function deriveLocalBranchNameCandidatesFromRemoteRef(
250 branchName: string,
251 remoteName?: string,
252): ReadonlyArray<string> {
253 const candidates = new Set<string>();
254 const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
255 if (firstSlashCandidate.length > 0) {
256 candidates.add(firstSlashCandidate);
257 }
258
259 if (remoteName) {
260 const remotePrefix = `${remoteName}/`;
261 if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
262 candidates.add(branchName.slice(remotePrefix.length));
263 }
264 }
265
266 return [...candidates];
267}
268
269// Only the whitespace git actually rejects is replaced — git accepts U+00A0 and
270// friends, and rewriting those would silently create a ref the user never asked
271// for.
272export function sanitizeNewRefName(rawName: string): string {
273 return rawName.trim().replace(/[ \t\n\r\f\v]+/g, "-");
274}
275
276export function dedupeRemoteBranchesWithLocalMatches(
277 refs: ReadonlyArray<VcsRef>,
278): ReadonlyArray<VcsRef> {
279 const localBranchNames = new Set(
280 Arr.filterMap(refs, (refName) =>
281 refName.isRemote ? Result.failVoid : Result.succeed(refName.name),
282 ),
283 );
284
285 return refs.filter((refName) => {
286 if (!refName.isRemote) {
287 return true;
288 }
289
290 if (refName.remoteName !== "origin") {
291 return true;
292 }
293
294 const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
295 refName.name,
296 refName.remoteName,
297 );
298 return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
299 });
300}
301
302const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
303 hasUpstream: false,
304 aheadCount: 0,
305 behindCount: 0,
306 aheadOfDefaultCount: 0,
307 pr: null,
308};
309
310export function mergeGitStatusParts(
311 local: VcsStatusLocalResult,
312 remote: VcsStatusRemoteResult | null,
313): VcsStatusResult {
314 return {
315 ...local,
316 ...(remote ?? EMPTY_GIT_STATUS_REMOTE),
317 };
318}
319
320function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
321 return {
322 hasUpstream: status.hasUpstream,
323 aheadCount: status.aheadCount,
324 behindCount: status.behindCount,
325 ...(status.aheadOfDefaultCount === undefined
326 ? {}
327 : { aheadOfDefaultCount: status.aheadOfDefaultCount }),
328 pr: status.pr,
329 };
330}
331
332function toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult {
333 return {
334 isRepo: status.isRepo,
335 ...(status.sourceControlProvider
336 ? { sourceControlProvider: status.sourceControlProvider }
337 : {}),
338 hasPrimaryRemote: status.hasPrimaryRemote,
339 isDefaultRef: status.isDefaultRef,
340 refName: status.refName,
341 hasWorkingTreeChanges: status.hasWorkingTreeChanges,
342 workingTree: status.workingTree,
343 ...(status.branchChanges ? { branchChanges: status.branchChanges } : {}),
344 };
345}
346
347export function applyGitStatusStreamEvent(
348 current: VcsStatusResult | null,
349 event: VcsStatusStreamEvent,
350): VcsStatusResult {
351 switch (event._tag) {
352 case "snapshot":
353 return mergeGitStatusParts(event.local, event.remote);
354 case "localUpdated":
355 return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);
356 case "remoteUpdated":
357 if (current === null) {
358 return mergeGitStatusParts(
359 {
360 isRepo: true,
361 hasPrimaryRemote: false,
362 isDefaultRef: false,
363 refName: null,
364 hasWorkingTreeChanges: false,
365 workingTree: { files: [], insertions: 0, deletions: 0 },
366 },
367 event.remote,
368 );
369 }
370 return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
371 }
372}