Open History to see the last commit
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";
30}
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}`;
42}
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}`;
70}
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);
81}
82
83function deriveLocalBranchNameCandidatesFromRemoteRef(
84 branchName: string,
85 remoteName?: string,
86): ReadonlyArray<string> {
87 const candidates = new Set<string>();
88 const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
89 if (firstSlashCandidate.length > 0) {
90 candidates.add(firstSlashCandidate);
91 }
92
93 if (remoteName) {
94 const remotePrefix = `${remoteName}/`;
95 if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
96 candidates.add(branchName.slice(remotePrefix.length));
97 }
98 }
99
100 return [...candidates];
101}
102
103/**
104 * Hide `origin/*` remote refs when a matching local branch already exists.
105 */
106export function dedupeRemoteBranchesWithLocalMatches(
107 branches: ReadonlyArray<GitBranch>,
108): ReadonlyArray<GitBranch> {
109 const localBranchNames = new Set(
110 branches.filter((branch) => !branch.isRemote).map((branch) => branch.name),
111 );
112
113 return branches.filter((branch) => {
114 if (!branch.isRemote) {
115 return true;
116 }
117
118 if (branch.remoteName !== "origin") {
119 return true;
120 }
121
122 const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
123 branch.name,
124 branch.remoteName,
125 );
126 return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
127 });
128}
129
130function parseGitRemoteHost(remoteUrl: string): string | null {
131 const trimmed = remoteUrl.trim();
132 if (trimmed.length === 0) {
133 return null;
134 }
135
136 if (trimmed.startsWith("git@")) {
137 const hostWithPath = trimmed.slice("git@".length);
138 const separatorIndex = hostWithPath.search(/[:/]/);
139 if (separatorIndex <= 0) {
140 return null;
141 }
142 return hostWithPath.slice(0, separatorIndex).toLowerCase();
143 }
144
145 try {
146 return new URL(trimmed).hostname.toLowerCase();
147 } catch {
148 return null;
149 }
150}
151
152function toBaseUrl(host: string): string {
153 return `https://${host}`;
154}
155
156function isGitHubHost(host: string): boolean {
157 return host === "github.com" || host.includes("github");
158}
159
160function isGitLabHost(host: string): boolean {
161 return host === "gitlab.com" || host.includes("gitlab");
162}
163
164export function detectGitHostingProviderFromRemoteUrl(
165 remoteUrl: string,
166): GitHostingProvider | null {
167 const host = parseGitRemoteHost(remoteUrl);
168 if (!host) {
169 return null;
170 }
171
172 if (isGitHubHost(host)) {
173 return {
174 kind: "github",
175 name: host === "github.com" ? "GitHub" : "GitHub Self-Hosted",
176 baseUrl: toBaseUrl(host),
177 };
178 }
179
180 if (isGitLabHost(host)) {
181 return {
182 kind: "gitlab",
183 name: host === "gitlab.com" ? "GitLab" : "GitLab Self-Hosted",
184 baseUrl: toBaseUrl(host),
185 };
186 }
187
188 return {
189 kind: "unknown",
190 name: host,
191 baseUrl: toBaseUrl(host),
192 };
193}
194
195const EMPTY_GIT_STATUS_REMOTE: GitStatusRemoteResult = {
196 hasUpstream: false,
197 aheadCount: 0,
198 behindCount: 0,
199 pr: null,
200};
201
202export function mergeGitStatusParts(
203 local: GitStatusLocalResult,
204 remote: GitStatusRemoteResult | null,
205): GitStatusResult {
206 return {
207 ...local,
208 ...(remote ?? EMPTY_GIT_STATUS_REMOTE),
209 };
210}
211
212function toRemoteStatusPart(status: GitStatusResult): GitStatusRemoteResult {
213 return {
214 hasUpstream: status.hasUpstream,
215 aheadCount: status.aheadCount,
216 behindCount: status.behindCount,
217 pr: status.pr,
218 };
219}
220
221function toLocalStatusPart(status: GitStatusResult): GitStatusLocalResult {
222 return {
223 isRepo: status.isRepo,
224 ...(status.hostingProvider ? { hostingProvider: status.hostingProvider } : {}),
225 hasOriginRemote: status.hasOriginRemote,
226 isDefaultBranch: status.isDefaultBranch,
227 branch: status.branch,
228 hasWorkingTreeChanges: status.hasWorkingTreeChanges,
229 workingTree: status.workingTree,
230 };
231}
232
233export function applyGitStatusStreamEvent(
234 current: GitStatusResult | null,
235 event: GitStatusStreamEvent,
236): GitStatusResult {
237 switch (event._tag) {
238 case "snapshot":
239 return mergeGitStatusParts(event.local, event.remote);
240 case "localUpdated":
241 return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);
242 case "remoteUpdated":
243 if (current === null) {
244 return mergeGitStatusParts(
245 {
246 isRepo: true,
247 hasOriginRemote: false,
248 isDefaultBranch: false,
249 branch: null,
250 hasWorkingTreeChanges: false,
251 workingTree: { files: [], insertions: 0, deletions: 0 },
252 },
253 event.remote,
254 );
255 }
256 return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
257 }
258}