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

cloneUrl.ts

37 lines1.5 KB

1export type CloneProtocol = "ssh" | "https";
2​
3const SCP_LIKE_URL = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/)(.+)$/;
4const SSH_URL = /^ssh:\/\/(?:[^@/\s]+@)?([^:/\s]+)(:\d+)?\/(.+)$/;
5const HTTPS_URL = /^https?:\/\/(?:[^@/\s]+@)?([^:/\s]+)(:\d+)?\/(.+)$/;
6​
7function parseCloneUrl(
8 url: string,
9): { protocol: CloneProtocol; host: string; path: string; customPort: boolean } | null {
10 const trimmed = url.trim();
11 const ssh = SSH_URL.exec(trimmed);
12 if (ssh) return { protocol: "ssh", host: ssh[1]!, path: ssh[3]!, customPort: !!ssh[2] };
13 const https = HTTPS_URL.exec(trimmed);
14 if (https) return { protocol: "https", host: https[1]!, path: https[3]!, customPort: !!https[2] };
15 const scp = SCP_LIKE_URL.exec(trimmed);
16 if (scp) return { protocol: "ssh", host: scp[1]!, path: scp[2]!, customPort: false };
17 return null;
19​
20export function cloneUrlProtocol(url: string): CloneProtocol | null {
21 return parseCloneUrl(url)?.protocol ?? null;
23​
24/**
25 * Rewrites a clone URL to the other protocol, because the target machine may
26 * only have SSH keys or only an HTTPS credential helper. Returns null when the
27 * URL cannot be rewritten safely, such as a custom port.
28 */
29export function cloneUrlForProtocol(url: string, protocol: CloneProtocol): string | null {
30 const parsed = parseCloneUrl(url);
31 if (!parsed) return null;
32 if (parsed.protocol === protocol) return url.trim();
33 if (parsed.customPort) return null;
34 return protocol === "ssh"
35 ? `git@${parsed.host}:${parsed.path}`
36 : `https://${parsed.host}/${parsed.path}`;