-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathparse_git_remote.rs
More file actions
100 lines (88 loc) · 2.9 KB
/
parse_git_remote.rs
File metadata and controls
100 lines (88 loc) · 2.9 KB
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
use anyhow::{Result, anyhow};
use lazy_static::lazy_static;
lazy_static! {
static ref REMOTE_REGEX: regex::Regex = regex::Regex::new(
r"(?P<domain>[^/@\.]+\.\w+)[:/](?P<owner>[^/]+)/(?P<repository>[^/]+?)(\.git)?/?$"
)
.unwrap();
}
#[derive(Debug)]
pub struct GitRemote {
pub domain: String,
pub owner: String,
pub repository: String,
}
pub fn parse_git_remote(remote: &str) -> Result<GitRemote> {
let captures = REMOTE_REGEX.captures(remote).ok_or_else(|| {
anyhow!("Could not extract owner and repository from remote url: {remote}")
})?;
let domain = captures.name("domain").unwrap().as_str();
let owner = captures.name("owner").unwrap().as_str();
let repository = captures.name("repository").unwrap().as_str();
Ok(GitRemote {
domain: domain.to_string(),
owner: owner.to_string(),
repository: repository.to_string(),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_git_remote() {
let remote = "git@github.com:CodSpeedHQ/runner.git";
let git_remote = parse_git_remote(remote).unwrap();
insta::assert_debug_snapshot!(git_remote, @r###"
GitRemote {
domain: "github.com",
owner: "CodSpeedHQ",
repository: "runner",
}
"###);
let remote = "https://github.com/CodSpeedHQ/runner.git";
let git_remote = parse_git_remote(remote).unwrap();
insta::assert_debug_snapshot!(git_remote, @r###"
GitRemote {
domain: "github.com",
owner: "CodSpeedHQ",
repository: "runner",
}
"###);
let remote = "https://github.com/CodSpeedHQ/runner";
let git_remote = parse_git_remote(remote).unwrap();
insta::assert_debug_snapshot!(git_remote, @r###"
GitRemote {
domain: "github.com",
owner: "CodSpeedHQ",
repository: "runner",
}
"###);
let remote = "git@gitlab.com:codspeed/runner.git";
let git_remote = parse_git_remote(remote).unwrap();
insta::assert_debug_snapshot!(git_remote, @r###"
GitRemote {
domain: "gitlab.com",
owner: "codspeed",
repository: "runner",
}
"###);
let remote = "https://gitlab.com/codspeed/runner.git";
let git_remote = parse_git_remote(remote).unwrap();
insta::assert_debug_snapshot!(git_remote, @r###"
GitRemote {
domain: "gitlab.com",
owner: "codspeed",
repository: "runner",
}
"###);
let remote = "https://github.com/codspeed/runner/";
let git_remote = parse_git_remote(remote).unwrap();
insta::assert_debug_snapshot!(git_remote, @r###"
GitRemote {
domain: "github.com",
owner: "codspeed",
repository: "runner",
}
"###);
}
}