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

cloneUrl.ts

117 lines4.4 KB

1import { isWindowsDrivePath } from "./path.ts";
2​
3export type CloneProtocol = "ssh" | "https";
4​
5const SCP_LIKE_URL = /^(?:[^@/\s]+@)?(\[[^\]@/\s]+\]|[^:/\s[\]]+):(?!\/)(.+)$/;
6// Userinfo may contain `@`; the last one before the first slash separates the host.
7const SSH_URL = /^ssh:\/\/(?:[^/\s]*@)?(\[[^\]@/\s]+\]|[^@:/\s]+)(:\d+)?\/(.+)$/;
8const HTTPS_URL = /^https?:\/\/(?:[^/\s]*@)?(\[[^\]@/\s]+\]|[^@:/\s]+)(:\d+)?\/(.+)$/;
9​
10function parseCloneUrl(url: string): {
11 protocol: CloneProtocol;
12 host: string;
13 path: string;
14 customPort: boolean;
15 scp: boolean;
16} | null {
17 const trimmed = url.trim();
18 const ssh = SSH_URL.exec(trimmed);
19 if (ssh)
20 return { protocol: "ssh", host: ssh[1]!, path: ssh[3]!, customPort: !!ssh[2], scp: false };
21 const https = HTTPS_URL.exec(trimmed);
22 if (https)
23 return {
24 protocol: "https",
25 host: https[1]!,
26 path: https[3]!,
27 customPort: !!https[2],
28 scp: false,
29 };
30 const scp = SCP_LIKE_URL.exec(trimmed);
31 if (scp) return { protocol: "ssh", host: scp[1]!, path: scp[2]!, customPort: false, scp: true };
32 return null;
34​
35/**
36 * Drops what an HTTP(S) remote can carry as a login: userinfo and the query. SSH URLs keep
37 * their user, which is part of the address.
38 */
39export function withoutRemoteUrlCredentials(url: string): string {
40 if (!/^https?:\/\//i.test(url)) return url;
41 return url.replace(/^(https?:\/\/)[^/?#]*@/i, "$1").replace(/\?[^#]*/, "");
43​
44export function isScpLikeCloneUrl(url: string): boolean {
45 return SCP_LIKE_URL.test(url);
47​
48export function cloneUrlProtocol(url: string): CloneProtocol | null {
49 return parseCloneUrl(url)?.protocol ?? null;
51​
52/**
53 * Rewrites a clone URL to the other protocol, because the target machine may
54 * only have SSH keys or only an HTTPS credential helper. Returns null when the
55 * URL cannot be rewritten safely, such as a custom port.
56 */
57export function cloneUrlForProtocol(url: string, protocol: CloneProtocol): string | null {
58 const parsed = parseCloneUrl(url);
59 if (!parsed) return null;
60 if (parsed.protocol === protocol) return url.trim();
61 if (parsed.customPort) return null;
62 // Azure's transports use different hosts and put the repository marker in
63 // different positions; changing only the scheme produces an invalid clone URL.
64 if (parsed.protocol === "ssh" && parsed.host.toLowerCase() === "ssh.dev.azure.com") {
65 const azure = /^v3\/([^/?#]+)\/([^/?#]+)\/([^/?#]+)$/.exec(parsed.path);
66 return azure ? `https://dev.azure.com/${azure[1]}/${azure[2]}/_git/${azure[3]}` : null;
67 }
68 if (parsed.protocol === "https" && parsed.host.toLowerCase() === "dev.azure.com") {
69 const azure = /^([^/?#]+)\/([^/?#]+)\/_git\/([^/?#]+)$/.exec(parsed.path);
70 return azure ? `git@ssh.dev.azure.com:v3/${azure[1]}/${azure[2]}/${azure[3]}` : null;
71 }
72 // Bitbucket Cloud serves SSH only from `ssh.bitbucket.org` and HTTPS only from `bitbucket.org`.
73 const host = /^(?:(?:alt)?ssh\.)?bitbucket\.org$/i.test(parsed.host)
74 ? protocol === "ssh"
75 ? "ssh.bitbucket.org"
76 : "bitbucket.org"
77 : parsed.host;
78 // SCP paths are literal; URI paths use percent escapes.
79 try {
80 if (protocol === "ssh") return `git@${host}:${decodeURIComponent(parsed.path)}`;
81 const path = parsed.scp
82 ? parsed.path.split("/").map(encodeURIComponent).join("/")
83 : parsed.path;
84 return `https://${host}/${path}`;
85 } catch {
86 return null;
87 }
89​
90const UNSAFE_SEGMENT = /^\.{1,2}$|[\\:*?"<>|\p{Cc}]|[ .]$/u;
91const WINDOWS_DEVICE_NAME =
92 /^(?:con|prn|aux|nul|conin\$|conout\$|com[0-9¹²³]|lpt[0-9¹²³])(?: *\.| *$)/i;
93​
94/**
95 * The `<host>/<owner>/<repo>` folders ghq clones a URL into, or null for local paths and
96 * anything with a folder that could leave the root.
97 */
98export function cloneUrlRepositoryPath(url: string): string | null {
99 if (isWindowsDrivePath(url.trim())) return null;
100 const parsed = parseCloneUrl(url);
101 if (!parsed) return null;
102 let repositoryPath = parsed.path.split(parsed.scp ? "?" : /[?#]/, 1)[0]!;
103 try {
104 if (!parsed.scp) repositoryPath = decodeURIComponent(repositoryPath);
105 } catch {
106 return null;
107 }
108 const segments = [parsed.host, ...repositoryPath.split("/").filter(Boolean)];
109 const last = segments.at(-1)!;
110 if (last.endsWith(".git")) segments[segments.length - 1] = last.slice(0, -".git".length);
111 if (
112 segments.length < 2 ||
113 segments.some((s) => s === "" || UNSAFE_SEGMENT.test(s) || WINDOWS_DEVICE_NAME.test(s))
114 )
115 return null;
116 return segments.join("/");