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

git.ts

270 lines7.8 KB

1import type {
2 VcsRef,
3 SourceControlProviderInfo,
4 VcsStatusLocalResult,
5 VcsStatusRemoteResult,
6 VcsStatusResult,
7 VcsStatusStreamEvent,
8} from "@t3tools/contracts";
9import * as Effect from "effect/Effect";
10import * as Random from "effect/Random";
11import { detectSourceControlProviderFromRemoteUrl } from "./sourceControl.ts";
12​
13export const WORKTREE_BRANCH_PREFIX = "t3code";
14const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
15​
16/**
17 * Sanitize an arbitrary string into a valid, lowercase git refName fragment.
18 * Strips quotes, collapses separators, limits to 64 chars.
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​
38/**
39 * Sanitize a string into a `feature/…` refName name.
40 * Preserves an existing `feature/` prefix or slash-separated namespace.
41 */
42export function sanitizeFeatureBranchName(raw: string): string {
43 const sanitized = sanitizeBranchFragment(raw);
44 if (sanitized.includes("/")) {
45 return sanitized.startsWith("feature/") ? sanitized : `feature/${sanitized}`;
46 }
47 return `feature/${sanitized}`;
49​
50const AUTO_FEATURE_BRANCH_FALLBACK = "feature/update";
51​
52/**
53 * Resolve a unique `feature/…` refName name that doesn't collide with
54 * any existing refName. Appends a numeric suffix when needed.
55 */
56export function resolveAutoFeatureBranchName(
57 existingBranchNames: readonly string[],
58 preferredBranch?: string,
59): string {
60 const preferred = preferredBranch?.trim();
61 const resolvedBase = sanitizeFeatureBranchName(
62 preferred && preferred.length > 0 ? preferred : AUTO_FEATURE_BRANCH_FALLBACK,
63 );
64 const existingNames = new Set(existingBranchNames.map((refName) => refName.toLowerCase()));
65​
66 if (!existingNames.has(resolvedBase)) {
67 return resolvedBase;
68 }
69​
70 let suffix = 2;
71 while (existingNames.has(`${resolvedBase}-${suffix}`)) {
72 suffix += 1;
73 }
74​
75 return `${resolvedBase}-${suffix}`;
77​
78/**
79 * Strip the remote prefix from a remote ref such as `origin/feature/demo`.
80 */
81export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
82 const firstSeparatorIndex = branchName.indexOf("/");
83 if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
84 return branchName;
85 }
86 return branchName.slice(firstSeparatorIndex + 1);
88​
89export function buildTemporaryWorktreeBranchName(): string {
90 const token = Effect.runSync(Random.nextUUIDv4).replace(/-/g, "").slice(0, 8).toLowerCase();
91 return `${WORKTREE_BRANCH_PREFIX}/${token}`;
93​
94export function isTemporaryWorktreeBranch(refName: string): boolean {
95 return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase());
97​
98/**
99 * Normalize a git remote URL into a stable comparison key.
100 */
101export function normalizeGitRemoteUrl(value: string): string {
102 const normalized = value
103 .trim()
104 .replace(/\/+$/g, "")
105 .replace(/\.git$/i, "")
106 .toLowerCase();
107​
108 if (/^(?:ssh|https?|git):\/\//i.test(normalized)) {
109 try {
110 const url = new URL(normalized);
111 const repositoryPath = url.pathname
112 .split("/")
113 .filter((segment) => segment.length > 0)
114 .join("/");
115 if (url.hostname && repositoryPath.includes("/")) {
116 return `${url.hostname}/${repositoryPath}`;
117 }
118 } catch {
119 return normalized;
120 }
121 }
122​
123 const scpStyleHostAndPath = /^git@([^:/\s]+)[:/]([^/\s]+(?:\/[^/\s]+)+)$/i.exec(normalized);
124 if (scpStyleHostAndPath?.[1] && scpStyleHostAndPath[2]) {
125 return `${scpStyleHostAndPath[1]}/${scpStyleHostAndPath[2]}`;
126 }
127​
128 return normalized;
130​
131/**
132 * Best-effort parse of a GitHub `owner/repo` identifier from common remote URL shapes.
133 */
134export function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {
135 const trimmed = url?.trim() ?? "";
136 if (trimmed.length === 0) {
137 return null;
138 }
139​
140 const match =
141 /^(?:git@github\.com:|ssh:\/\/git@github\.com\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(
142 trimmed,
143 );
144 const repositoryNameWithOwner = match?.[1]?.trim() ?? "";
145 return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;
147​
148function deriveLocalBranchNameCandidatesFromRemoteRef(
149 branchName: string,
150 remoteName?: string,
151): ReadonlyArray<string> {
152 const candidates = new Set<string>();
153 const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
154 if (firstSlashCandidate.length > 0) {
155 candidates.add(firstSlashCandidate);
156 }
157​
158 if (remoteName) {
159 const remotePrefix = `${remoteName}/`;
160 if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
161 candidates.add(branchName.slice(remotePrefix.length));
162 }
163 }
164​
165 return [...candidates];
167​
168/**
169 * Hide `origin/*` remote refs when a matching local refName already exists.
170 */
171export function dedupeRemoteBranchesWithLocalMatches(
172 refs: ReadonlyArray<VcsRef>,
173): ReadonlyArray<VcsRef> {
174 const localBranchNames = new Set(
175 refs.filter((refName) => !refName.isRemote).map((refName) => refName.name),
176 );
177​
178 return refs.filter((refName) => {
179 if (!refName.isRemote) {
180 return true;
181 }
182​
183 if (refName.remoteName !== "origin") {
184 return true;
185 }
186​
187 const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
188 refName.name,
189 refName.remoteName,
190 );
191 return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
192 });
194​
195export function detectSourceControlProviderFromGitRemoteUrl(
196 remoteUrl: string,
197): SourceControlProviderInfo | null {
198 return detectSourceControlProviderFromRemoteUrl(remoteUrl);
200​
201const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
202 hasUpstream: false,
203 aheadCount: 0,
204 behindCount: 0,
205 aheadOfDefaultCount: 0,
206 pr: null,
207};
208​
209export function mergeGitStatusParts(
210 local: VcsStatusLocalResult,
211 remote: VcsStatusRemoteResult | null,
212): VcsStatusResult {
213 return {
214 ...local,
215 ...(remote ?? EMPTY_GIT_STATUS_REMOTE),
216 };
218​
219function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
220 return {
221 hasUpstream: status.hasUpstream,
222 aheadCount: status.aheadCount,
223 behindCount: status.behindCount,
224 ...(status.aheadOfDefaultCount === undefined
225 ? {}
226 : { aheadOfDefaultCount: status.aheadOfDefaultCount }),
227 pr: status.pr,
228 };
230​
231function toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult {
232 return {
233 isRepo: status.isRepo,
234 ...(status.sourceControlProvider
235 ? { sourceControlProvider: status.sourceControlProvider }
236 : {}),
237 hasPrimaryRemote: status.hasPrimaryRemote,
238 isDefaultRef: status.isDefaultRef,
239 refName: status.refName,
240 hasWorkingTreeChanges: status.hasWorkingTreeChanges,
241 workingTree: status.workingTree,
242 };
244​
245export function applyGitStatusStreamEvent(
246 current: VcsStatusResult | null,
247 event: VcsStatusStreamEvent,
248): VcsStatusResult {
249 switch (event._tag) {
250 case "snapshot":
251 return mergeGitStatusParts(event.local, event.remote);
252 case "localUpdated":
253 return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);
254 case "remoteUpdated":
255 if (current === null) {
256 return mergeGitStatusParts(
257 {
258 isRepo: true,
259 hasPrimaryRemote: false,
260 isDefaultRef: false,
261 refName: null,
262 hasWorkingTreeChanges: false,
263 workingTree: { files: [], insertions: 0, deletions: 0 },
264 },
265 event.remote,
266 );
267 }
268 return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
269 }