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

cloneUrl.ts

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