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 * Best-effort parse of a GitHub `owner/repo` identifier from common remote URL shapes.
148 */
149export function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {
150 const trimmed = url?.trim() ?? "";
151 if (trimmed.length === 0) {
152 return null;
153 }
154
155 const match =
156 /^(?:git@github\.com:|ssh:\/\/git@github\.com\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(
157 trimmed,
158 );
159 const repositoryNameWithOwner = match?.[1]?.trim() ?? "";
160 return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;
161}
162
163function deriveLocalBranchNameCandidatesFromRemoteRef(
164 branchName: string,
165 remoteName?: string,
166): ReadonlyArray<string> {
167 const candidates = new Set<string>();
168 const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
169 if (firstSlashCandidate.length > 0) {
170 candidates.add(firstSlashCandidate);
171 }
172
173 if (remoteName) {
174 const remotePrefix = `${remoteName}/`;
175 if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
176 candidates.add(branchName.slice(remotePrefix.length));
177 }
178 }
179
180 return [...candidates];
181}
182
183/**
184 * Hide `origin/*` remote refs when a matching local refName already exists.
185 */
186export function dedupeRemoteBranchesWithLocalMatches(
187 refs: ReadonlyArray<VcsRef>,
188): ReadonlyArray<VcsRef> {
189 const localBranchNames = new Set(
190 Arr.filterMap(refs, (refName) =>
191 refName.isRemote ? Result.failVoid : Result.succeed(refName.name),
192 ),
193 );
194
195 return refs.filter((refName) => {
196 if (!refName.isRemote) {
197 return true;
198 }
199
200 if (refName.remoteName !== "origin") {
201 return true;
202 }
203
204 const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
205 refName.name,
206 refName.remoteName,
207 );
208 return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
209 });
210}
211
212export function detectSourceControlProviderFromGitRemoteUrl(
213 remoteUrl: string,
214): SourceControlProviderInfo | null {
215 return detectSourceControlProviderFromRemoteUrl(remoteUrl);
216}
217
218const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
219 hasUpstream: false,
220 aheadCount: 0,
221 behindCount: 0,
222 aheadOfDefaultCount: 0,
223 pr: null,
224};
225
226export function mergeGitStatusParts(
227 local: VcsStatusLocalResult,
228 remote: VcsStatusRemoteResult | null,
229): VcsStatusResult {
230 return {
231 ...local,
232 ...(remote ?? EMPTY_GIT_STATUS_REMOTE),
233 };
234}
235
236function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
237 return {
238 hasUpstream: status.hasUpstream,
239 aheadCount: status.aheadCount,
240 behindCount: status.behindCount,
241 ...(status.aheadOfDefaultCount === undefined
242 ? {}
243 : { aheadOfDefaultCount: status.aheadOfDefaultCount }),
244 pr: status.pr,
245 };
246}
247
248function toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult {
249 return {
250 isRepo: status.isRepo,
251 ...(status.sourceControlProvider
252 ? { sourceControlProvider: status.sourceControlProvider }
253 : {}),
254 hasPrimaryRemote: status.hasPrimaryRemote,
255 isDefaultRef: status.isDefaultRef,
256 refName: status.refName,
257 hasWorkingTreeChanges: status.hasWorkingTreeChanges,
258 workingTree: status.workingTree,
259 };
260}
261
262export function applyGitStatusStreamEvent(
263 current: VcsStatusResult | null,
264 event: VcsStatusStreamEvent,
265): VcsStatusResult {
266 switch (event._tag) {
267 case "snapshot":
268 return mergeGitStatusParts(event.local, event.remote);
269 case "localUpdated":
270 return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);
271 case "remoteUpdated":
272 if (current === null) {
273 return mergeGitStatusParts(
274 {
275 isRepo: true,
276 hasPrimaryRemote: false,
277 isDefaultRef: false,
278 refName: null,
279 hasWorkingTreeChanges: false,
280 workingTree: { files: [], insertions: 0, deletions: 0 },
281 },
282 event.remote,
283 );
284 }
285 return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
286 }
287}