-
-
Notifications
You must be signed in to change notification settings - Fork 244
Expand file tree
/
Copy pathvcs.rs
More file actions
305 lines (270 loc) · 8.87 KB
/
vcs.rs
File metadata and controls
305 lines (270 loc) · 8.87 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
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 std::fmt;
use std::path::PathBuf;
use git2;
use regex::Regex;
use prelude::*;
use api::{Repo, Ref};
#[derive(Copy, Clone)]
pub enum GitReference<'a> {
Commit(git2::Oid),
Symbolic(&'a str),
}
impl<'a> fmt::Display for GitReference<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
GitReference::Commit(ref c) => write!(f, "{}", c),
GitReference::Symbolic(ref s) => write!(f, "{}", s),
}
}
}
#[derive(Debug)]
pub struct CommitSpec {
pub repo: String,
pub path: Option<PathBuf>,
pub rev: String,
pub prev_rev: Option<String>,
}
#[derive(Debug, PartialEq, Eq)]
pub struct VcsUrl {
pub provider: &'static str,
pub id: String,
}
fn parse_rev_range(rng: &str) -> (Option<String>, String) {
if rng == "" {
return (None, "HEAD".into());
}
let mut iter = rng.rsplitn(2, "..");
let rev = iter.next().unwrap_or("HEAD");
(iter.next().map(|x| x.to_string()), rev.to_string())
}
impl CommitSpec {
pub fn parse(s: &str) -> Result<CommitSpec> {
lazy_static! {
static ref SPEC_RE: Regex = Regex::new(
r"^([^@#]+)(?:#([^@]+))?(?:@(.+))?$").unwrap();
}
if let Some(caps) = SPEC_RE.captures(s) {
let (prev_rev, rev) = parse_rev_range(caps.get(3).map(|x| x.as_str()).unwrap_or(""));
Ok(CommitSpec {
repo: caps[1].to_string(),
path: caps.get(2).map(|x| PathBuf::from(x.as_str())),
rev: rev,
prev_rev: prev_rev,
})
} else {
Err(Error::from(format!("Could not parse commit spec '{}'", s)))
}
}
pub fn reference<'a>(&'a self) -> GitReference<'a> {
if let Ok(oid) = git2::Oid::from_str(&self.rev) {
GitReference::Commit(oid)
} else {
GitReference::Symbolic(&self.rev)
}
}
pub fn prev_reference<'a>(&'a self) -> Option<GitReference<'a>> {
self.prev_rev.as_ref().map(|rev| {
if let Ok(oid) = git2::Oid::from_str(rev) {
GitReference::Commit(oid)
} else {
GitReference::Symbolic(rev)
}
})
}
}
fn strip_git_suffix(s: &str) -> &str {
if s.ends_with(".git") {
&s[0..s.len() - 4]
} else {
s
}
}
impl VcsUrl {
pub fn parse(url: &str) -> VcsUrl {
lazy_static! {
static ref GITHUB_URL_RE: Regex = Regex::new(
r"^(?:ssh|https?)://(?:[^@]+@)?github.com/([^/]+)/([^/]+)").unwrap();
static ref GITHUB_SSH_RE: Regex = Regex::new(
r"^(?:[^@]+@)?github.com:([^/]+)/([^/]+)").unwrap();
}
if let Some(caps) = GITHUB_URL_RE.captures(url) {
VcsUrl {
provider: "github",
id: format!("{}/{}", &caps[1], strip_git_suffix(&caps[2])),
}
} else if let Some(caps) = GITHUB_SSH_RE.captures(url) {
VcsUrl {
provider: "github",
id: format!("{}/{}", &caps[1], strip_git_suffix(&caps[2])),
}
} else {
VcsUrl {
provider: "generic",
id: url.into(),
}
}
}
}
fn is_matching_url(a: &str, b: &str) -> bool {
VcsUrl::parse(a) == VcsUrl::parse(b)
}
fn find_reference_url(repo: &str, repos: &[Repo]) -> Result<String> {
for configured_repo in repos {
if configured_repo.name != repo {
continue;
}
if &configured_repo.provider.id != "github" &&
&configured_repo.provider.id != "git" {
return Err(Error::from("For non git repositories \
explicit revisions are required"));
}
return Ok(configured_repo.url.clone())
}
Err(Error::from(format!("Could not find matching repository for {}", repo)))
}
fn find_matching_rev(reference: GitReference, spec: &CommitSpec,
repos: &[Repo], disable_discovery: bool)
-> Result<Option<String>>
{
let r = match reference {
GitReference::Commit(commit) => {
return Ok(Some(commit.to_string()));
}
GitReference::Symbolic(r) => r,
};
let (repo, discovery) = if let Some(ref path) = spec.path {
(git2::Repository::open(path)?, false)
} else {
(git2::Repository::open_from_env()?, !disable_discovery)
};
let reference_url = find_reference_url(&spec.repo, repos)?;
// direct reference in root repository found. If we are in discovery
// mode we want to also check for matching URLs.
if_chain! {
if let Ok(remote) = repo.find_remote("origin");
if let Some(url) = remote.url();
if !discovery || is_matching_url(url, &reference_url);
then {
let head = repo.revparse_single(r)?;
return Ok(Some(head.id().to_string()));
}
}
// in discovery mode we want to find that repo in associated submodules.
for submodule in repo.submodules()? {
if_chain! {
if let Some(submodule_url) = submodule.url();
if is_matching_url(submodule_url, &reference_url);
then {
// heads on submodules is easier so let's start with that
// because that does not require the submodule to be
// checked out.
if_chain! {
if r == "HEAD";
if let Some(head_oid) = submodule.head_id();
then {
return Ok(Some(head_oid.to_string()));
}
}
// otherwise we need to open the submodule which requires
// it to be checked out.
if_chain! {
if let Ok(subrepo) = submodule.open();
then {
let head = subrepo.revparse_single(r)?;
return Ok(Some(head.id().to_string()));
}
}
}
}
}
Ok(None)
}
fn find_matching_revs(spec: &CommitSpec, repos: &[Repo], disable_discovery: bool)
-> Result<(Option<String>, String)>
{
fn error(r: GitReference, repo: &str) -> Error {
Error::from(format!(
"Could not find commit '{}' for '{}'. If you do not have local \
checkouts of the repositories in question referencing tags or \
other references will not work and you need to refer to \
revisions explicitly.",
r, repo))
}
let rev = if let Some(rev) = find_matching_rev(
spec.reference(), &spec, &repos[..], disable_discovery)? {
rev
} else {
return Err(error(spec.reference(), &spec.repo));
};
let prev_rev = if let Some(rev) = spec.prev_reference() {
if let Some(rv) = find_matching_rev(
rev, &spec, &repos[..], disable_discovery)? {
Some(rv)
} else {
return Err(error(rev, &spec.repo));
}
} else {
None
};
Ok((prev_rev, rev))
}
pub fn find_head() -> Result<String> {
let repo = git2::Repository::open_from_env()?;
let head = repo.revparse_single("HEAD")?;
Ok(head.id().to_string())
}
/// Given commit specs and repos this returns a list of head commits
/// from it.
pub fn find_heads(specs: Option<Vec<CommitSpec>>, repos: Vec<Repo>)
-> Result<Vec<Ref>>
{
let mut rv = vec![];
// if commit specs were explicitly provided find head commits with
// limited amounts of magic.
if let Some(specs) = specs {
for spec in &specs {
let (prev_rev, rev) = find_matching_revs(
&spec, &repos[..], specs.len() == 1)?;
rv.push(Ref {
repo: spec.repo.clone(),
rev: rev,
prev_rev: prev_rev,
});
}
// otherwise apply all the magic available
} else {
for repo in &repos {
let spec = CommitSpec {
repo: repo.name.to_string(),
path: None,
rev: "HEAD".into(),
prev_rev: None,
};
if let Some(rev) = find_matching_rev(
spec.reference(), &spec, &repos[..], false)? {
rv.push(Ref {
repo: repo.name.to_string(),
rev: rev,
prev_rev: None,
});
}
}
}
Ok(rv)
}
#[test]
fn test_url_parsing() {
assert_eq!(VcsUrl::parse("http://github.com/mitsuhiko/flask"), VcsUrl {
provider: "github",
id: "mitsuhiko/flask".into(),
});
assert_eq!(VcsUrl::parse("git@github.com:mitsuhiko/flask.git"), VcsUrl {
provider: "github",
id: "mitsuhiko/flask".into(),
});
}
#[test]
fn test_url_normalization() {
assert!(is_matching_url("http://github.com/mitsuhiko/flask",
"git@github.com:mitsuhiko/flask.git"));
}