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

git.ts

376 lines11.8 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 const scpStyleHostAndPath = /^[a-zA-Z0-9._-]+@([^:/\s]+):([^/\s]+(?:\/[^/\s]+)+)$/i.exec(
167 normalized,
168 );
169 const scpHost = scpStyleHostAndPath?.[1];
170 const scpPath = scpStyleHostAndPath?.[2];
171 if (scpHost && scpPath) {
172 return azureDevOpsRepositoryKey(scpHost, scpPath.split("/")) ?? `${scpHost}/${scpPath}`;
173 }
174​
175 return normalized;
177​
178function parseGitConfigValue(raw: string): string {
179 let out = "";
180 let quoted = false;
181 for (let index = 0; index < raw.length; index += 1) {
182 const char = raw[index]!;
183 if (char === "\\" && index + 1 < raw.length) {
184 out += raw[index + 1];
185 index += 1;
186 continue;
187 }
188 if (char === '"') {
189 quoted = !quoted;
190 continue;
191 }
192 if (!quoted && (char === "#" || char === ";")) break;
193 out += char;
194 }
195 return out.trim();
197​
198export function parseOriginUrlFromGitConfig(configText: string): string | null {
199 let section: string | null = null;
200 let originUrl: string | null = null;
201 let firstRemoteUrl: string | null = null;
202 // A trailing backslash continues the value on the next line.
203 const joined = configText.replace(/\\\r?\n[ \t]*/g, "");
204 for (const rawLine of joined.split(/\r?\n/)) {
205 const line = rawLine.trim();
206 if (line.length === 0 || line.startsWith("#") || line.startsWith(";")) continue;
207 // Both `[remote "origin"]` and the legacy `[remote.origin]` form, with an
208 // optional trailing comment. Git keeps quoted subsections case-sensitive
209 // but folds the dotted form to lowercase.
210 const header = /^\[\s*remote(?:\s+"([^"]+)"|\.([^\]\s]+))\s*\](?:\s*[#;].*)?$/i.exec(line);
211 if (header) {
212 section = header[1] ?? header[2]?.toLowerCase() ?? null;
213 continue;
214 }
215 if (line.startsWith("[")) {
216 section = null;
217 continue;
218 }
219 if (section === null) continue;
220 const match = /^url\s*=\s*(.*)$/i.exec(line);
221 if (!match) continue;
222 const url = parseGitConfigValue(match[1] ?? "");
223 if (url.length === 0) continue;
224 if (section === "origin") {
225 originUrl ??= url;
226 } else {
227 firstRemoteUrl ??= url;
228 }
229 }
230 return originUrl ?? firstRemoteUrl;
232​
233export function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {
234 const trimmed = url?.trim() ?? "";
235 if (trimmed.length === 0) {
236 return null;
237 }
238​
239 const match =
240 /^(?:git@github\.com:|ssh:\/\/(?:git@)?github\.com\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(
241 trimmed,
242 );
243 const repositoryNameWithOwner = match?.[1]?.trim() ?? "";
244 return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;
246​
247function deriveLocalBranchNameCandidatesFromRemoteRef(
248 branchName: string,
249 remoteName?: string,
250): ReadonlyArray<string> {
251 const candidates = new Set<string>();
252 const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
253 if (firstSlashCandidate.length > 0) {
254 candidates.add(firstSlashCandidate);
255 }
256​
257 if (remoteName) {
258 const remotePrefix = `${remoteName}/`;
259 if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
260 candidates.add(branchName.slice(remotePrefix.length));
261 }
262 }
263​
264 return [...candidates];
266​
267// Only the whitespace git actually rejects is replaced — git accepts U+00A0 and
268// friends, and rewriting those would silently create a ref the user never asked
269// for.
270export function sanitizeNewRefName(rawName: string): string {
271 return rawName.trim().replace(/[ \t\n\r\f\v]+/g, "-");
273​
274export function dedupeRemoteBranchesWithLocalMatches(
275 refs: ReadonlyArray<VcsRef>,
276): ReadonlyArray<VcsRef> {
277 const localBranchNames = new Set(
278 Arr.filterMap(refs, (refName) =>
279 refName.isRemote ? Result.failVoid : Result.succeed(refName.name),
280 ),
281 );
282​
283 return refs.filter((refName) => {
284 if (!refName.isRemote) {
285 return true;
286 }
287​
288 if (refName.remoteName !== "origin") {
289 return true;
290 }
291​
292 const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
293 refName.name,
294 refName.remoteName,
295 );
296 return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
297 });
299​
300export function detectSourceControlProviderFromGitRemoteUrl(
301 remoteUrl: string,
302): SourceControlProviderInfo | null {
303 return detectSourceControlProviderFromRemoteUrl(remoteUrl);
305​
306const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
307 hasUpstream: false,
308 aheadCount: 0,
309 behindCount: 0,
310 aheadOfDefaultCount: 0,
311 pr: null,
312};
313​
314export function mergeGitStatusParts(
315 local: VcsStatusLocalResult,
316 remote: VcsStatusRemoteResult | null,
317): VcsStatusResult {
318 return {
319 ...local,
320 ...(remote ?? EMPTY_GIT_STATUS_REMOTE),
321 };
323​
324function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
325 return {
326 hasUpstream: status.hasUpstream,
327 aheadCount: status.aheadCount,
328 behindCount: status.behindCount,
329 ...(status.aheadOfDefaultCount === undefined
330 ? {}
331 : { aheadOfDefaultCount: status.aheadOfDefaultCount }),
332 pr: status.pr,
333 };
335​
336function toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult {
337 return {
338 isRepo: status.isRepo,
339 ...(status.sourceControlProvider
340 ? { sourceControlProvider: status.sourceControlProvider }
341 : {}),
342 hasPrimaryRemote: status.hasPrimaryRemote,
343 isDefaultRef: status.isDefaultRef,
344 refName: status.refName,
345 hasWorkingTreeChanges: status.hasWorkingTreeChanges,
346 workingTree: status.workingTree,
347 ...(status.branchChanges ? { branchChanges: status.branchChanges } : {}),
348 };
350​
351export function applyGitStatusStreamEvent(
352 current: VcsStatusResult | null,
353 event: VcsStatusStreamEvent,
354): VcsStatusResult {
355 switch (event._tag) {
356 case "snapshot":
357 return mergeGitStatusParts(event.local, event.remote);
358 case "localUpdated":
359 return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);
360 case "remoteUpdated":
361 if (current === null) {
362 return mergeGitStatusParts(
363 {
364 isRepo: true,
365 hasPrimaryRemote: false,
366 isDefaultRef: false,
367 refName: null,
368 hasWorkingTreeChanges: false,
369 workingTree: { files: [], insertions: 0, deletions: 0 },
370 },
371 event.remote,
372 );
373 }
374 return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
375 }