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

cloneUrl.ts

113 lines4.3 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 cloneUrlProtocol(url: string): CloneProtocol | null {
45 return parseCloneUrl(url)?.protocol ?? null;
47​
48/**
49 * Rewrites a clone URL to the other protocol, because the target machine may
50 * only have SSH keys or only an HTTPS credential helper. Returns null when the
51 * URL cannot be rewritten safely, such as a custom port.
52 */
53export function cloneUrlForProtocol(url: string, protocol: CloneProtocol): string | null {
54 const parsed = parseCloneUrl(url);
55 if (!parsed) return null;
56 if (parsed.protocol === protocol) return url.trim();
57 if (parsed.customPort) return null;
58 // Azure's transports use different hosts and put the repository marker in
59 // different positions; changing only the scheme produces an invalid clone URL.
60 if (parsed.protocol === "ssh" && parsed.host.toLowerCase() === "ssh.dev.azure.com") {
61 const azure = /^v3\/([^/?#]+)\/([^/?#]+)\/([^/?#]+)$/.exec(parsed.path);
62 return azure ? `https://dev.azure.com/${azure[1]}/${azure[2]}/_git/${azure[3]}` : null;
63 }
64 if (parsed.protocol === "https" && parsed.host.toLowerCase() === "dev.azure.com") {
65 const azure = /^([^/?#]+)\/([^/?#]+)\/_git\/([^/?#]+)$/.exec(parsed.path);
66 return azure ? `git@ssh.dev.azure.com:v3/${azure[1]}/${azure[2]}/${azure[3]}` : null;
67 }
68 // Bitbucket Cloud serves SSH only from `ssh.bitbucket.org` and HTTPS only from `bitbucket.org`.
69 const host = /^(?:(?:alt)?ssh\.)?bitbucket\.org$/i.test(parsed.host)
70 ? protocol === "ssh"
71 ? "ssh.bitbucket.org"
72 : "bitbucket.org"
73 : parsed.host;
74 // SCP paths are literal; URI paths use percent escapes.
75 try {
76 if (protocol === "ssh") return `git@${host}:${decodeURIComponent(parsed.path)}`;
77 const path = parsed.scp
78 ? parsed.path.split("/").map(encodeURIComponent).join("/")
79 : parsed.path;
80 return `https://${host}/${path}`;
81 } catch {
82 return null;
83 }
85​
86const UNSAFE_SEGMENT = /^\.{1,2}$|[\\:*?"<>|\p{Cc}]|[ .]$/u;
87const WINDOWS_DEVICE_NAME =
88 /^(?:con|prn|aux|nul|conin\$|conout\$|com[0-9¹²³]|lpt[0-9¹²³])(?: *\.| *$)/i;
89​
90/**
91 * The `<host>/<owner>/<repo>` folders ghq clones a URL into, or null for local paths and
92 * anything with a folder that could leave the root.
93 */
94export function cloneUrlRepositoryPath(url: string): string | null {
95 if (isWindowsDrivePath(url.trim())) return null;
96 const parsed = parseCloneUrl(url);
97 if (!parsed) return null;
98 let repositoryPath = parsed.path.split(/[?#]/)[0]!;
99 try {
100 if (!parsed.scp) repositoryPath = decodeURIComponent(repositoryPath);
101 } catch {
102 return null;
103 }
104 const segments = [parsed.host, ...repositoryPath.split("/").filter(Boolean)];
105 const last = segments.at(-1)!;
106 if (last.endsWith(".git")) segments[segments.length - 1] = last.slice(0, -".git".length);
107 if (
108 segments.length < 2 ||
109 segments.some((s) => s === "" || UNSAFE_SEGMENT.test(s) || WINDOWS_DEVICE_NAME.test(s))
110 )
111 return null;
112 return segments.join("/");