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

git.ts

322 lines8.8 KB

1import type {
2 GitBranch,
3 GitHostingProvider,
4 GitStatusLocalResult,
5 GitStatusRemoteResult,
6 GitStatusResult,
7 GitStatusStreamEvent,
8} from "@t3tools/contracts";
9import * as Effect from "effect/Effect";
10import * as Random from "effect/Random";
11​
12export const WORKTREE_BRANCH_PREFIX = "t3code";
13const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
14​
15/**
16 * Sanitize an arbitrary string into a valid, lowercase git branch fragment.
17 * Strips quotes, collapses separators, limits to 64 chars.
18 */
19export function sanitizeBranchFragment(raw: string): string {
20 const normalized = raw
21 .trim()
22 .toLowerCase()
23 .replace(/['"`]/g, "")
24 .replace(/^[./\s_-]+|[./\s_-]+$/g, "");
25​
26 const branchFragment = normalized
27 .replace(/[^a-z0-9/_-]+/g, "-")
28 .replace(/\/+/g, "/")
29 .replace(/-+/g, "-")
30 .replace(/^[./_-]+|[./_-]+$/g, "")
31 .slice(0, 64)
32 .replace(/[./_-]+$/g, "");
33​
34 return branchFragment.length > 0 ? branchFragment : "update";
36​
37/**
38 * Sanitize a string into a `feature/…` branch name.
39 * Preserves an existing `feature/` prefix or slash-separated namespace.
40 */
41export function sanitizeFeatureBranchName(raw: string): string {
42 const sanitized = sanitizeBranchFragment(raw);
43 if (sanitized.includes("/")) {
44 return sanitized.startsWith("feature/") ? sanitized : `feature/${sanitized}`;
45 }
46 return `feature/${sanitized}`;
48​
49const AUTO_FEATURE_BRANCH_FALLBACK = "feature/update";
50​
51/**
52 * Resolve a unique `feature/…` branch name that doesn't collide with
53 * any existing branch. Appends a numeric suffix when needed.
54 */
55export function resolveAutoFeatureBranchName(
56 existingBranchNames: readonly string[],
57 preferredBranch?: string,
58): string {
59 const preferred = preferredBranch?.trim();
60 const resolvedBase = sanitizeFeatureBranchName(
61 preferred && preferred.length > 0 ? preferred : AUTO_FEATURE_BRANCH_FALLBACK,
62 );
63 const existingNames = new Set(existingBranchNames.map((branch) => branch.toLowerCase()));
64​
65 if (!existingNames.has(resolvedBase)) {
66 return resolvedBase;
67 }
68​
69 let suffix = 2;
70 while (existingNames.has(`${resolvedBase}-${suffix}`)) {
71 suffix += 1;
72 }
73​
74 return `${resolvedBase}-${suffix}`;
76​
77/**
78 * Strip the remote prefix from a remote ref such as `origin/feature/demo`.
79 */
80export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
81 const firstSeparatorIndex = branchName.indexOf("/");
82 if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
83 return branchName;
84 }
85 return branchName.slice(firstSeparatorIndex + 1);
87​
88export function buildTemporaryWorktreeBranchName(): string {
89 const token = Effect.runSync(Random.nextUUIDv4).replace(/-/g, "").slice(0, 8).toLowerCase();
90 return `${WORKTREE_BRANCH_PREFIX}/${token}`;
92​
93export function isTemporaryWorktreeBranch(branch: string): boolean {
94 return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase());
96​
97/**
98 * Normalize a git remote URL into a stable comparison key.
99 */
100export function normalizeGitRemoteUrl(value: string): string {
101 const normalized = value
102 .trim()
103 .replace(/\/+$/g, "")
104 .replace(/\.git$/i, "")
105 .toLowerCase();
106​
107 if (/^(?:ssh|https?|git):\/\//i.test(normalized)) {
108 try {
109 const url = new URL(normalized);
110 const repositoryPath = url.pathname
111 .split("/")
112 .filter((segment) => segment.length > 0)
113 .join("/");
114 if (url.hostname && repositoryPath.includes("/")) {
115 return `${url.hostname}/${repositoryPath}`;
116 }
117 } catch {
118 return normalized;
119 }
120 }
121​
122 const scpStyleHostAndPath = /^git@([^:/\s]+)[:/]([^/\s]+(?:\/[^/\s]+)+)$/i.exec(normalized);
123 if (scpStyleHostAndPath?.[1] && scpStyleHostAndPath[2]) {
124 return `${scpStyleHostAndPath[1]}/${scpStyleHostAndPath[2]}`;
125 }
126​
127 return normalized;
129​
130/**
131 * Best-effort parse of a GitHub `owner/repo` identifier from common remote URL shapes.
132 */
133export function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {
134 const trimmed = url?.trim() ?? "";
135 if (trimmed.length === 0) {
136 return null;
137 }
138​
139 const match =
140 /^(?:git@github\.com:|ssh:\/\/git@github\.com\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(
141 trimmed,
142 );
143 const repositoryNameWithOwner = match?.[1]?.trim() ?? "";
144 return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;
146​
147function deriveLocalBranchNameCandidatesFromRemoteRef(
148 branchName: string,
149 remoteName?: string,
150): ReadonlyArray<string> {
151 const candidates = new Set<string>();
152 const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
153 if (firstSlashCandidate.length > 0) {
154 candidates.add(firstSlashCandidate);
155 }
156​
157 if (remoteName) {
158 const remotePrefix = `${remoteName}/`;
159 if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
160 candidates.add(branchName.slice(remotePrefix.length));
161 }
162 }
163​
164 return [...candidates];
166​
167/**
168 * Hide `origin/*` remote refs when a matching local branch already exists.
169 */
170export function dedupeRemoteBranchesWithLocalMatches(
171 branches: ReadonlyArray<GitBranch>,
172): ReadonlyArray<GitBranch> {
173 const localBranchNames = new Set(
174 branches.filter((branch) => !branch.isRemote).map((branch) => branch.name),
175 );
176​
177 return branches.filter((branch) => {
178 if (!branch.isRemote) {
179 return true;
180 }
181​
182 if (branch.remoteName !== "origin") {
183 return true;
184 }
185​
186 const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
187 branch.name,
188 branch.remoteName,
189 );
190 return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
191 });
193​
194function parseGitRemoteHost(remoteUrl: string): string | null {
195 const trimmed = remoteUrl.trim();
196 if (trimmed.length === 0) {
197 return null;
198 }
199​
200 if (trimmed.startsWith("git@")) {
201 const hostWithPath = trimmed.slice("git@".length);
202 const separatorIndex = hostWithPath.search(/[:/]/);
203 if (separatorIndex <= 0) {
204 return null;
205 }
206 return hostWithPath.slice(0, separatorIndex).toLowerCase();
207 }
208​
209 try {
210 return new URL(trimmed).hostname.toLowerCase();
211 } catch {
212 return null;
213 }
215​
216function toBaseUrl(host: string): string {
217 return `https://${host}`;
219​
220function isGitHubHost(host: string): boolean {
221 return host === "github.com" || host.includes("github");
223​
224function isGitLabHost(host: string): boolean {
225 return host === "gitlab.com" || host.includes("gitlab");
227​
228export function detectGitHostingProviderFromRemoteUrl(
229 remoteUrl: string,
230): GitHostingProvider | null {
231 const host = parseGitRemoteHost(remoteUrl);
232 if (!host) {
233 return null;
234 }
235​
236 if (isGitHubHost(host)) {
237 return {
238 kind: "github",
239 name: host === "github.com" ? "GitHub" : "GitHub Self-Hosted",
240 baseUrl: toBaseUrl(host),
241 };
242 }
243​
244 if (isGitLabHost(host)) {
245 return {
246 kind: "gitlab",
247 name: host === "gitlab.com" ? "GitLab" : "GitLab Self-Hosted",
248 baseUrl: toBaseUrl(host),
249 };
250 }
251​
252 return {
253 kind: "unknown",
254 name: host,
255 baseUrl: toBaseUrl(host),
256 };
258​
259const EMPTY_GIT_STATUS_REMOTE: GitStatusRemoteResult = {
260 hasUpstream: false,
261 aheadCount: 0,
262 behindCount: 0,
263 pr: null,
264};
265​
266export function mergeGitStatusParts(
267 local: GitStatusLocalResult,
268 remote: GitStatusRemoteResult | null,
269): GitStatusResult {
270 return {
271 ...local,
272 ...(remote ?? EMPTY_GIT_STATUS_REMOTE),
273 };
275​
276function toRemoteStatusPart(status: GitStatusResult): GitStatusRemoteResult {
277 return {
278 hasUpstream: status.hasUpstream,
279 aheadCount: status.aheadCount,
280 behindCount: status.behindCount,
281 pr: status.pr,
282 };
284​
285function toLocalStatusPart(status: GitStatusResult): GitStatusLocalResult {
286 return {
287 isRepo: status.isRepo,
288 ...(status.hostingProvider ? { hostingProvider: status.hostingProvider } : {}),
289 hasOriginRemote: status.hasOriginRemote,
290 isDefaultBranch: status.isDefaultBranch,
291 branch: status.branch,
292 hasWorkingTreeChanges: status.hasWorkingTreeChanges,
293 workingTree: status.workingTree,
294 };
296​
297export function applyGitStatusStreamEvent(
298 current: GitStatusResult | null,
299 event: GitStatusStreamEvent,
300): GitStatusResult {
301 switch (event._tag) {
302 case "snapshot":
303 return mergeGitStatusParts(event.local, event.remote);
304 case "localUpdated":
305 return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);
306 case "remoteUpdated":
307 if (current === null) {
308 return mergeGitStatusParts(
309 {
310 isRepo: true,
311 hasOriginRemote: false,
312 isDefaultBranch: false,
313 branch: null,
314 hasWorkingTreeChanges: false,
315 workingTree: { files: [], insertions: 0, deletions: 0 },
316 },
317 event.remote,
318 );
319 }
320 return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
321 }