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

git.ts

308 lines8.2 KB

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