Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

git.ts

372 lines11.8 KB

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";
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}`;
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}`;
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);
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}`;
106​
107export function isTemporaryWorktreeBranch(refName: string): boolean {
108 return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase());
110​
111/**
112 * The web spelling of an Azure DevOps repository reached over SSH, or null for anything else.
113 *
114 * Azure alone addresses one repository under two names that share no part: `ssh.dev.azure.com` and
115 * `v3/{org}/{project}/{repo}` over SSH, against `dev.azure.com` and `{org}/{project}/_git/{repo}`
116 * everywhere a person sees it. A project cloned over SSH would otherwise be a different repository
117 * to every comparison made against a pull request URL, which arrives in the web spelling. So the
118 * web spelling is the one both are keyed by.
119 */
120function azureDevOpsRepositoryKey(host: string, segments: ReadonlyArray<string>): string | null {
121 if (host !== "ssh.dev.azure.com" && host !== "vs-ssh.visualstudio.com") return null;
122 const [marker, organization, project, repository] = segments;
123 if (segments.length !== 4 || marker !== "v3") return null;
124 if (!organization || !project || !repository) return null;
125 return host === "ssh.dev.azure.com"
126 ? `dev.azure.com/${organization}/${project}/_git/${repository}`
127 : `${organization}.visualstudio.com/${project}/_git/${repository}`;
129​
130/**
131 * Normalize a git remote URL into a stable comparison key.
132 */
133export function normalizeGitRemoteUrl(value: string): string {
134 const normalized = value
135 .trim()
136 .replace(/\/+$/g, "")
137 .replace(/\.git$/i, "")
138 .toLowerCase();
139​
140 if (/^(?:ssh|https?|git):\/\//i.test(normalized)) {
141 try {
142 const url = new URL(normalized);
143 const repositorySegments = url.pathname.split("/").filter((segment) => segment.length > 0);
144 if (url.hostname && repositorySegments.length > 1) {
145 return (
146 azureDevOpsRepositoryKey(url.hostname, repositorySegments) ??
147 `${url.hostname}/${repositorySegments.join("/")}`
148 );
149 }
150 } catch {
151 return normalized;
152 }
153 }
154​
155 const scpStyleHostAndPath = /^[a-zA-Z0-9._-]+@([^:/\s]+):([^/\s]+(?:\/[^/\s]+)+)$/i.exec(
156 normalized,
157 );
158 const scpHost = scpStyleHostAndPath?.[1];
159 const scpPath = scpStyleHostAndPath?.[2];
160 if (scpHost && scpPath) {
161 return azureDevOpsRepositoryKey(scpHost, scpPath.split("/")) ?? `${scpHost}/${scpPath}`;
162 }
163​
164 return normalized;
166​
167/**
168 * Unquote a git config value: strip an inline `#` or `;` comment outside
169 * quotes, then drop surrounding quotes and backslash escapes.
170 */
171function parseGitConfigValue(raw: string): string {
172 let out = "";
173 let quoted = false;
174 for (let index = 0; index < raw.length; index += 1) {
175 const char = raw[index]!;
176 if (char === "\\" && index + 1 < raw.length) {
177 out += raw[index + 1];
178 index += 1;
179 continue;
180 }
181 if (char === '"') {
182 quoted = !quoted;
183 continue;
184 }
185 if (!quoted && (char === "#" || char === ";")) break;
186 out += char;
187 }
188 return out.trim();
190​
191/**
192 * Read the primary remote URL from raw `.git/config` text without spawning
193 * git. Prefers `remote.origin.url` and falls back to the first remote so
194 * clones made with `git clone --origin <name>` still resolve.
195 */
196export function parseOriginUrlFromGitConfig(configText: string): string | null {
197 let section: string | null = null;
198 let originUrl: string | null = null;
199 let firstRemoteUrl: string | null = null;
200 // A trailing backslash continues the value on the next line.
201 const joined = configText.replace(/\\\r?\n[ \t]*/g, "");
202 for (const rawLine of joined.split(/\r?\n/)) {
203 const line = rawLine.trim();
204 if (line.length === 0 || line.startsWith("#") || line.startsWith(";")) continue;
205 // Both `[remote "origin"]` and the legacy `[remote.origin]` form, with an
206 // optional trailing comment. Git keeps quoted subsections case-sensitive
207 // but folds the dotted form to lowercase.
208 const header = /^\[\s*remote(?:\s+"([^"]+)"|\.([^\]\s]+))\s*\](?:\s*[#;].*)?$/i.exec(line);
209 if (header) {
210 section = header[1] ?? header[2]?.toLowerCase() ?? null;
211 continue;
212 }
213 if (line.startsWith("[")) {
214 section = null;
215 continue;
216 }
217 if (section === null) continue;
218 const match = /^url\s*=\s*(.*)$/i.exec(line);
219 if (!match) continue;
220 const url = parseGitConfigValue(match[1] ?? "");
221 if (url.length === 0) continue;
222 if (section === "origin") {
223 originUrl ??= url;
224 } else {
225 firstRemoteUrl ??= url;
226 }
227 }
228 return originUrl ?? firstRemoteUrl;
230​
231/**
232 * Best-effort parse of a GitHub `owner/repo` identifier from common remote URL shapes.
233 */
234export function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {
235 const trimmed = url?.trim() ?? "";
236 if (trimmed.length === 0) {
237 return null;
238 }
239​
240 const match =
241 /^(?:git@github\.com:|ssh:\/\/(?:git@)?github\.com\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(
242 trimmed,
243 );
244 const repositoryNameWithOwner = match?.[1]?.trim() ?? "";
245 return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;
247​
248function deriveLocalBranchNameCandidatesFromRemoteRef(
249 branchName: string,
250 remoteName?: string,
251): ReadonlyArray<string> {
252 const candidates = new Set<string>();
253 const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
254 if (firstSlashCandidate.length > 0) {
255 candidates.add(firstSlashCandidate);
256 }
257​
258 if (remoteName) {
259 const remotePrefix = `${remoteName}/`;
260 if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
261 candidates.add(branchName.slice(remotePrefix.length));
262 }
263 }
264​
265 return [...candidates];
267​
268/**
269 * Hide `origin/*` remote refs when a matching local refName already exists.
270 */
271export function dedupeRemoteBranchesWithLocalMatches(
272 refs: ReadonlyArray<VcsRef>,
273): ReadonlyArray<VcsRef> {
274 const localBranchNames = new Set(
275 Arr.filterMap(refs, (refName) =>
276 refName.isRemote ? Result.failVoid : Result.succeed(refName.name),
277 ),
278 );
279​
280 return refs.filter((refName) => {
281 if (!refName.isRemote) {
282 return true;
283 }
284​
285 if (refName.remoteName !== "origin") {
286 return true;
287 }
288​
289 const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
290 refName.name,
291 refName.remoteName,
292 );
293 return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
294 });
296​
297export function detectSourceControlProviderFromGitRemoteUrl(
298 remoteUrl: string,
299): SourceControlProviderInfo | null {
300 return detectSourceControlProviderFromRemoteUrl(remoteUrl);
302​
303const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
304 hasUpstream: false,
305 aheadCount: 0,
306 behindCount: 0,
307 aheadOfDefaultCount: 0,
308 pr: null,
309};
310​
311export function mergeGitStatusParts(
312 local: VcsStatusLocalResult,
313 remote: VcsStatusRemoteResult | null,
314): VcsStatusResult {
315 return {
316 ...local,
317 ...(remote ?? EMPTY_GIT_STATUS_REMOTE),
318 };
320​
321function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
322 return {
323 hasUpstream: status.hasUpstream,
324 aheadCount: status.aheadCount,
325 behindCount: status.behindCount,
326 ...(status.aheadOfDefaultCount === undefined
327 ? {}
328 : { aheadOfDefaultCount: status.aheadOfDefaultCount }),
329 pr: status.pr,
330 };
332​
333function toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult {
334 return {
335 isRepo: status.isRepo,
336 ...(status.sourceControlProvider
337 ? { sourceControlProvider: status.sourceControlProvider }
338 : {}),
339 hasPrimaryRemote: status.hasPrimaryRemote,
340 isDefaultRef: status.isDefaultRef,
341 refName: status.refName,
342 hasWorkingTreeChanges: status.hasWorkingTreeChanges,
343 workingTree: status.workingTree,
344 };
346​
347export function applyGitStatusStreamEvent(
348 current: VcsStatusResult | null,
349 event: VcsStatusStreamEvent,
350): VcsStatusResult {
351 switch (event._tag) {
352 case "snapshot":
353 return mergeGitStatusParts(event.local, event.remote);
354 case "localUpdated":
355 return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);
356 case "remoteUpdated":
357 if (current === null) {
358 return mergeGitStatusParts(
359 {
360 isRepo: true,
361 hasPrimaryRemote: false,
362 isDefaultRef: false,
363 refName: null,
364 hasWorkingTreeChanges: false,
365 workingTree: { files: [], insertions: 0, deletions: 0 },
366 },
367 event.remote,
368 );
369 }
370 return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
371 }