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

git.ts

364 lines11.3 KB

1import type {
2 BranchNamingOptions,
3 VcsRef,
4 VcsStatusLocalResult,
5 VcsStatusRemoteResult,
6 VcsStatusResult,
7 VcsStatusStreamEvent,
8} from "@t3tools/contracts";
9import * as Arr from "effect/Array";
10import * as Result from "effect/Result";
11​
12export const WORKTREE_BRANCH_PREFIX = "t3";
13const TEMP_WORKTREE_HEX_TOKEN = "[0-9a-f]{8}";
14const TEMP_WORKTREE_UUID_V4_TOKEN =
15 "[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}";
16const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(
17 `^(?:${WORKTREE_BRANCH_PREFIX}[-/]${TEMP_WORKTREE_HEX_TOKEN}|t3code(?:[-/]${TEMP_WORKTREE_HEX_TOKEN}|\\/${TEMP_WORKTREE_UUID_V4_TOKEN}))$`,
18);
19​
20export function sanitizeBranchFragment(raw: string): string {
21 const normalized = raw
22 .trim()
23 .toLowerCase()
24 .replace(/['"`]/g, "")
25 .replace(/^[./\s_-]+|[./\s_-]+$/g, "");
26​
27 const branchFragment = normalized
28 .replace(/[^a-z0-9/_-]+/g, "-")
29 .replace(/\/+/g, "/")
30 .replace(/-+/g, "-")
31 .replace(/^[./_-]+|[./_-]+$/g, "")
32 .slice(0, 64)
33 .replace(/[./_-]+$/g, "");
34​
35 return branchFragment.length > 0 ? branchFragment : "update";
37​
38export function formatGeneratedBranchName(raw: string, naming?: BranchNamingOptions): string {
39 if (naming?.mode === "custom") return raw.trim();
40 const branch = sanitizeBranchFragment(raw);
41 if (naming?.mode !== "static") return branch;
42 const prefix = naming.prefix
43 .split("/")
44 .map((part) =>
45 part
46 .replace(/[^a-zA-Z0-9_-]+/g, "-")
47 .replace(/-+/g, "-")
48 .replace(/^-+|-+$/g, ""),
49 )
50 .filter(Boolean)
51 .join("/");
52 return prefix ? `${prefix}/${branch}` : branch;
54​
55export function sanitizeFeatureBranchName(raw: string): string {
56 const sanitized = sanitizeBranchFragment(raw);
57 return sanitized.includes("/") ? sanitized : `feature/${sanitized}`;
59​
60const AUTO_FEATURE_BRANCH_FALLBACK = "feature/update";
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 = existingBranchNames.map((refName) => refName.toLowerCase());
71 const existingRefs = new Set(existingNames);
72 const parts = resolvedBase.split("/");
73 let resolved = "";
74​
75 for (const [index, part] of parts.entries()) {
76 const base = resolved ? `${resolved}/${part}` : part;
77 let candidate = base;
78 let suffix = 2;
79 while (
80 existingRefs.has(candidate) ||
81 (index === parts.length - 1 &&
82 existingNames.some((refName) => refName.startsWith(`${candidate}/`)))
83 ) {
84 candidate = `${base}-${suffix}`;
85 suffix += 1;
86 }
87 resolved = candidate;
88 }
89​
90 return resolved;
92​
93export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
94 const firstSeparatorIndex = branchName.indexOf("/");
95 if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
96 return branchName;
97 }
98 return branchName.slice(firstSeparatorIndex + 1);
100​
101export function buildTemporaryWorktreeBranchName(
102 randomHex: (byteLength: number) => string,
103): string {
104 const token = randomHex(4)
105 .toLowerCase()
106 .replace(/[^0-9a-f]/g, "")
107 .slice(0, 8);
108 return `${WORKTREE_BRANCH_PREFIX}/${token}`;
110​
111/** Flatten temporary t3/<hex> refs because an existing t3 branch blocks nested refs. */
112export function flattenTemporaryWorktreeBranchName(refName: string): string {
113 const normalized = refName.trim().toLowerCase();
114 const tokenStart = normalized.search(/[-/]/) + 1;
115 const token = normalized.slice(tokenStart, tokenStart + 8);
116 return `${WORKTREE_BRANCH_PREFIX}-${token}`;
118​
119export function isTemporaryWorktreeBranch(refName: string): boolean {
120 return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase());
122​
123function lowerCaseRemote(value: string): string {
124 return value
125 .trim()
126 .replace(/\/+$/g, "")
127 .replace(/\.git$/i, "")
128 .toLowerCase();
130​
131/**
132 * The host and repository path a remote names, lower case and without a port, or null for a
133 * remote that names no host, such as a local path.
134 */
135export function parseGitRemoteRepository(
136 value: string,
137): { readonly host: string; readonly path: string } | null {
138 const normalized = lowerCaseRemote(value);
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 { host: url.hostname, path: repositorySegments.join("/") };
146 }
147 } catch {
148 return null;
149 }
150 }
151​
152 // A userless one-letter prefix is a Windows drive, not an SCP host.
153 const scpStyleHostAndPath = /^[a-z]:/i.test(normalized)
154 ? null
155 : /^(?:[a-zA-Z0-9._-]+@)?([^@:/\\\s]+):\/?([^/\s]+(?:\/[^/\s]+)+)$/i.exec(normalized);
156 const scpHost = scpStyleHostAndPath?.[1];
157 const scpPath = scpStyleHostAndPath?.[2];
158 return scpHost && scpPath ? { host: scpHost, path: scpPath } : null;
160​
161/**
162 * `host/path` for a remote that names a host, otherwise the remote itself, lower case. A host that
163 * spells repositories differently over SSH has its source control registry's
164 * `repositoryKeyFromRemote` rewrite this, so persisted keys come from that, not from here.
165 */
166export function normalizeGitRemoteUrl(value: string): string {
167 const repository = parseGitRemoteRepository(value);
168 return repository === null ? lowerCaseRemote(value) : `${repository.host}/${repository.path}`;
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​
191export function isBareGitConfig(configText: string): boolean {
192 let inCore = false;
193 let bare = false;
194 for (const rawLine of configText.split(/\r?\n/)) {
195 let line = rawLine.trim();
196 // Git accepts the first setting on the section header's own line.
197 const header = /^\[\s*([^\]]*?)\s*\](.*)$/.exec(line);
198 if (header !== null) {
199 inCore = header[1]!.toLowerCase() === "core";
200 line = header[2]!.trim();
201 }
202 if (!inCore) continue;
203 const match = /^bare\s*(?:=(.*)|[#;].*)?$/i.exec(line);
204 if (match === null) continue;
205 const value = match[1] === undefined ? "true" : parseGitConfigValue(match[1]).toLowerCase();
206 bare = value === "true" || value === "yes" || value === "on" || value === "1";
207 }
208 return bare;
210​
211export function parseOriginUrlFromGitConfig(configText: string): string | null {
212 let section: string | null = null;
213 let originUrl: string | null = null;
214 let firstRemoteUrl: string | null = null;
215 const joined = configText.replace(/\\\r?\n[ \t]*/g, "");
216 for (const rawLine of joined.split(/\r?\n/)) {
217 let line = rawLine.trim();
218 if (line.length === 0 || line.startsWith("#") || line.startsWith(";")) continue;
219 // Git preserves case in quoted remote subsections but lowercases legacy dotted ones,
220 // and accepts the first setting on the section header's own line.
221 const header = /^\[\s*remote(?:\s+"([^"]+)"|\.([^\]\s]+))\s*\](.*)$/i.exec(line);
222 if (header) {
223 section = header[1] ?? header[2]?.toLowerCase() ?? null;
224 line = header[3]!.trim();
225 } else if (line.startsWith("[")) {
226 section = null;
227 continue;
228 }
229 if (section === null) continue;
230 const match = /^url\s*=\s*(.*)$/i.exec(line);
231 if (!match) continue;
232 const url = parseGitConfigValue(match[1] ?? "");
233 if (url.length === 0) continue;
234 if (section === "origin") {
235 originUrl ??= url;
236 } else {
237 firstRemoteUrl ??= url;
238 }
239 }
240 return originUrl ?? firstRemoteUrl;
242​
243function deriveLocalBranchNameCandidatesFromRemoteRef(
244 branchName: string,
245 remoteName?: string,
246): ReadonlyArray<string> {
247 const candidates = new Set<string>();
248 const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
249 if (firstSlashCandidate.length > 0) {
250 candidates.add(firstSlashCandidate);
251 }
252​
253 if (remoteName) {
254 const remotePrefix = `${remoteName}/`;
255 if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
256 candidates.add(branchName.slice(remotePrefix.length));
257 }
258 }
259​
260 return [...candidates];
262​
263// Replace only Git-rejected whitespace; nonbreaking spaces are valid ref characters.
264export function sanitizeNewRefName(rawName: string): string {
265 return rawName.trim().replace(/[ \t\n\r\f\v]+/g, "-");
267​
268export function dedupeRemoteBranchesWithLocalMatches(
269 refs: ReadonlyArray<VcsRef>,
270): ReadonlyArray<VcsRef> {
271 const localBranchNames = new Set(
272 Arr.filterMap(refs, (refName) =>
273 refName.isRemote ? Result.failVoid : Result.succeed(refName.name),
274 ),
275 );
276​
277 return refs.filter((refName) => {
278 if (!refName.isRemote) {
279 return true;
280 }
281​
282 if (refName.remoteName !== "origin") {
283 return true;
284 }
285​
286 const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
287 refName.name,
288 refName.remoteName,
289 );
290 return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
291 });
293​
294const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
295 hasUpstream: false,
296 aheadCount: 0,
297 behindCount: 0,
298 aheadOfDefaultCount: 0,
299 pr: null,
300};
301​
302export function mergeGitStatusParts(
303 local: VcsStatusLocalResult,
304 remote: VcsStatusRemoteResult | null,
305): VcsStatusResult {
306 return {
307 ...local,
308 ...(remote ?? EMPTY_GIT_STATUS_REMOTE),
309 };
311​
312function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
313 return {
314 hasUpstream: status.hasUpstream,
315 aheadCount: status.aheadCount,
316 behindCount: status.behindCount,
317 ...(status.aheadOfDefaultCount === undefined
318 ? {}
319 : { aheadOfDefaultCount: status.aheadOfDefaultCount }),
320 pr: status.pr,
321 };
323​
324function toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult {
325 return {
326 isRepo: status.isRepo,
327 ...(status.sourceControlProvider
328 ? { sourceControlProvider: status.sourceControlProvider }
329 : {}),
330 hasPrimaryRemote: status.hasPrimaryRemote,
331 isDefaultRef: status.isDefaultRef,
332 refName: status.refName,
333 hasWorkingTreeChanges: status.hasWorkingTreeChanges,
334 workingTree: status.workingTree,
335 ...(status.branchChanges ? { branchChanges: status.branchChanges } : {}),
336 };
338​
339export function applyGitStatusStreamEvent(
340 current: VcsStatusResult | null,
341 event: VcsStatusStreamEvent,
342): VcsStatusResult {
343 switch (event._tag) {
344 case "snapshot":
345 return mergeGitStatusParts(event.local, event.remote);
346 case "localUpdated":
347 return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);
348 case "remoteUpdated":
349 if (current === null) {
350 return mergeGitStatusParts(
351 {
352 isRepo: true,
353 hasPrimaryRemote: false,
354 isDefaultRef: false,
355 refName: null,
356 hasWorkingTreeChanges: false,
357 workingTree: { files: [], insertions: 0, deletions: 0 },
358 },
359 event.remote,
360 );
361 }
362 return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
363 }