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]+):(?!\/)(.+)$/;
6const SSH_URL = /^ssh:\/\/(?:[^@/\s]+@)?([^:/\s]+)(:\d+)?\/(.+)$/;
7const HTTPS_URL = /^https?:\/\/(?:[^@/\s]+@)?([^:/\s]+)(:\d+)?\/(.+)$/;
8
9function parseCloneUrl(
10 url: string,
11): { protocol: CloneProtocol; host: string; path: string; customPort: boolean } | null {
12 const trimmed = url.trim();
13 const ssh = SSH_URL.exec(trimmed);
14 if (ssh) return { protocol: "ssh", host: ssh[1]!, path: ssh[3]!, customPort: !!ssh[2] };
15 const https = HTTPS_URL.exec(trimmed);
16 if (https) return { protocol: "https", host: https[1]!, path: https[3]!, customPort: !!https[2] };
17 const scp = SCP_LIKE_URL.exec(trimmed);
18 if (scp) return { protocol: "ssh", host: scp[1]!, path: scp[2]!, customPort: false };
19 return null;
20}
21
22export function cloneUrlProtocol(url: string): CloneProtocol | null {
23 return parseCloneUrl(url)?.protocol ?? null;
24}
25
26/**
27 * Rewrites a clone URL to the other protocol, because the target machine may
28 * only have SSH keys or only an HTTPS credential helper. Returns null when the
29 * URL cannot be rewritten safely, such as a custom port.
30 */
31export function cloneUrlForProtocol(url: string, protocol: CloneProtocol): string | null {
32 const parsed = parseCloneUrl(url);
33 if (!parsed) return null;
34 if (parsed.protocol === protocol) return url.trim();
35 if (parsed.customPort) return null;
36 return protocol === "ssh"
37 ? `git@${parsed.host}:${parsed.path}`
38 : `https://${parsed.host}/${parsed.path}`;
39}
40
41const UNSAFE_SEGMENT = /^\.{1,2}$|[\\:*?"<>|\p{Cc}]|[ .]$/u;
42const WINDOWS_DEVICE_NAME =
43 /^(?:con|prn|aux|nul|conin\$|conout\$|com[0-9¹²³]|lpt[0-9¹²³])(?: *\.| *$)/i;
44
45/**
46 * The `<host>/<owner>/<repo>` folders ghq clones a URL into, or null for local paths and
47 * anything with a folder that could leave the root.
48 */
49export function cloneUrlRepositoryPath(url: string): string | null {
50 if (isWindowsDrivePath(url.trim())) return null;
51 const parsed = parseCloneUrl(url);
52 if (!parsed) return null;
53 const segments = [parsed.host, ...parsed.path.split(/[?#]/)[0]!.split("/").filter(Boolean)];
54 const last = segments.at(-1)!;
55 if (last.endsWith(".git")) segments[segments.length - 1] = last.slice(0, -".git".length);
56 if (
57 segments.length < 2 ||
58 segments.some((s) => s === "" || UNSAFE_SEGMENT.test(s) || WINDOWS_DEVICE_NAME.test(s))
59 )
60 return null;
61 return segments.join("/");
62}