Open History to see the last commit
1export type CloneProtocol = "ssh" | "https";
2
3const SCP_LIKE_URL = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/)(.+)$/;
4// Userinfo may contain `@`; the last one before the first slash separates the host.
5const SSH_URL = /^ssh:\/\/(?:[^/\s]*@)?([^@:/\s]+)(:\d+)?\/(.+)$/;
6const HTTPS_URL = /^https?:\/\/(?:[^/\s]*@)?([^@:/\s]+)(:\d+)?\/(.+)$/;
7
8function parseCloneUrl(
9 url: string,
10): { protocol: CloneProtocol; host: string; path: string; customPort: boolean } | null {
11 const trimmed = url.trim();
12 const ssh = SSH_URL.exec(trimmed);
13 if (ssh) return { protocol: "ssh", host: ssh[1]!, path: ssh[3]!, customPort: !!ssh[2] };
14 const https = HTTPS_URL.exec(trimmed);
15 if (https) return { protocol: "https", host: https[1]!, path: https[3]!, customPort: !!https[2] };
16 const scp = SCP_LIKE_URL.exec(trimmed);
17 if (scp) return { protocol: "ssh", host: scp[1]!, path: scp[2]!, customPort: false };
18 return null;
19}
20
21export function cloneUrlProtocol(url: string): CloneProtocol | null {
22 return parseCloneUrl(url)?.protocol ?? null;
23}
24
25/**
26 * Rewrites a clone URL to the other protocol, because the target machine may
27 * only have SSH keys or only an HTTPS credential helper. Returns null when the
28 * URL cannot be rewritten safely, such as a custom port.
29 */
30export function cloneUrlForProtocol(url: string, protocol: CloneProtocol): string | null {
31 const parsed = parseCloneUrl(url);
32 if (!parsed) return null;
33 if (parsed.protocol === protocol) return url.trim();
34 if (parsed.customPort) return null;
35 // Azure's transports use different hosts and put the repository marker in
36 // different positions; changing only the scheme produces an invalid clone URL.
37 if (parsed.protocol === "ssh" && parsed.host.toLowerCase() === "ssh.dev.azure.com") {
38 const azure = /^v3\/([^/?#]+)\/([^/?#]+)\/([^/?#]+)$/.exec(parsed.path);
39 return azure ? `https://dev.azure.com/${azure[1]}/${azure[2]}/_git/${azure[3]}` : null;
40 }
41 if (parsed.protocol === "https" && parsed.host.toLowerCase() === "dev.azure.com") {
42 const azure = /^([^/?#]+)\/([^/?#]+)\/_git\/([^/?#]+)$/.exec(parsed.path);
43 return azure ? `git@ssh.dev.azure.com:v3/${azure[1]}/${azure[2]}/${azure[3]}` : null;
44 }
45 return protocol === "ssh"
46 ? `git@${parsed.host}:${parsed.path}`
47 : `https://${parsed.host}/${parsed.path}`;
48}