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

cloneUrl.ts

139 lines5.5 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. For folder suggestions, a `?key=` after a slash, after the
96 * first `.git` leaf, or as the first repository-page key (`ref`, `branch`, or `view`) starts
97 * a pasted query, whose value may itself end in `.git`.
98 */
99export function withoutScpQuery(path: string): string {
100 const withoutSeparatedQuery = path.replace(/(?<=\/)\?[^/?=]+=.*$/, "");
101 if (withoutSeparatedQuery !== path) return withoutSeparatedQuery;
102​
103 const query =
104 /^(.*?\.git\/*)\?[^/?=]+=/i.exec(path) ?? /^(.*?[^/?])\?(?:ref|branch|view)=/.exec(path);
105 return query ? query[1]! : path.replace(/\?[^/]*\/*$/, "");
107​
108const UNSAFE_SEGMENT = /^\.{1,2}$|[\\:*?"<>|\p{Cc}]|[ .]$/u;
109const WINDOWS_DEVICE_NAME =
110 /^(?:con|prn|aux|nul|conin\$|conout\$|com[0-9¹²³]|lpt[0-9¹²³])(?: *\.| *$)/i;
111​
112/**
113 * The `<host>/<owner>/<repo>` folders ghq clones a URL into, or null for local paths and
114 * anything with a folder that could leave the root.
115 */
116export function cloneUrlRepositoryPath(url: string): string | null {
117 const parsed = parseCloneUrl(url);
118 if (!parsed) return null;
119 let repositoryPath = parsed.scp
120 ? withoutScpQuery(parsed.path)
121 : parsed.protocol === "ssh"
122 ? // Git sends `#` in an ssh:// path and keeps a `%` that starts no escape as typed.
123 parsed.path.split("?", 1)[0]!.replace(/%(?![\da-f]{2})/gi, "%25")
124 : parsed.path.split(/[?#]/, 1)[0]!;
125 try {
126 if (!parsed.scp) repositoryPath = decodeURIComponent(repositoryPath);
127 } catch {
128 return null;
129 }
130 const segments = [parsed.host, ...repositoryPath.split("/").filter(Boolean)];
131 const last = segments.at(-1)!;
132 if (last.endsWith(".git")) segments[segments.length - 1] = last.slice(0, -".git".length);
133 if (
134 segments.length < 2 ||
135 segments.some((s) => s === "" || UNSAFE_SEGMENT.test(s) || WINDOWS_DEVICE_NAME.test(s))
136 )
137 return null;
138 return segments.join("/");