1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
use anyhow::Result;
use log::debug;
use regex::Regex;
use std::fmt;
use std::str::FromStr;
use strum_macros::{EnumString, EnumVariantNames};
use url::Url;
#[derive(Debug, PartialEq, EnumString, EnumVariantNames)]
#[strum(serialize_all = "kebab_case")]
pub enum Protocol {
Unspecified,
File,
Http,
Https,
Ssh,
Git,
#[strum(serialize = "git+ssh")]
GitSsh,
}
#[derive(Debug, PartialEq)]
pub struct GitUrl {
pub href: String,
pub host: Option<String>,
pub name: String,
pub owner: Option<String>,
pub organization: Option<String>,
pub fullname: String,
pub protocol: Protocol,
pub user: Option<String>,
pub token: Option<String>,
pub port: Option<u16>,
pub path: String,
pub git_suffix: bool,
}
impl fmt::Display for GitUrl {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.href)
}
}
impl Default for GitUrl {
fn default() -> Self {
GitUrl {
href: "".to_string(),
host: None,
name: "".to_string(),
owner: None,
organization: None,
fullname: "".to_string(),
protocol: Protocol::Unspecified,
user: None,
token: None,
port: None,
path: "".to_string(),
git_suffix: true,
}
}
}
impl GitUrl {
pub fn new(url: &str) -> GitUrl {
GitUrl {
href: url.to_string(),
..Default::default()
}
}
pub fn parse(url: &str) -> Result<GitUrl> {
let normalized = normalize_url(url).expect("Url normalization failed");
let protocol = Protocol::from_str(normalized.scheme())
.expect(&format!("Protocol unsupported: {:?}", normalized.scheme()));
let urlpath = match &protocol {
Protocol::Ssh => {
normalized.path()[1..].to_string()
}
_ => normalized.path().to_string(),
};
let git_suffix_check = &urlpath.ends_with(".git");
debug!("The urlpath: {:?}", &urlpath);
let splitpath = &urlpath.rsplit_terminator("/").collect::<Vec<&str>>();
debug!("rsplit results for metadata: {:?}", splitpath);
let name = splitpath[0].trim_end_matches(".git").to_string();
let (owner, organization, fullname) = match &protocol {
Protocol::File => (None::<String>, None::<String>, name.clone()),
_ => {
let mut fullname: Vec<&str> = Vec::new();
let hosts_w_organization_in_path = vec!["dev.azure.com", "ssh.dev.azure.com"];
match hosts_w_organization_in_path.contains(&normalized.clone().host_str().unwrap())
{
true => {
debug!("Found a git provider with an org");
match &protocol {
Protocol::Ssh => {
fullname.push(splitpath[2].clone());
fullname.push(splitpath[1].clone());
fullname.push(splitpath[0].clone());
(
Some(splitpath[1].to_string()),
Some(splitpath[2].to_string()),
fullname.join("/").to_string(),
)
}
Protocol::Https => {
fullname.push(splitpath[3].clone());
fullname.push(splitpath[2].clone());
fullname.push(splitpath[0].clone());
(
Some(splitpath[2].to_string()),
Some(splitpath[3].to_string()),
fullname.join("/").to_string(),
)
}
_ => panic!("Protocol not supported for host"),
}
}
false => {
fullname.push(splitpath[1]);
fullname.push(name.as_str());
(
Some(splitpath[1].to_string()),
None::<String>,
fullname.join("/").to_string(),
)
}
}
}
};
Ok(GitUrl {
href: url.to_string(),
host: match normalized.host_str() {
Some(h) => Some(h.to_string()),
None => None,
},
name: name,
owner: owner,
organization: organization,
fullname: fullname,
protocol: Protocol::from_str(normalized.scheme()).expect("Protocol unsupported"),
user: match normalized.username().to_string().len() {
0 => None,
_ => Some(normalized.username().to_string()),
},
token: match normalized.password() {
Some(p) => Some(p.to_string()),
None => None,
},
port: normalized.port(),
path: urlpath,
git_suffix: *git_suffix_check,
..Default::default()
})
}
}
fn normalize_ssh_url(url: &str) -> Result<Url> {
let u = url.split(":").collect::<Vec<&str>>();
match u.len() {
2 => {
debug!("Normalizing ssh url: {:?}", u);
normalize_url(&format!("ssh://{}/{}", u[0], u[1]))
}
3 => {
debug!("Normalizing ssh url with ports: {:?}", u);
normalize_url(&format!("ssh://{}:{}/{}", u[0], u[1], u[2]))
}
_default => {
panic!("SSH normalization pattern not covered for: {:?}", u);
}
}
}
fn normalize_file_path(filepath: &str) -> Result<Url> {
let fp = Url::from_file_path(filepath);
match fp {
Ok(path) => Ok(path),
Err(_e) => {
Ok(normalize_url(&format!("file://{}", filepath))
.expect("file:// normalization failed"))
}
}
}
pub fn normalize_url(url: &str) -> Result<Url> {
debug!("Processing: {:?}", &url);
let url_parse = Url::parse(&url);
Ok(match url_parse {
Ok(u) => {
match Protocol::from_str(u.scheme()) {
Ok(_p) => u,
Err(_e) => {
debug!("Scheme parse fail. Assuming a userless ssh url");
normalize_ssh_url(url)?
}
}
}
Err(_e) => {
let re = Regex::new(r"^\S+(@)\S+(:).*$")?;
match re.is_match(&url) {
true => {
debug!("Protocol::SSH match for normalization");
normalize_ssh_url(url)?
}
false => {
debug!("Protocol::File match for normalization");
normalize_file_path(&format!("{}", url))?
}
}
}
})
}