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