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

git.ts

397 lines12.7 KB

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