Open History to see the last commit
1import type {
2 VcsRef,
3 SourceControlProviderInfo,
4 VcsStatusLocalResult,
5 VcsStatusRemoteResult,
6 VcsStatusResult,
7 VcsStatusStreamEvent,
8} from "@t3tools/contracts";
9import * as Arr from "effect/Array";
10import * as Result from "effect/Result";
11import { detectSourceControlProviderFromRemoteUrl } from "./sourceControl.ts";
12
13export const WORKTREE_BRANCH_PREFIX = "t3code";
14// Canonical form is `t3code/<8 hex>`. Older mobile builds generated `t3code/<uuid>`
15// via Crypto.randomUUID() (always RFC 4122 v4), so the matcher also accepts exactly
16// that shape — version nibble `4`, variant nibble `[89ab]` — to keep those threads
17// eligible for branch regeneration without loosening beyond what was ever generated.
18const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(
19 `^${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})$`,
20);
21
22/**
23 * Sanitize an arbitrary string into a valid, lowercase git refName fragment.
24 * Strips quotes, collapses separators, limits to 64 chars.
25 */
26export function sanitizeBranchFragment(raw: string): string {
27 const normalized = raw
28 .trim()
29 .toLowerCase()
30 .replace(/['"`]/g, "")
31 .replace(/^[./\s_-]+|[./\s_-]+$/g, "");
32
33 const branchFragment = normalized
34 .replace(/[^a-z0-9/_-]+/g, "-")
35 .replace(/\/+/g, "/")
36 .replace(/-+/g, "-")
37 .replace(/^[./_-]+|[./_-]+$/g, "")
38 .slice(0, 64)
39 .replace(/[./_-]+$/g, "");
40
41 return branchFragment.length > 0 ? branchFragment : "update";
42}
43
44/**
45 * Sanitize a string into a `feature/…` refName name.
46 * Preserves an existing `feature/` prefix or slash-separated namespace.
47 */
48export function sanitizeFeatureBranchName(raw: string): string {
49 const sanitized = sanitizeBranchFragment(raw);
50 if (sanitized.includes("/")) {
51 return sanitized.startsWith("feature/") ? sanitized : `feature/${sanitized}`;
52 }
53 return `feature/${sanitized}`;
54}
55
56const AUTO_FEATURE_BRANCH_FALLBACK = "feature/update";
57
58/**
59 * Resolve a unique `feature/…` refName name that doesn't collide with
60 * any existing refName. Appends a numeric suffix when needed.
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 = new Set(existingBranchNames.map((refName) => refName.toLowerCase()));
71
72 if (!existingNames.has(resolvedBase)) {
73 return resolvedBase;
74 }
75
76 let suffix = 2;
77 while (existingNames.has(`${resolvedBase}-${suffix}`)) {
78 suffix += 1;
79 }
80
81 return `${resolvedBase}-${suffix}`;
82}
83
84/**
85 * Strip the remote prefix from a remote ref such as `origin/feature/demo`.
86 */
87export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
88 const firstSeparatorIndex = branchName.indexOf("/");
89 if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
90 return branchName;
91 }
92 return branchName.slice(firstSeparatorIndex + 1);
93}
94
95export function buildTemporaryWorktreeBranchName(
96 randomHex: (byteLength: number) => string,
97): string {
98 // Normalize to exactly 8 lowercase hex chars so a UUID-shaped callback
99 // still produces the canonical temporary branch form.
100 const token = randomHex(4)
101 .toLowerCase()
102 .replace(/[^0-9a-f]/g, "")
103 .slice(0, 8);
104 return `${WORKTREE_BRANCH_PREFIX}/${token}`;
105}
106
107export function isTemporaryWorktreeBranch(refName: string): boolean {
108 return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase());
109}
110
111/**
112 * Normalize a git remote URL into a stable comparison key.
113 */
114export function normalizeGitRemoteUrl(value: string): string {
115 const normalized = value
116 .trim()
117 .replace(/\/+$/g, "")
118 .replace(/\.git$/i, "")
119 .toLowerCase();
120
121 if (/^(?:ssh|https?|git):\/\//i.test(normalized)) {
122 try {
123 const url = new URL(normalized);
124 const repositoryPath = url.pathname
125 .split("/")
126 .filter((segment) => segment.length > 0)
127 .join("/");
128 if (url.hostname && repositoryPath.includes("/")) {
129 return `${url.hostname}/${repositoryPath}`;
130 }
131 } catch {
132 return normalized;
133 }
134 }
135
136 const scpStyleHostAndPath = /^[a-zA-Z0-9._-]+@([^:/\s]+):([^/\s]+(?:\/[^/\s]+)+)$/i.exec(
137 normalized,
138 );
139 if (scpStyleHostAndPath?.[1] && scpStyleHostAndPath[2]) {
140 return `${scpStyleHostAndPath[1]}/${scpStyleHostAndPath[2]}`;
141 }
142
143 return normalized;
144}
145
146/**
147 * Unquote a git config value: strip an inline `#` or `;` comment outside
148 * quotes, then drop surrounding quotes and backslash escapes.
149 */
150function parseGitConfigValue(raw: string): string {
151 let out = "";
152 let quoted = false;
153 for (let index = 0; index < raw.length; index += 1) {
154 const char = raw[index]!;
155 if (char === "\\" && index + 1 < raw.length) {
156 out += raw[index + 1];
157 index += 1;
158 continue;
159 }
160 if (char === '"') {
161 quoted = !quoted;
162 continue;
163 }
164 if (!quoted && (char === "#" || char === ";")) break;
165 out += char;
166 }
167 return out.trim();
168}
169
170/**
171 * Read the primary remote URL from raw `.git/config` text without spawning
172 * git. Prefers `remote.origin.url` and falls back to the first remote so
173 * clones made with `git clone --origin <name>` still resolve.
174 */
175export function parseOriginUrlFromGitConfig(configText: string): string | null {
176 let section: string | null = null;
177 let originUrl: string | null = null;
178 let firstRemoteUrl: string | null = null;
179 // A trailing backslash continues the value on the next line.
180 const joined = configText.replace(/\\\r?\n[ \t]*/g, "");
181 for (const rawLine of joined.split(/\r?\n/)) {
182 const line = rawLine.trim();
183 if (line.length === 0 || line.startsWith("#") || line.startsWith(";")) continue;
184 // Both `[remote "origin"]` and the legacy `[remote.origin]` form, with an
185 // optional trailing comment. Git keeps quoted subsections case-sensitive
186 // but folds the dotted form to lowercase.
187 const header = /^\[\s*remote(?:\s+"([^"]+)"|\.([^\]\s]+))\s*\](?:\s*[#;].*)?$/i.exec(line);
188 if (header) {
189 section = header[1] ?? header[2]?.toLowerCase() ?? null;
190 continue;
191 }
192 if (line.startsWith("[")) {
193 section = null;
194 continue;
195 }
196 if (section === null) continue;
197 const match = /^url\s*=\s*(.*)$/i.exec(line);
198 if (!match) continue;
199 const url = parseGitConfigValue(match[1] ?? "");
200 if (url.length === 0) continue;
201 if (section === "origin") {
202 originUrl ??= url;
203 } else {
204 firstRemoteUrl ??= url;
205 }
206 }
207 return originUrl ?? firstRemoteUrl;
208}
209
210/**
211 * Best-effort parse of a GitHub `owner/repo` identifier from common remote URL shapes.
212 */
213export function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {
214 const trimmed = url?.trim() ?? "";
215 if (trimmed.length === 0) {
216 return null;
217 }
218
219 const match =
220 /^(?:git@github\.com:|ssh:\/\/(?:git@)?github\.com\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(
221 trimmed,
222 );
223 const repositoryNameWithOwner = match?.[1]?.trim() ?? "";
224 return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;
225}
226
227function deriveLocalBranchNameCandidatesFromRemoteRef(
228 branchName: string,
229 remoteName?: string,
230): ReadonlyArray<string> {
231 const candidates = new Set<string>();
232 const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
233 if (firstSlashCandidate.length > 0) {
234 candidates.add(firstSlashCandidate);
235 }
236
237 if (remoteName) {
238 const remotePrefix = `${remoteName}/`;
239 if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
240 candidates.add(branchName.slice(remotePrefix.length));
241 }
242 }
243
244 return [...candidates];
245}
246
247/**
248 * Hide `origin/*` remote refs when a matching local refName already exists.
249 */
250export function dedupeRemoteBranchesWithLocalMatches(
251 refs: ReadonlyArray<VcsRef>,
252): ReadonlyArray<VcsRef> {
253 const localBranchNames = new Set(
254 Arr.filterMap(refs, (refName) =>
255 refName.isRemote ? Result.failVoid : Result.succeed(refName.name),
256 ),
257 );
258
259 return refs.filter((refName) => {
260 if (!refName.isRemote) {
261 return true;
262 }
263
264 if (refName.remoteName !== "origin") {
265 return true;
266 }
267
268 const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
269 refName.name,
270 refName.remoteName,
271 );
272 return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
273 });
274}
275
276export function detectSourceControlProviderFromGitRemoteUrl(
277 remoteUrl: string,
278): SourceControlProviderInfo | null {
279 return detectSourceControlProviderFromRemoteUrl(remoteUrl);
280}
281
282const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
283 hasUpstream: false,
284 aheadCount: 0,
285 behindCount: 0,
286 aheadOfDefaultCount: 0,
287 pr: null,
288};
289
290export function mergeGitStatusParts(
291 local: VcsStatusLocalResult,
292 remote: VcsStatusRemoteResult | null,
293): VcsStatusResult {
294 return {
295 ...local,
296 ...(remote ?? EMPTY_GIT_STATUS_REMOTE),
297 };
298}
299
300function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
301 return {
302 hasUpstream: status.hasUpstream,
303 aheadCount: status.aheadCount,
304 behindCount: status.behindCount,
305 ...(status.aheadOfDefaultCount === undefined
306 ? {}
307 : { aheadOfDefaultCount: status.aheadOfDefaultCount }),
308 pr: status.pr,
309 };
310}
311
312function toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult {
313 return {
314 isRepo: status.isRepo,
315 ...(status.sourceControlProvider
316 ? { sourceControlProvider: status.sourceControlProvider }
317 : {}),
318 hasPrimaryRemote: status.hasPrimaryRemote,
319 isDefaultRef: status.isDefaultRef,
320 refName: status.refName,
321 hasWorkingTreeChanges: status.hasWorkingTreeChanges,
322 workingTree: status.workingTree,
323 };
324}
325
326export function applyGitStatusStreamEvent(
327 current: VcsStatusResult | null,
328 event: VcsStatusStreamEvent,
329): VcsStatusResult {
330 switch (event._tag) {
331 case "snapshot":
332 return mergeGitStatusParts(event.local, event.remote);
333 case "localUpdated":
334 return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);
335 case "remoteUpdated":
336 if (current === null) {
337 return mergeGitStatusParts(
338 {
339 isRepo: true,
340 hasPrimaryRemote: false,
341 isDefaultRef: false,
342 refName: null,
343 hasWorkingTreeChanges: false,
344 workingTree: { files: [], insertions: 0, deletions: 0 },
345 },
346 event.remote,
347 );
348 }
349 return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
350 }
351}