chainguard_sandbox/workspaces/
repourl.rs1pub fn normalize_github_url(u: &str) -> String {
8 let u = u.trim();
9 let (host, p, kind) = split_remote(u);
10 let p = p.trim_matches('/');
11 let p = p.strip_suffix(".git").unwrap_or(p);
12 let h = host.to_lowercase();
13 if h == "github.com" || h == "www.github.com" {
14 return format!("https://github.com/{p}");
15 }
16 match kind {
17 Kind::Url => match url::Url::parse(u) {
18 Ok(mut pu) => {
19 let _ = pu.set_username("");
20 let _ = pu.set_password(None);
21 let path = pu.path().to_string();
22 let path = path.strip_suffix('/').unwrap_or(&path);
23 let path = path.strip_suffix(".git").unwrap_or(path).to_string();
24 pu.set_path(&path);
25 let s = pu.to_string();
26 if path.is_empty() {
28 s.trim_end_matches('/').to_string()
29 } else {
30 s
31 }
32 }
33 Err(_) => u.to_string(),
34 },
35 Kind::Scp => u.to_string(),
36 Kind::Bare => {
37 let t = u.strip_suffix('/').unwrap_or(u);
38 t.strip_suffix(".git").unwrap_or(t).to_string()
39 }
40 }
41}
42
43enum Kind {
44 Bare,
46 Url,
48 Scp,
50}
51
52fn split_remote(u: &str) -> (String, String, Kind) {
53 if u.contains("://") {
54 return match url::Url::parse(u) {
55 Ok(pu) => (
56 pu.host_str()
57 .unwrap_or_default()
58 .trim_matches(['[', ']'])
59 .to_string(),
60 pu.path().to_string(),
61 Kind::Url,
62 ),
63 Err(_) => (String::new(), u.to_string(), Kind::Url),
64 };
65 }
66 if is_scp_like(u) {
67 let (host_part, p) = u.split_once(':').unwrap_or((u, ""));
68 let host_part = host_part
69 .split_once('@')
70 .map(|(_, h)| h)
71 .unwrap_or(host_part);
72 return (host_part.to_string(), p.to_string(), Kind::Scp);
73 }
74 let (host, p) = u.split_once('/').unwrap_or((u, ""));
75 (host.to_string(), p.to_string(), Kind::Bare)
76}
77
78pub(crate) fn is_scp_like(u: &str) -> bool {
80 match u.find(':') {
81 Some(i) => i > 0 && !u[..i].contains('/') && !u.contains("://"),
82 None => false,
83 }
84}
85
86#[cfg(test)]
87mod tests {
88 use super::*;
89
90 #[test]
91 fn normalizes_github_forms() {
92 for i in [
93 "git@github.com:o/r.git",
94 "ssh://git@github.com:22/o/r",
95 "git://github.com/o/r",
96 "https://token@GitHub.com/o/r.git",
97 "github.com/o/r",
98 " https://www.github.com/o/r/ ",
99 ] {
100 assert_eq!(normalize_github_url(i), "https://github.com/o/r", "{i}");
101 }
102 assert_eq!(
103 normalize_github_url("https://u:p@gitlab.com/o/r.git"),
104 "https://gitlab.com/o/r"
105 );
106 assert_eq!(
107 normalize_github_url("git@gitlab.com:o/r.git"),
108 "git@gitlab.com:o/r.git"
109 );
110 assert_eq!(
111 super::super::repository_url("gitlab.com/o/r"),
112 "https://gitlab.com/o/r"
113 );
114 }
115}