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

git.ts

293 lines8.8 KB

1import type {
2 VcsRef,
3 SourceControlProviderInfo,
4 VcsStatusLocalResult,
5 VcsStatusRemoteResult,
6 VcsStatusResult,
7 VcsStatusStreamEvent,
8} from "@t3tools/contracts";
9import * as Arr from "effect/Array";
10import * as Result from "effect/Result";
11import {
12 canonicalizeSshRemoteHostname,
13 detectSourceControlProviderFromRemoteUrl,
14} from "./sourceControl.ts";
15​
16export const WORKTREE_BRANCH_PREFIX = "t3code";
17// Canonical form is `t3code/<8 hex>`. Older mobile builds generated `t3code/<uuid>`
18// via Crypto.randomUUID() (always RFC 4122 v4), so the matcher also accepts exactly
19// that shape — version nibble `4`, variant nibble `[89ab]` — to keep those threads
20// eligible for branch regeneration without loosening beyond what was ever generated.
21const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(
22 `^${WORKTREE_BRANCH_PREFIX}\\/(?:[0-9a-f]{8}|[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$`,
23);
24​
25/**
26 * Sanitize an arbitrary string into a valid, lowercase git refName fragment.
27 * Strips quotes, collapses separators, limits to 64 chars.
28 */
29export function sanitizeBranchFragment(raw: string): string {
30 const normalized = raw
31 .trim()
32 .toLowerCase()
33 .replace(/['"`]/g, "")
34 .replace(/^[./\s_-]+|[./\s_-]+$/g, "");
35​
36 const branchFragment = normalized
37 .replace(/[^a-z0-9/_-]+/g, "-")
38 .replace(/\/+/g, "/")
39 .replace(/-+/g, "-")
40 .replace(/^[./_-]+|[./_-]+$/g, "")
41 .slice(0, 64)
42 .replace(/[./_-]+$/g, "");
43​
44 return branchFragment.length > 0 ? branchFragment : "update";
46​
47/**
48 * Sanitize a string into a `feature/…` refName name.
49 * Preserves an existing `feature/` prefix or slash-separated namespace.
50 */
51export function sanitizeFeatureBranchName(raw: string): string {
52 const sanitized = sanitizeBranchFragment(raw);
53 if (sanitized.includes("/")) {
54 return sanitized.startsWith("feature/") ? sanitized : `feature/${sanitized}`;
55 }
56 return `feature/${sanitized}`;
58​
59const AUTO_FEATURE_BRANCH_FALLBACK = "feature/update";
60​
61/**
62 * Resolve a unique `feature/…` refName name that doesn't collide with
63 * any existing refName. Appends a numeric suffix when needed.
64 */
65export function resolveAutoFeatureBranchName(
66 existingBranchNames: readonly string[],
67 preferredBranch?: string,
68): string {
69 const preferred = preferredBranch?.trim();
70 const resolvedBase = sanitizeFeatureBranchName(
71 preferred && preferred.length > 0 ? preferred : AUTO_FEATURE_BRANCH_FALLBACK,
72 );
73 const existingNames = new Set(existingBranchNames.map((refName) => refName.toLowerCase()));
74​
75 if (!existingNames.has(resolvedBase)) {
76 return resolvedBase;
77 }
78​
79 let suffix = 2;
80 while (existingNames.has(`${resolvedBase}-${suffix}`)) {
81 suffix += 1;
82 }
83​
84 return `${resolvedBase}-${suffix}`;
86​
87/**
88 * Strip the remote prefix from a remote ref such as `origin/feature/demo`.
89 */
90export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
91 const firstSeparatorIndex = branchName.indexOf("/");
92 if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
93 return branchName;
94 }
95 return branchName.slice(firstSeparatorIndex + 1);
97​
98export function buildTemporaryWorktreeBranchName(
99 randomHex: (byteLength: number) => string,
100): string {
101 // Normalize to exactly 8 lowercase hex chars so a UUID-shaped callback
102 // still produces the canonical temporary branch form.
103 const token = randomHex(4)
104 .toLowerCase()
105 .replace(/[^0-9a-f]/g, "")
106 .slice(0, 8);
107 return `${WORKTREE_BRANCH_PREFIX}/${token}`;
109​
110export function isTemporaryWorktreeBranch(refName: string): boolean {
111 return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase());
113​
114/**
115 * Normalize a git remote URL into a stable comparison key.
116 */
117export function normalizeGitRemoteUrl(value: string): string {
118 const normalized = value
119 .trim()
120 .replace(/\/+$/g, "")
121 .replace(/\.git$/i, "")
122 .toLowerCase();
123​
124 if (/^(?:ssh|https?|git):\/\//i.test(normalized)) {
125 try {
126 const url = new URL(normalized);
127 const repositoryPath = url.pathname
128 .split("/")
129 .filter((segment) => segment.length > 0)
130 .join("/");
131 if (url.hostname && repositoryPath.includes("/")) {
132 const hostname =
133 url.protocol === "ssh:" ? canonicalizeSshRemoteHostname(url.hostname) : url.hostname;
134 return `${hostname}/${repositoryPath}`;
135 }
136 } catch {
137 return normalized;
138 }
139 }
140​
141 const scpStyleHostAndPath = /^[a-zA-Z0-9._-]+@([^:/\s]+):([^/\s]+(?:\/[^/\s]+)+)$/i.exec(
142 normalized,
143 );
144 if (scpStyleHostAndPath?.[1] && scpStyleHostAndPath[2]) {
145 return `${canonicalizeSshRemoteHostname(scpStyleHostAndPath[1])}/${scpStyleHostAndPath[2]}`;
146 }
147​
148 return normalized;
150​
151/**
152 * Best-effort parse of a GitHub `owner/repo` identifier from common remote URL shapes.
153 */
154export function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {
155 const trimmed = url?.trim() ?? "";
156 if (trimmed.length === 0) {
157 return null;
158 }
159​
160 // SSH shapes tolerate a multi-account alias suffix such as `github.com-work`.
161 const match =
162 /^(?:git@github\.com(?:-[^./:\s]+)?:|ssh:\/\/git@github\.com(?:-[^./\s]+)?\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(
163 trimmed,
164 );
165 const repositoryNameWithOwner = match?.[1]?.trim() ?? "";
166 return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;
168​
169function deriveLocalBranchNameCandidatesFromRemoteRef(
170 branchName: string,
171 remoteName?: string,
172): ReadonlyArray<string> {
173 const candidates = new Set<string>();
174 const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
175 if (firstSlashCandidate.length > 0) {
176 candidates.add(firstSlashCandidate);
177 }
178​
179 if (remoteName) {
180 const remotePrefix = `${remoteName}/`;
181 if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
182 candidates.add(branchName.slice(remotePrefix.length));
183 }
184 }
185​
186 return [...candidates];
188​
189/**
190 * Hide `origin/*` remote refs when a matching local refName already exists.
191 */
192export function dedupeRemoteBranchesWithLocalMatches(
193 refs: ReadonlyArray<VcsRef>,
194): ReadonlyArray<VcsRef> {
195 const localBranchNames = new Set(
196 Arr.filterMap(refs, (refName) =>
197 refName.isRemote ? Result.failVoid : Result.succeed(refName.name),
198 ),
199 );
200​
201 return refs.filter((refName) => {
202 if (!refName.isRemote) {
203 return true;
204 }
205​
206 if (refName.remoteName !== "origin") {
207 return true;
208 }
209​
210 const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
211 refName.name,
212 refName.remoteName,
213 );
214 return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
215 });
217​
218export function detectSourceControlProviderFromGitRemoteUrl(
219 remoteUrl: string,
220): SourceControlProviderInfo | null {
221 return detectSourceControlProviderFromRemoteUrl(remoteUrl);
223​
224const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
225 hasUpstream: false,
226 aheadCount: 0,
227 behindCount: 0,
228 aheadOfDefaultCount: 0,
229 pr: null,
230};
231​
232export function mergeGitStatusParts(
233 local: VcsStatusLocalResult,
234 remote: VcsStatusRemoteResult | null,
235): VcsStatusResult {
236 return {
237 ...local,
238 ...(remote ?? EMPTY_GIT_STATUS_REMOTE),
239 };
241​
242function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
243 return {
244 hasUpstream: status.hasUpstream,
245 aheadCount: status.aheadCount,
246 behindCount: status.behindCount,
247 ...(status.aheadOfDefaultCount === undefined
248 ? {}
249 : { aheadOfDefaultCount: status.aheadOfDefaultCount }),
250 pr: status.pr,
251 };
253​
254function toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult {
255 return {
256 isRepo: status.isRepo,
257 ...(status.sourceControlProvider
258 ? { sourceControlProvider: status.sourceControlProvider }
259 : {}),
260 hasPrimaryRemote: status.hasPrimaryRemote,
261 isDefaultRef: status.isDefaultRef,
262 refName: status.refName,
263 hasWorkingTreeChanges: status.hasWorkingTreeChanges,
264 workingTree: status.workingTree,
265 };
267​
268export function applyGitStatusStreamEvent(
269 current: VcsStatusResult | null,
270 event: VcsStatusStreamEvent,
271): VcsStatusResult {
272 switch (event._tag) {
273 case "snapshot":
274 return mergeGitStatusParts(event.local, event.remote);
275 case "localUpdated":
276 return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);
277 case "remoteUpdated":
278 if (current === null) {
279 return mergeGitStatusParts(
280 {
281 isRepo: true,
282 hasPrimaryRemote: false,
283 isDefaultRef: false,
284 refName: null,
285 hasWorkingTreeChanges: false,
286 workingTree: { files: [], insertions: 0, deletions: 0 },
287 },
288 event.remote,
289 );
290 }
291 return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
292 }