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

git.ts

379 lines12.0 KB

1import type {
2 BranchNamingOptions,
3 VcsRef,
4 SourceControlProviderInfo,
5 SourceControlHostOverrides,
6 VcsStatusLocalResult,
7 VcsStatusRemoteResult,
8 VcsStatusResult,
9 VcsStatusStreamEvent,
10} from "@t3tools/contracts";
11import * as Arr from "effect/Array";
12import * as Result from "effect/Result";
13import { detectSourceControlProviderFromRemoteUrl } from "./sourceControl.ts";
14​
15export const WORKTREE_BRANCH_PREFIX = "t3";
16const TEMP_WORKTREE_HEX_TOKEN = "[0-9a-f]{8}";
17const TEMP_WORKTREE_UUID_V4_TOKEN =
18 "[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}";
19const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(
20 `^(?:${WORKTREE_BRANCH_PREFIX}[-/]${TEMP_WORKTREE_HEX_TOKEN}|t3code(?:[-/]${TEMP_WORKTREE_HEX_TOKEN}|\\/${TEMP_WORKTREE_UUID_V4_TOKEN}))$`,
21);
22​
23export function sanitizeBranchFragment(raw: string): string {
24 const normalized = raw
25 .trim()
26 .toLowerCase()
27 .replace(/['"`]/g, "")
28 .replace(/^[./\s_-]+|[./\s_-]+$/g, "");
29​
30 const branchFragment = normalized
31 .replace(/[^a-z0-9/_-]+/g, "-")
32 .replace(/\/+/g, "/")
33 .replace(/-+/g, "-")
34 .replace(/^[./_-]+|[./_-]+$/g, "")
35 .slice(0, 64)
36 .replace(/[./_-]+$/g, "");
37​
38 return branchFragment.length > 0 ? branchFragment : "update";
40​
41export function formatGeneratedBranchName(raw: string, naming?: BranchNamingOptions): string {
42 if (naming?.mode === "custom") return raw.trim();
43 const branch = sanitizeBranchFragment(raw);
44 if (naming?.mode !== "static") return branch;
45 const prefix = naming.prefix
46 .split("/")
47 .map((part) =>
48 part
49 .replace(/[^a-zA-Z0-9_-]+/g, "-")
50 .replace(/-+/g, "-")
51 .replace(/^-+|-+$/g, ""),
52 )
53 .filter(Boolean)
54 .join("/");
55 return prefix ? `${prefix}/${branch}` : branch;
57​
58export function sanitizeFeatureBranchName(raw: string): string {
59 const sanitized = sanitizeBranchFragment(raw);
60 return sanitized.includes("/") ? sanitized : `feature/${sanitized}`;
62​
63const AUTO_FEATURE_BRANCH_FALLBACK = "feature/update";
64​
65export function resolveAutoFeatureBranchName(
66 existingBranchNames: readonly string[],
67 preferredBranch?: string,
68): string {
69 const preferred = preferredBranch?.trim();
70 const resolvedBase = sanitizeFeatureBranchName(
71 preferred && preferred.length > 0 ? preferred : AUTO_FEATURE_BRANCH_FALLBACK,
72 );
73 const existingNames = existingBranchNames.map((refName) => refName.toLowerCase());
74 const existingRefs = new Set(existingNames);
75 const parts = resolvedBase.split("/");
76 let resolved = "";
77​
78 for (const [index, part] of parts.entries()) {
79 const base = resolved ? `${resolved}/${part}` : part;
80 let candidate = base;
81 let suffix = 2;
82 while (
83 existingRefs.has(candidate) ||
84 (index === parts.length - 1 &&
85 existingNames.some((refName) => refName.startsWith(`${candidate}/`)))
86 ) {
87 candidate = `${base}-${suffix}`;
88 suffix += 1;
89 }
90 resolved = candidate;
91 }
92​
93 return resolved;
95​
96export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
97 const firstSeparatorIndex = branchName.indexOf("/");
98 if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
99 return branchName;
100 }
101 return branchName.slice(firstSeparatorIndex + 1);
103​
104export function buildTemporaryWorktreeBranchName(
105 randomHex: (byteLength: number) => string,
106): string {
107 const token = randomHex(4)
108 .toLowerCase()
109 .replace(/[^0-9a-f]/g, "")
110 .slice(0, 8);
111 return `${WORKTREE_BRANCH_PREFIX}/${token}`;
113​
114/**
115 * Git stores refs as paths, so a plain `t3` branch makes every `t3/<hex>`
116 * ref impossible. This moves a temporary name to the flat `t3-<hex>` sibling.
117 */
118export function flattenTemporaryWorktreeBranchName(refName: string): string {
119 const normalized = refName.trim().toLowerCase();
120 const tokenStart = normalized.search(/[-/]/) + 1;
121 const token = normalized.slice(tokenStart, tokenStart + 8);
122 return `${WORKTREE_BRANCH_PREFIX}-${token}`;
124​
125export function isTemporaryWorktreeBranch(refName: string): boolean {
126 return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase());
128​
129/**
130 * Azure alone addresses one repository under two names that share no part: `ssh.dev.azure.com` and
131 * `v3/{org}/{project}/{repo}` over SSH, against `dev.azure.com` and `{org}/{project}/_git/{repo}`
132 * everywhere a person sees it. A project cloned over SSH would otherwise be a different repository
133 * to every comparison made against a pull request URL, which arrives in the web spelling.
134 */
135function azureDevOpsRepositoryKey(host: string, segments: ReadonlyArray<string>): string | null {
136 if (host !== "ssh.dev.azure.com" && host !== "vs-ssh.visualstudio.com") return null;
137 const [marker, organization, project, repository] = segments;
138 if (segments.length !== 4 || marker !== "v3") return null;
139 if (!organization || !project || !repository) return null;
140 return host === "ssh.dev.azure.com"
141 ? `dev.azure.com/${organization}/${project}/_git/${repository}`
142 : `${organization}.visualstudio.com/${project}/_git/${repository}`;
144​
145export function normalizeGitRemoteUrl(value: string): string {
146 const normalized = value
147 .trim()
148 .replace(/\/+$/g, "")
149 .replace(/\.git$/i, "")
150 .toLowerCase();
151​
152 if (/^(?:ssh|https?|git):\/\//i.test(normalized)) {
153 try {
154 const url = new URL(normalized);
155 const repositorySegments = url.pathname.split("/").filter((segment) => segment.length > 0);
156 if (url.hostname && repositorySegments.length > 1) {
157 return (
158 azureDevOpsRepositoryKey(url.hostname, repositorySegments) ??
159 `${url.hostname}/${repositorySegments.join("/")}`
160 );
161 }
162 } catch {
163 return normalized;
164 }
165 }
166​
167 // A userless one-letter prefix is a Windows drive, not an SCP host.
168 const scpStyleHostAndPath = /^[a-z]:/i.test(normalized)
169 ? null
170 : /^(?:[a-zA-Z0-9._-]+@)?([^@:/\\\s]+):\/?([^/\s]+(?:\/[^/\s]+)+)$/i.exec(normalized);
171 const scpHost = scpStyleHostAndPath?.[1];
172 const scpPath = scpStyleHostAndPath?.[2];
173 if (scpHost && scpPath) {
174 return azureDevOpsRepositoryKey(scpHost, scpPath.split("/")) ?? `${scpHost}/${scpPath}`;
175 }
176​
177 return normalized;
179​
180function parseGitConfigValue(raw: string): string {
181 let out = "";
182 let quoted = false;
183 for (let index = 0; index < raw.length; index += 1) {
184 const char = raw[index]!;
185 if (char === "\\" && index + 1 < raw.length) {
186 out += raw[index + 1];
187 index += 1;
188 continue;
189 }
190 if (char === '"') {
191 quoted = !quoted;
192 continue;
193 }
194 if (!quoted && (char === "#" || char === ";")) break;
195 out += char;
196 }
197 return out.trim();
199​
200export function parseOriginUrlFromGitConfig(configText: string): string | null {
201 let section: string | null = null;
202 let originUrl: string | null = null;
203 let firstRemoteUrl: string | null = null;
204 // A trailing backslash continues the value on the next line.
205 const joined = configText.replace(/\\\r?\n[ \t]*/g, "");
206 for (const rawLine of joined.split(/\r?\n/)) {
207 const line = rawLine.trim();
208 if (line.length === 0 || line.startsWith("#") || line.startsWith(";")) continue;
209 // Both `[remote "origin"]` and the legacy `[remote.origin]` form, with an
210 // optional trailing comment. Git keeps quoted subsections case-sensitive
211 // but folds the dotted form to lowercase.
212 const header = /^\[\s*remote(?:\s+"([^"]+)"|\.([^\]\s]+))\s*\](?:\s*[#;].*)?$/i.exec(line);
213 if (header) {
214 section = header[1] ?? header[2]?.toLowerCase() ?? null;
215 continue;
216 }
217 if (line.startsWith("[")) {
218 section = null;
219 continue;
220 }
221 if (section === null) continue;
222 const match = /^url\s*=\s*(.*)$/i.exec(line);
223 if (!match) continue;
224 const url = parseGitConfigValue(match[1] ?? "");
225 if (url.length === 0) continue;
226 if (section === "origin") {
227 originUrl ??= url;
228 } else {
229 firstRemoteUrl ??= url;
230 }
231 }
232 return originUrl ?? firstRemoteUrl;
234​
235export function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {
236 const trimmed = url?.trim() ?? "";
237 if (trimmed.length === 0) {
238 return null;
239 }
240​
241 const match =
242 /^(?:git@github\.com:|ssh:\/\/(?:git@)?github\.com\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(
243 trimmed,
244 );
245 const repositoryNameWithOwner = match?.[1]?.trim() ?? "";
246 return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;
248​
249function deriveLocalBranchNameCandidatesFromRemoteRef(
250 branchName: string,
251 remoteName?: string,
252): ReadonlyArray<string> {
253 const candidates = new Set<string>();
254 const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
255 if (firstSlashCandidate.length > 0) {
256 candidates.add(firstSlashCandidate);
257 }
258​
259 if (remoteName) {
260 const remotePrefix = `${remoteName}/`;
261 if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
262 candidates.add(branchName.slice(remotePrefix.length));
263 }
264 }
265​
266 return [...candidates];
268​
269// Only the whitespace git actually rejects is replaced — git accepts U+00A0 and
270// friends, and rewriting those would silently create a ref the user never asked
271// for.
272export function sanitizeNewRefName(rawName: string): string {
273 return rawName.trim().replace(/[ \t\n\r\f\v]+/g, "-");
275​
276export function dedupeRemoteBranchesWithLocalMatches(
277 refs: ReadonlyArray<VcsRef>,
278): ReadonlyArray<VcsRef> {
279 const localBranchNames = new Set(
280 Arr.filterMap(refs, (refName) =>
281 refName.isRemote ? Result.failVoid : Result.succeed(refName.name),
282 ),
283 );
284​
285 return refs.filter((refName) => {
286 if (!refName.isRemote) {
287 return true;
288 }
289​
290 if (refName.remoteName !== "origin") {
291 return true;
292 }
293​
294 const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
295 refName.name,
296 refName.remoteName,
297 );
298 return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
299 });
301​
302export function detectSourceControlProviderFromGitRemoteUrl(
303 remoteUrl: string,
304 overrides?: SourceControlHostOverrides,
305): SourceControlProviderInfo | null {
306 return detectSourceControlProviderFromRemoteUrl(remoteUrl, overrides);
308​
309const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
310 hasUpstream: false,
311 aheadCount: 0,
312 behindCount: 0,
313 aheadOfDefaultCount: 0,
314 pr: null,
315};
316​
317export function mergeGitStatusParts(
318 local: VcsStatusLocalResult,
319 remote: VcsStatusRemoteResult | null,
320): VcsStatusResult {
321 return {
322 ...local,
323 ...(remote ?? EMPTY_GIT_STATUS_REMOTE),
324 };
326​
327function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
328 return {
329 hasUpstream: status.hasUpstream,
330 aheadCount: status.aheadCount,
331 behindCount: status.behindCount,
332 ...(status.aheadOfDefaultCount === undefined
333 ? {}
334 : { aheadOfDefaultCount: status.aheadOfDefaultCount }),
335 pr: status.pr,
336 };
338​
339function toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult {
340 return {
341 isRepo: status.isRepo,
342 ...(status.sourceControlProvider
343 ? { sourceControlProvider: status.sourceControlProvider }
344 : {}),
345 hasPrimaryRemote: status.hasPrimaryRemote,
346 isDefaultRef: status.isDefaultRef,
347 refName: status.refName,
348 hasWorkingTreeChanges: status.hasWorkingTreeChanges,
349 workingTree: status.workingTree,
350 ...(status.branchChanges ? { branchChanges: status.branchChanges } : {}),
351 };
353​
354export function applyGitStatusStreamEvent(
355 current: VcsStatusResult | null,
356 event: VcsStatusStreamEvent,
357): VcsStatusResult {
358 switch (event._tag) {
359 case "snapshot":
360 return mergeGitStatusParts(event.local, event.remote);
361 case "localUpdated":
362 return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);
363 case "remoteUpdated":
364 if (current === null) {
365 return mergeGitStatusParts(
366 {
367 isRepo: true,
368 hasPrimaryRemote: false,
369 isDefaultRef: false,
370 refName: null,
371 hasWorkingTreeChanges: false,
372 workingTree: { files: [], insertions: 0, deletions: 0 },
373 },
374 event.remote,
375 );
376 }
377 return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
378 }