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

git.ts

377 lines12.0 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 parseOriginUrlFromGitConfig(configText: string): string | null {
200 let section: string | null = null;
201 let originUrl: string | null = null;
202 let firstRemoteUrl: string | null = null;
203 // A trailing backslash continues the value on the next line.
204 const joined = configText.replace(/\\\r?\n[ \t]*/g, "");
205 for (const rawLine of joined.split(/\r?\n/)) {
206 const line = rawLine.trim();
207 if (line.length === 0 || line.startsWith("#") || line.startsWith(";")) continue;
208 // Both `[remote "origin"]` and the legacy `[remote.origin]` form, with an
209 // optional trailing comment. Git keeps quoted subsections case-sensitive
210 // but folds the dotted form to lowercase.
211 const header = /^\[\s*remote(?:\s+"([^"]+)"|\.([^\]\s]+))\s*\](?:\s*[#;].*)?$/i.exec(line);
212 if (header) {
213 section = header[1] ?? header[2]?.toLowerCase() ?? null;
214 continue;
215 }
216 if (line.startsWith("[")) {
217 section = null;
218 continue;
219 }
220 if (section === null) continue;
221 const match = /^url\s*=\s*(.*)$/i.exec(line);
222 if (!match) continue;
223 const url = parseGitConfigValue(match[1] ?? "");
224 if (url.length === 0) continue;
225 if (section === "origin") {
226 originUrl ??= url;
227 } else {
228 firstRemoteUrl ??= url;
229 }
230 }
231 return originUrl ?? firstRemoteUrl;
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// Only the whitespace git actually rejects is replaced — git accepts U+00A0 and
269// friends, and rewriting those would silently create a ref the user never asked
270// for.
271export function sanitizeNewRefName(rawName: string): string {
272 return rawName.trim().replace(/[ \t\n\r\f\v]+/g, "-");
274​
275export function dedupeRemoteBranchesWithLocalMatches(
276 refs: ReadonlyArray<VcsRef>,
277): ReadonlyArray<VcsRef> {
278 const localBranchNames = new Set(
279 Arr.filterMap(refs, (refName) =>
280 refName.isRemote ? Result.failVoid : Result.succeed(refName.name),
281 ),
282 );
283​
284 return refs.filter((refName) => {
285 if (!refName.isRemote) {
286 return true;
287 }
288​
289 if (refName.remoteName !== "origin") {
290 return true;
291 }
292​
293 const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
294 refName.name,
295 refName.remoteName,
296 );
297 return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
298 });
300​
301export function detectSourceControlProviderFromGitRemoteUrl(
302 remoteUrl: string,
303): SourceControlProviderInfo | null {
304 return detectSourceControlProviderFromRemoteUrl(remoteUrl);
306​
307const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
308 hasUpstream: false,
309 aheadCount: 0,
310 behindCount: 0,
311 aheadOfDefaultCount: 0,
312 pr: null,
313};
314​
315export function mergeGitStatusParts(
316 local: VcsStatusLocalResult,
317 remote: VcsStatusRemoteResult | null,
318): VcsStatusResult {
319 return {
320 ...local,
321 ...(remote ?? EMPTY_GIT_STATUS_REMOTE),
322 };
324​
325function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
326 return {
327 hasUpstream: status.hasUpstream,
328 aheadCount: status.aheadCount,
329 behindCount: status.behindCount,
330 ...(status.aheadOfDefaultCount === undefined
331 ? {}
332 : { aheadOfDefaultCount: status.aheadOfDefaultCount }),
333 pr: status.pr,
334 };
336​
337function toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult {
338 return {
339 isRepo: status.isRepo,
340 ...(status.sourceControlProvider
341 ? { sourceControlProvider: status.sourceControlProvider }
342 : {}),
343 hasPrimaryRemote: status.hasPrimaryRemote,
344 isDefaultRef: status.isDefaultRef,
345 refName: status.refName,
346 hasWorkingTreeChanges: status.hasWorkingTreeChanges,
347 workingTree: status.workingTree,
348 ...(status.branchChanges ? { branchChanges: status.branchChanges } : {}),
349 };
351​
352export function applyGitStatusStreamEvent(
353 current: VcsStatusResult | null,
354 event: VcsStatusStreamEvent,
355): VcsStatusResult {
356 switch (event._tag) {
357 case "snapshot":
358 return mergeGitStatusParts(event.local, event.remote);
359 case "localUpdated":
360 return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);
361 case "remoteUpdated":
362 if (current === null) {
363 return mergeGitStatusParts(
364 {
365 isRepo: true,
366 hasPrimaryRemote: false,
367 isDefaultRef: false,
368 refName: null,
369 hasWorkingTreeChanges: false,
370 workingTree: { files: [], insertions: 0, deletions: 0 },
371 },
372 event.remote,
373 );
374 }
375 return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
376 }