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 .normalize("NFKD")
23 .replace(/[̀-ͯ]/g, "")
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/** Flatten temporary t3/<hex> refs because an existing t3 branch blocks nested refs. */
114export function flattenTemporaryWorktreeBranchName(refName: string): string {
115 const normalized = refName.trim().toLowerCase();
116 const tokenStart = normalized.search(/[-/]/) + 1;
117 const token = normalized.slice(tokenStart, tokenStart + 8);
118 return `${WORKTREE_BRANCH_PREFIX}-${token}`;
119}
120
121export function isTemporaryWorktreeBranch(refName: string): boolean {
122 return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase());
123}
124
125function lowerCaseRemote(value: string): string {
126 return value
127 .trim()
128 .replace(/\/+$/g, "")
129 .replace(/\.git$/i, "")
130 .toLowerCase();
131}
132
133/**
134 * The host and repository path a remote names, lower case and without a port, or null for a
135 * remote that names no host, such as a local path.
136 */
137export function parseGitRemoteRepository(
138 value: string,
139): { readonly host: string; readonly path: string } | null {
140 const normalized = lowerCaseRemote(value);
141
142 if (/^(?:ssh|https?|git):\/\//i.test(normalized)) {
143 try {
144 const url = new URL(normalized);
145 const repositorySegments = url.pathname.split("/").filter((segment) => segment.length > 0);
146 if (url.hostname && repositorySegments.length > 1) {
147 return { host: url.hostname, path: repositorySegments.join("/") };
148 }
149 } catch {
150 return null;
151 }
152 }
153
154 // A userless one-letter prefix is a Windows drive, not an SCP host.
155 const scpStyleHostAndPath = /^[a-z]:/i.test(normalized)
156 ? null
157 : /^(?:[a-zA-Z0-9._-]+@)?([^@:/\\\s]+):\/?([^/\s]+(?:\/[^/\s]+)+)$/i.exec(normalized);
158 const scpHost = scpStyleHostAndPath?.[1];
159 const scpPath = scpStyleHostAndPath?.[2];
160 return scpHost && scpPath ? { host: scpHost, path: scpPath } : null;
161}
162
163/**
164 * `host/path` for a remote that names a host, otherwise the remote itself, lower case. A host that
165 * spells repositories differently over SSH has its source control registry's
166 * `repositoryKeyFromRemote` rewrite this, so persisted keys come from that, not from here.
167 */
168export function normalizeGitRemoteUrl(value: string): string {
169 const repository = parseGitRemoteRepository(value);
170 return repository === null ? lowerCaseRemote(value) : `${repository.host}/${repository.path}`;
171}
172
173function parseGitConfigValue(raw: string): string {
174 let out = "";
175 let quoted = false;
176 for (let index = 0; index < raw.length; index += 1) {
177 const char = raw[index]!;
178 if (char === "\\" && index + 1 < raw.length) {
179 out += raw[index + 1];
180 index += 1;
181 continue;
182 }
183 if (char === '"') {
184 quoted = !quoted;
185 continue;
186 }
187 if (!quoted && (char === "#" || char === ";")) break;
188 out += char;
189 }
190 return out.trim();
191}
192
193export function isBareGitConfig(configText: string): boolean {
194 let inCore = false;
195 let bare = false;
196 for (const rawLine of configText.split(/\r?\n/)) {
197 let line = rawLine.trim();
198 // Git accepts the first setting on the section header's own line.
199 const header = /^\[\s*([^\]]*?)\s*\](.*)$/.exec(line);
200 if (header !== null) {
201 inCore = header[1]!.toLowerCase() === "core";
202 line = header[2]!.trim();
203 }
204 if (!inCore) continue;
205 const match = /^bare\s*(?:=(.*)|[#;].*)?$/i.exec(line);
206 if (match === null) continue;
207 const value = match[1] === undefined ? "true" : parseGitConfigValue(match[1]).toLowerCase();
208 bare = value === "true" || value === "yes" || value === "on" || value === "1";
209 }
210 return bare;
211}
212
213export function parseOriginUrlFromGitConfig(configText: string): string | null {
214 let section: string | null = null;
215 let originUrl: string | null = null;
216 let firstRemoteUrl: string | null = null;
217 const joined = configText.replace(/\\\r?\n[ \t]*/g, "");
218 for (const rawLine of joined.split(/\r?\n/)) {
219 let line = rawLine.trim();
220 if (line.length === 0 || line.startsWith("#") || line.startsWith(";")) continue;
221 // Git preserves case in quoted remote subsections but lowercases legacy dotted ones,
222 // and accepts the first setting on the section header's own line.
223 const header = /^\[\s*remote(?:\s+"([^"]+)"|\.([^\]\s]+))\s*\](.*)$/i.exec(line);
224 if (header) {
225 section = header[1] ?? header[2]?.toLowerCase() ?? null;
226 line = header[3]!.trim();
227 } else if (line.startsWith("[")) {
228 section = null;
229 continue;
230 }
231 if (section === null) continue;
232 const match = /^url\s*=\s*(.*)$/i.exec(line);
233 if (!match) continue;
234 const url = parseGitConfigValue(match[1] ?? "");
235 if (url.length === 0) continue;
236 if (section === "origin") {
237 originUrl ??= url;
238 } else {
239 firstRemoteUrl ??= url;
240 }
241 }
242 return originUrl ?? firstRemoteUrl;
243}
244
245function deriveLocalBranchNameCandidatesFromRemoteRef(
246 branchName: string,
247 remoteName?: string,
248): ReadonlyArray<string> {
249 const candidates = new Set<string>();
250 const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
251 if (firstSlashCandidate.length > 0) {
252 candidates.add(firstSlashCandidate);
253 }
254
255 if (remoteName) {
256 const remotePrefix = `${remoteName}/`;
257 if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
258 candidates.add(branchName.slice(remotePrefix.length));
259 }
260 }
261
262 return [...candidates];
263}
264
265// Replace only Git-rejected whitespace; nonbreaking spaces are valid ref characters.
266export function sanitizeNewRefName(rawName: string): string {
267 return rawName.trim().replace(/[ \t\n\r\f\v]+/g, "-");
268}
269
270export function dedupeRemoteBranchesWithLocalMatches(
271 refs: ReadonlyArray<VcsRef>,
272): ReadonlyArray<VcsRef> {
273 const localBranchNames = new Set(
274 Arr.filterMap(refs, (refName) =>
275 refName.isRemote ? Result.failVoid : Result.succeed(refName.name),
276 ),
277 );
278
279 return refs.filter((refName) => {
280 if (!refName.isRemote) {
281 return true;
282 }
283
284 if (refName.remoteName !== "origin") {
285 return true;
286 }
287
288 const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
289 refName.name,
290 refName.remoteName,
291 );
292 return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
293 });
294}
295
296const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
297 hasUpstream: false,
298 aheadCount: 0,
299 behindCount: 0,
300 aheadOfDefaultCount: 0,
301 pr: null,
302};
303
304export function mergeGitStatusParts(
305 local: VcsStatusLocalResult,
306 remote: VcsStatusRemoteResult | null,
307): VcsStatusResult {
308 return {
309 ...local,
310 ...(remote ?? EMPTY_GIT_STATUS_REMOTE),
311 };
312}
313
314function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
315 return {
316 hasUpstream: status.hasUpstream,
317 aheadCount: status.aheadCount,
318 behindCount: status.behindCount,
319 ...(status.aheadOfDefaultCount === undefined
320 ? {}
321 : { aheadOfDefaultCount: status.aheadOfDefaultCount }),
322 pr: status.pr,
323 };
324}
325
326function toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult {
327 return {
328 isRepo: status.isRepo,
329 ...(status.sourceControlProvider
330 ? { sourceControlProvider: status.sourceControlProvider }
331 : {}),
332 hasPrimaryRemote: status.hasPrimaryRemote,
333 isDefaultRef: status.isDefaultRef,
334 refName: status.refName,
335 hasWorkingTreeChanges: status.hasWorkingTreeChanges,
336 workingTree: status.workingTree,
337 ...(status.branchChanges ? { branchChanges: status.branchChanges } : {}),
338 };
339}
340
341export function applyGitStatusStreamEvent(
342 current: VcsStatusResult | null,
343 event: VcsStatusStreamEvent,
344): VcsStatusResult {
345 switch (event._tag) {
346 case "snapshot":
347 return mergeGitStatusParts(event.local, event.remote);
348 case "localUpdated":
349 return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);
350 case "remoteUpdated":
351 if (current === null) {
352 return mergeGitStatusParts(
353 {
354 isRepo: true,
355 hasPrimaryRemote: false,
356 isDefaultRef: false,
357 refName: null,
358 hasWorkingTreeChanges: false,
359 workingTree: { files: [], insertions: 0, deletions: 0 },
360 },
361 event.remote,
362 );
363 }
364 return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
365 }
366}