Open History to see the last commit
1import type {
2 VcsRef,
3 SourceControlProviderInfo,
4 VcsStatusLocalResult,
5 VcsStatusRemoteResult,
6 VcsStatusResult,
7 VcsStatusStreamEvent,
8} from "@v12/contracts";
9import * as Arr from "effect/Array";
10import * as Result from "effect/Result";
11import { detectSourceControlProviderFromRemoteUrl } from "./sourceControl.ts";
12
13export const WORKTREE_BRANCH_PREFIX = "v12";
14const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
15
16/**
17 * Sanitize an arbitrary string into a valid, lowercase git refName fragment.
18 * Strips quotes, collapses separators, limits to 64 chars.
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
38/**
39 * Sanitize a string into a `feature/…` refName name.
40 * Preserves an existing `feature/` prefix or slash-separated namespace.
41 */
42export function sanitizeFeatureBranchName(raw: string): string {
43 const sanitized = sanitizeBranchFragment(raw);
44 if (sanitized.includes("/")) {
45 return sanitized.startsWith("feature/") ? sanitized : `feature/${sanitized}`;
46 }
47 return `feature/${sanitized}`;
48}
49
50const AUTO_FEATURE_BRANCH_FALLBACK = "feature/update";
51
52/**
53 * Resolve a unique `feature/…` refName name that doesn't collide with
54 * any existing refName. Appends a numeric suffix when needed.
55 */
56export function resolveAutoFeatureBranchName(
57 existingBranchNames: readonly string[],
58 preferredBranch?: string,
59): string {
60 const preferred = preferredBranch?.trim();
61 const resolvedBase = sanitizeFeatureBranchName(
62 preferred && preferred.length > 0 ? preferred : AUTO_FEATURE_BRANCH_FALLBACK,
63 );
64 const existingNames = new Set(existingBranchNames.map((refName) => refName.toLowerCase()));
65
66 if (!existingNames.has(resolvedBase)) {
67 return resolvedBase;
68 }
69
70 let suffix = 2;
71 while (existingNames.has(`${resolvedBase}-${suffix}`)) {
72 suffix += 1;
73 }
74
75 return `${resolvedBase}-${suffix}`;
76}
77
78/**
79 * Strip the remote prefix from a remote ref such as `origin/feature/demo`.
80 */
81export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
82 const firstSeparatorIndex = branchName.indexOf("/");
83 if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
84 return branchName;
85 }
86 return branchName.slice(firstSeparatorIndex + 1);
87}
88
89export function buildTemporaryWorktreeBranchName(
90 randomHex: (byteLength: number) => string,
91): string {
92 const token = randomHex(4).toLowerCase();
93 return `${WORKTREE_BRANCH_PREFIX}/${token}`;
94}
95
96export function isTemporaryWorktreeBranch(refName: string): boolean {
97 return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase());
98}
99
100/**
101 * Normalize a git remote URL into a stable comparison key.
102 */
103export function normalizeGitRemoteUrl(value: string): string {
104 const normalized = value
105 .trim()
106 .replace(/\/+$/g, "")
107 .replace(/\.git$/i, "")
108 .toLowerCase();
109
110 if (/^(?:ssh|https?|git):\/\//i.test(normalized)) {
111 try {
112 const url = new URL(normalized);
113 const repositoryPath = url.pathname
114 .split("/")
115 .filter((segment) => segment.length > 0)
116 .join("/");
117 if (url.hostname && repositoryPath.includes("/")) {
118 return `${url.hostname}/${repositoryPath}`;
119 }
120 } catch {
121 return normalized;
122 }
123 }
124
125 const scpStyleHostAndPath = /^git@([^:/\s]+)[:/]([^/\s]+(?:\/[^/\s]+)+)$/i.exec(normalized);
126 if (scpStyleHostAndPath?.[1] && scpStyleHostAndPath[2]) {
127 return `${scpStyleHostAndPath[1]}/${scpStyleHostAndPath[2]}`;
128 }
129
130 return normalized;
131}
132
133/**
134 * Best-effort parse of a GitHub `owner/repo` identifier from common remote URL shapes.
135 */
136export function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {
137 const trimmed = url?.trim() ?? "";
138 if (trimmed.length === 0) {
139 return null;
140 }
141
142 const match =
143 /^(?:git@github\.com:|ssh:\/\/git@github\.com\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(
144 trimmed,
145 );
146 const repositoryNameWithOwner = match?.[1]?.trim() ?? "";
147 return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;
148}
149
150function deriveLocalBranchNameCandidatesFromRemoteRef(
151 branchName: string,
152 remoteName?: string,
153): ReadonlyArray<string> {
154 const candidates = new Set<string>();
155 const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
156 if (firstSlashCandidate.length > 0) {
157 candidates.add(firstSlashCandidate);
158 }
159
160 if (remoteName) {
161 const remotePrefix = `${remoteName}/`;
162 if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
163 candidates.add(branchName.slice(remotePrefix.length));
164 }
165 }
166
167 return [...candidates];
168}
169
170/**
171 * Hide `origin/*` remote refs when a matching local refName already exists.
172 */
173export function dedupeRemoteBranchesWithLocalMatches(
174 refs: ReadonlyArray<VcsRef>,
175): ReadonlyArray<VcsRef> {
176 const localBranchNames = new Set(
177 Arr.filterMap(refs, (refName) =>
178 refName.isRemote ? Result.failVoid : Result.succeed(refName.name),
179 ),
180 );
181
182 return refs.filter((refName) => {
183 if (!refName.isRemote) {
184 return true;
185 }
186
187 if (refName.remoteName !== "origin") {
188 return true;
189 }
190
191 const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
192 refName.name,
193 refName.remoteName,
194 );
195 return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
196 });
197}
198
199export function detectSourceControlProviderFromGitRemoteUrl(
200 remoteUrl: string,
201): SourceControlProviderInfo | null {
202 return detectSourceControlProviderFromRemoteUrl(remoteUrl);
203}
204
205const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
206 hasUpstream: false,
207 aheadCount: 0,
208 behindCount: 0,
209 aheadOfDefaultCount: 0,
210 pr: null,
211};
212
213export function mergeGitStatusParts(
214 local: VcsStatusLocalResult,
215 remote: VcsStatusRemoteResult | null,
216): VcsStatusResult {
217 return {
218 ...local,
219 ...(remote ?? EMPTY_GIT_STATUS_REMOTE),
220 };
221}
222
223function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
224 return {
225 hasUpstream: status.hasUpstream,
226 aheadCount: status.aheadCount,
227 behindCount: status.behindCount,
228 ...(status.aheadOfDefaultCount === undefined
229 ? {}
230 : { aheadOfDefaultCount: status.aheadOfDefaultCount }),
231 pr: status.pr,
232 };
233}
234
235function toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult {
236 return {
237 isRepo: status.isRepo,
238 ...(status.sourceControlProvider
239 ? { sourceControlProvider: status.sourceControlProvider }
240 : {}),
241 hasPrimaryRemote: status.hasPrimaryRemote,
242 isDefaultRef: status.isDefaultRef,
243 refName: status.refName,
244 hasWorkingTreeChanges: status.hasWorkingTreeChanges,
245 workingTree: status.workingTree,
246 };
247}
248
249export function applyGitStatusStreamEvent(
250 current: VcsStatusResult | null,
251 event: VcsStatusStreamEvent,
252): VcsStatusResult {
253 switch (event._tag) {
254 case "snapshot":
255 return mergeGitStatusParts(event.local, event.remote);
256 case "localUpdated":
257 return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);
258 case "remoteUpdated":
259 if (current === null) {
260 return mergeGitStatusParts(
261 {
262 isRepo: true,
263 hasPrimaryRemote: false,
264 isDefaultRef: false,
265 refName: null,
266 hasWorkingTreeChanges: false,
267 workingTree: { files: [], insertions: 0, deletions: 0 },
268 },
269 event.remote,
270 );
271 }
272 return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
273 }
274}