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