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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
use std::fmt;
use std::path::{Path, PathBuf};
use std::fs::{self, File};
use rustc_serialize::{Encodable, Encoder};
use url::Url;
use git2::{self, ObjectType};
use core::GitReference;
use util::{CargoResult, ChainError, human, ToUrl, internal};
#[derive(PartialEq, Clone, Debug)]
pub struct GitRevision(git2::Oid);
impl fmt::Display for GitRevision {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
#[derive(PartialEq,Clone,Debug)]
pub struct GitRemote {
url: Url,
}
#[derive(PartialEq,Clone,RustcEncodable)]
struct EncodableGitRemote {
url: String,
}
impl Encodable for GitRemote {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
EncodableGitRemote {
url: self.url.to_string()
}.encode(s)
}
}
pub struct GitDatabase {
remote: GitRemote,
path: PathBuf,
repo: git2::Repository,
}
#[derive(RustcEncodable)]
pub struct EncodableGitDatabase {
remote: GitRemote,
path: String,
}
impl Encodable for GitDatabase {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
EncodableGitDatabase {
remote: self.remote.clone(),
path: self.path.display().to_string()
}.encode(s)
}
}
pub struct GitCheckout<'a> {
database: &'a GitDatabase,
location: PathBuf,
revision: GitRevision,
repo: git2::Repository,
}
#[derive(RustcEncodable)]
pub struct EncodableGitCheckout {
database: EncodableGitDatabase,
location: String,
revision: String,
}
impl<'a> Encodable for GitCheckout<'a> {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
EncodableGitCheckout {
location: self.location.display().to_string(),
revision: self.revision.to_string(),
database: EncodableGitDatabase {
remote: self.database.remote.clone(),
path: self.database.path.display().to_string(),
},
}.encode(s)
}
}
impl GitRemote {
pub fn new(url: &Url) -> GitRemote {
GitRemote { url: url.clone() }
}
pub fn url(&self) -> &Url {
&self.url
}
pub fn rev_for(&self, path: &Path, reference: &GitReference)
-> CargoResult<GitRevision> {
let db = try!(self.db_at(path));
db.rev_for(reference)
}
pub fn checkout(&self, into: &Path) -> CargoResult<GitDatabase> {
let repo = match git2::Repository::open(into) {
Ok(repo) => {
try!(self.fetch_into(&repo).chain_error(|| {
human(format!("failed to fetch into {}", into.display()))
}));
repo
}
Err(..) => {
try!(self.clone_into(into).chain_error(|| {
human(format!("failed to clone into: {}", into.display()))
}))
}
};
Ok(GitDatabase {
remote: self.clone(),
path: into.to_path_buf(),
repo: repo,
})
}
pub fn db_at(&self, db_path: &Path) -> CargoResult<GitDatabase> {
let repo = try!(git2::Repository::open(db_path));
Ok(GitDatabase {
remote: self.clone(),
path: db_path.to_path_buf(),
repo: repo,
})
}
fn fetch_into(&self, dst: &git2::Repository) -> CargoResult<()> {
let url = self.url.to_string();
let refspec = "refs/heads/*:refs/heads/*";
fetch(dst, &url, refspec)
}
fn clone_into(&self, dst: &Path) -> CargoResult<git2::Repository> {
let url = self.url.to_string();
if fs::metadata(&dst).is_ok() {
try!(fs::remove_dir_all(dst));
}
try!(fs::create_dir_all(dst));
let repo = try!(git2::Repository::init_bare(dst));
try!(fetch(&repo, &url, "refs/heads/*:refs/heads/*"));
Ok(repo)
}
}
impl GitDatabase {
fn path<'a>(&'a self) -> &'a Path {
&self.path
}
pub fn copy_to(&self, rev: GitRevision, dest: &Path)
-> CargoResult<GitCheckout> {
let checkout = match git2::Repository::open(dest) {
Ok(repo) => {
let checkout = GitCheckout::new(dest, self, rev, repo);
if !checkout.is_fresh() {
try!(checkout.fetch());
try!(checkout.reset());
assert!(checkout.is_fresh());
}
checkout
}
Err(..) => try!(GitCheckout::clone_into(dest, self, rev)),
};
try!(checkout.update_submodules().chain_error(|| {
internal("failed to update submodules")
}));
Ok(checkout)
}
pub fn rev_for(&self, reference: &GitReference) -> CargoResult<GitRevision> {
let id = match *reference {
GitReference::Tag(ref s) => {
try!((|| {
let refname = format!("refs/tags/{}", s);
let id = try!(self.repo.refname_to_id(&refname));
let obj = try!(self.repo.find_object(id, None));
let obj = try!(obj.peel(ObjectType::Commit));
Ok(obj.id())
}).chain_error(|| {
human(format!("failed to find tag `{}`", s))
}))
}
GitReference::Branch(ref s) => {
try!((|| {
let b = try!(self.repo.find_branch(s, git2::BranchType::Local));
b.get().target().chain_error(|| {
human(format!("branch `{}` did not have a target", s))
})
}).chain_error(|| {
human(format!("failed to find branch `{}`", s))
}))
}
GitReference::Rev(ref s) => {
let obj = try!(self.repo.revparse_single(s));
obj.id()
}
};
Ok(GitRevision(id))
}
pub fn has_ref(&self, reference: &str) -> CargoResult<()> {
try!(self.repo.revparse_single(reference));
Ok(())
}
}
impl<'a> GitCheckout<'a> {
fn new(path: &Path, database: &'a GitDatabase, revision: GitRevision,
repo: git2::Repository)
-> GitCheckout<'a>
{
GitCheckout {
location: path.to_path_buf(),
database: database,
revision: revision,
repo: repo,
}
}
fn clone_into(into: &Path, database: &'a GitDatabase,
revision: GitRevision)
-> CargoResult<GitCheckout<'a>>
{
let repo = try!(GitCheckout::clone_repo(database.path(), into));
let checkout = GitCheckout::new(into, database, revision, repo);
try!(checkout.reset());
Ok(checkout)
}
fn clone_repo(source: &Path, into: &Path) -> CargoResult<git2::Repository> {
let dirname = into.parent().unwrap();
try!(fs::create_dir_all(&dirname).chain_error(|| {
human(format!("Couldn't mkdir {}", dirname.display()))
}));
if fs::metadata(&into).is_ok() {
try!(fs::remove_dir_all(into).chain_error(|| {
human(format!("Couldn't rmdir {}", into.display()))
}));
}
let url = try!(source.to_url().map_err(human));
let url = url.to_string();
let repo = try!(git2::Repository::clone(&url, into).chain_error(|| {
internal(format!("failed to clone {} into {}", source.display(),
into.display()))
}));
Ok(repo)
}
fn is_fresh(&self) -> bool {
match self.repo.revparse_single("HEAD") {
Ok(ref head) if head.id() == self.revision.0 => {
fs::metadata(self.location.join(".cargo-ok")).is_ok()
}
_ => false,
}
}
fn fetch(&self) -> CargoResult<()> {
info!("fetch {}", self.repo.path().display());
let url = try!(self.database.path.to_url().map_err(human));
let url = url.to_string();
let refspec = "refs/heads/*:refs/heads/*";
try!(fetch(&self.repo, &url, refspec));
Ok(())
}
fn reset(&self) -> CargoResult<()> {
let ok_file = self.location.join(".cargo-ok");
let _ = fs::remove_file(&ok_file);
info!("reset {} to {}", self.repo.path().display(), self.revision);
let object = try!(self.repo.find_object(self.revision.0, None));
try!(self.repo.reset(&object, git2::ResetType::Hard, None));
try!(File::create(ok_file));
Ok(())
}
fn update_submodules(&self) -> CargoResult<()> {
return update_submodules(&self.repo);
fn update_submodules(repo: &git2::Repository) -> CargoResult<()> {
info!("update submodules for: {:?}", repo.workdir().unwrap());
for mut child in try!(repo.submodules()).into_iter() {
try!(child.init(false));
let url = try!(child.url().chain_error(|| {
internal("non-utf8 url for submodule")
}));
let head = match child.head_id() {
Some(head) => head,
None => continue,
};
let head_and_repo = child.open().and_then(|repo| {
let target = try!(repo.head()).target();
Ok((target, repo))
});
let repo = match head_and_repo {
Ok((head, repo)) => {
if child.head_id() == head {
continue
}
repo
}
Err(..) => {
let path = repo.workdir().unwrap().join(child.path());
try!(git2::Repository::clone(url, &path))
}
};
let refspec = "refs/heads/*:refs/heads/*";
try!(fetch(&repo, url, refspec).chain_error(|| {
internal(format!("failed to fetch submodule `{}` from {}",
child.name().unwrap_or(""), url))
}));
let obj = try!(repo.find_object(head, None));
try!(repo.reset(&obj, git2::ResetType::Hard, None));
try!(update_submodules(&repo));
}
Ok(())
}
}
}
fn with_authentication<T, F>(url: &str, cfg: &git2::Config, mut f: F)
-> CargoResult<T>
where F: FnMut(&mut git2::Credentials) -> CargoResult<T>
{
let mut cred_helper = git2::CredentialHelper::new(url);
cred_helper.config(cfg);
let mut called = 0;
let res = f(&mut |url, username, allowed| {
called += 1;
if called >= 2 {
return Err(git2::Error::from_str("no authentication available"))
}
if allowed.contains(git2::SSH_KEY) ||
allowed.contains(git2::USERNAME) {
let user = username.map(|s| s.to_string())
.or_else(|| cred_helper.username.clone())
.unwrap_or("git".to_string());
if allowed.contains(git2::USERNAME) {
git2::Cred::username(&user)
} else {
git2::Cred::ssh_key_from_agent(&user)
}
} else if allowed.contains(git2::USER_PASS_PLAINTEXT) {
git2::Cred::credential_helper(cfg, url, username)
} else if allowed.contains(git2::DEFAULT) {
git2::Cred::default()
} else {
Err(git2::Error::from_str("no authentication available"))
}
});
if called > 0 {
res.chain_error(|| {
human("failed to authenticate when downloading repository")
})
} else {
res
}
}
pub fn fetch(repo: &git2::Repository, url: &str,
refspec: &str) -> CargoResult<()> {
with_authentication(url, &try!(repo.config()), |f| {
let mut cb = git2::RemoteCallbacks::new();
cb.credentials(f);
let mut remote = try!(repo.remote_anonymous(&url));
let mut opts = git2::FetchOptions::new();
opts.remote_callbacks(cb)
.download_tags(git2::AutotagOption::All);
try!(remote.fetch(&[refspec], Some(&mut opts), None));
Ok(())
})
}