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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
use std::cmp::{self, Ordering};
use std::collections::hash_map::{HashMap, Values, IterMut};
use std::fmt::{self, Formatter};
use std::hash;
use std::path::Path;
use std::sync::Arc;
use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
use url::Url;
use core::{Package, PackageId, Registry};
use sources::{PathSource, GitSource, RegistrySource};
use sources::git;
use util::{human, Config, CargoResult, ToUrl};
pub trait Source: Registry {
fn update(&mut self) -> CargoResult<()>;
fn download(&mut self, package: &PackageId) -> CargoResult<Package>;
fn fingerprint(&self, pkg: &Package) -> CargoResult<String>;
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Kind {
Git(GitReference),
Path,
Registry,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum GitReference {
Tag(String),
Branch(String),
Rev(String),
}
#[derive(Clone, Eq, Debug)]
pub struct SourceId {
inner: Arc<SourceIdInner>,
}
#[derive(Eq, Clone, Debug)]
struct SourceIdInner {
url: Url,
canonical_url: Url,
kind: Kind,
precise: Option<String>,
}
impl SourceId {
fn new(kind: Kind, url: Url) -> SourceId {
SourceId {
inner: Arc::new(SourceIdInner {
kind: kind,
canonical_url: git::canonicalize_url(&url),
url: url,
precise: None,
}),
}
}
pub fn from_url(string: &str) -> SourceId {
let mut parts = string.splitn(2, '+');
let kind = parts.next().unwrap();
let url = parts.next().unwrap();
match kind {
"git" => {
let mut url = url.to_url().unwrap();
let mut reference = GitReference::Branch("master".to_string());
for (k, v) in url.query_pairs() {
match &k[..] {
"branch" |
"ref" => reference = GitReference::Branch(v.into_owned()),
"rev" => reference = GitReference::Rev(v.into_owned()),
"tag" => reference = GitReference::Tag(v.into_owned()),
_ => {}
}
}
let precise = url.fragment().map(|s| s.to_owned());
url.set_fragment(None);
url.set_query(None);
SourceId::for_git(&url, reference).with_precise(precise)
}
"registry" => {
let url = url.to_url().unwrap();
SourceId::new(Kind::Registry, url)
.with_precise(Some("locked".to_string()))
}
"path" => {
let url = url.to_url().unwrap();
SourceId::new(Kind::Path, url)
}
_ => panic!("Unsupported serialized SourceId"),
}
}
pub fn to_url(&self) -> String {
match *self.inner {
SourceIdInner { kind: Kind::Path, ref url, .. } => {
format!("path+{}", url)
}
SourceIdInner {
kind: Kind::Git(ref reference), ref url, ref precise, ..
} => {
let ref_str = reference.url_ref();
let precise_str = if precise.is_some() {
format!("#{}", precise.as_ref().unwrap())
} else {
"".to_string()
};
format!("git+{}{}{}", url, ref_str, precise_str)
}
SourceIdInner { kind: Kind::Registry, ref url, .. } => {
format!("registry+{}", url)
}
}
}
pub fn for_path(path: &Path) -> CargoResult<SourceId> {
let url = try!(path.to_url().map_err(human));
Ok(SourceId::new(Kind::Path, url))
}
pub fn for_git(url: &Url, reference: GitReference) -> SourceId {
SourceId::new(Kind::Git(reference), url.clone())
}
pub fn for_registry(url: &Url) -> SourceId {
SourceId::new(Kind::Registry, url.clone())
}
pub fn for_central(config: &Config) -> CargoResult<SourceId> {
Ok(SourceId::for_registry(&try!(RegistrySource::url(config))))
}
pub fn url(&self) -> &Url {
&self.inner.url
}
pub fn is_path(&self) -> bool {
self.inner.kind == Kind::Path
}
pub fn is_registry(&self) -> bool {
self.inner.kind == Kind::Registry
}
pub fn is_git(&self) -> bool {
match self.inner.kind {
Kind::Git(_) => true,
_ => false,
}
}
pub fn load<'a>(&self, config: &'a Config) -> Box<Source + 'a> {
trace!("loading SourceId; {}", self);
match self.inner.kind {
Kind::Git(..) => Box::new(GitSource::new(self, config)),
Kind::Path => {
let path = match self.inner.url.to_file_path() {
Ok(p) => p,
Err(()) => panic!("path sources cannot be remote"),
};
Box::new(PathSource::new(&path, self, config))
}
Kind::Registry => Box::new(RegistrySource::new(self, config)),
}
}
pub fn precise(&self) -> Option<&str> {
self.inner.precise.as_ref().map(|s| &s[..])
}
pub fn git_reference(&self) -> Option<&GitReference> {
match self.inner.kind {
Kind::Git(ref s) => Some(s),
_ => None,
}
}
pub fn with_precise(&self, v: Option<String>) -> SourceId {
SourceId {
inner: Arc::new(SourceIdInner {
precise: v,
..(*self.inner).clone()
})
}
}
pub fn is_default_registry(&self) -> bool {
match self.inner.kind {
Kind::Registry => {}
_ => return false,
}
self.inner.url.to_string() == RegistrySource::default_url()
}
}
impl PartialEq for SourceId {
fn eq(&self, other: &SourceId) -> bool {
(*self.inner).eq(&*other.inner)
}
}
impl PartialOrd for SourceId {
fn partial_cmp(&self, other: &SourceId) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for SourceId {
fn cmp(&self, other: &SourceId) -> Ordering {
self.inner.cmp(&other.inner)
}
}
impl Encodable for SourceId {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
if self.is_path() {
s.emit_option_none()
} else {
self.to_url().encode(s)
}
}
}
impl Decodable for SourceId {
fn decode<D: Decoder>(d: &mut D) -> Result<SourceId, D::Error> {
let string: String = Decodable::decode(d).ok().expect("Invalid encoded SourceId");
Ok(SourceId::from_url(&string))
}
}
impl fmt::Display for SourceId {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match *self.inner {
SourceIdInner { kind: Kind::Path, ref url, .. } => {
fmt::Display::fmt(url, f)
}
SourceIdInner { kind: Kind::Git(ref reference), ref url,
ref precise, .. } => {
try!(write!(f, "{}{}", url, reference.url_ref()));
if let Some(ref s) = *precise {
let len = cmp::min(s.len(), 8);
try!(write!(f, "#{}", &s[..len]));
}
Ok(())
}
SourceIdInner { kind: Kind::Registry, ref url, .. } => {
write!(f, "registry {}", url)
}
}
}
}
impl PartialEq for SourceIdInner {
fn eq(&self, other: &SourceIdInner) -> bool {
if self.kind != other.kind {
return false;
}
if self.url == other.url {
return true;
}
match (&self.kind, &other.kind) {
(&Kind::Git(ref ref1), &Kind::Git(ref ref2)) => {
ref1 == ref2 && self.canonical_url == other.canonical_url
}
_ => false,
}
}
}
impl PartialOrd for SourceIdInner {
fn partial_cmp(&self, other: &SourceIdInner) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for SourceIdInner {
fn cmp(&self, other: &SourceIdInner) -> Ordering {
match self.kind.cmp(&other.kind) {
Ordering::Equal => {}
ord => return ord,
}
match self.url.cmp(&other.url) {
Ordering::Equal => {}
ord => return ord,
}
match (&self.kind, &other.kind) {
(&Kind::Git(ref ref1), &Kind::Git(ref ref2)) => {
(ref1, &self.canonical_url).cmp(&(ref2, &other.canonical_url))
}
_ => self.kind.cmp(&other.kind),
}
}
}
impl hash::Hash for SourceId {
fn hash<S: hash::Hasher>(&self, into: &mut S) {
self.inner.kind.hash(into);
match *self.inner {
SourceIdInner { kind: Kind::Git(..), ref canonical_url, .. } => {
canonical_url.hash(into)
}
_ => self.inner.url.hash(into),
}
}
}
impl GitReference {
pub fn to_ref_string(&self) -> Option<String> {
match *self {
GitReference::Branch(ref s) => {
if *s == "master" {
None
} else {
Some(format!("branch={}", s))
}
}
GitReference::Tag(ref s) => Some(format!("tag={}", s)),
GitReference::Rev(ref s) => Some(format!("rev={}", s)),
}
}
fn url_ref(&self) -> String {
match self.to_ref_string() {
None => "".to_string(),
Some(s) => format!("?{}", s),
}
}
}
pub struct SourceMap<'src> {
map: HashMap<SourceId, Box<Source + 'src>>,
}
pub type Sources<'a, 'src> = Values<'a, SourceId, Box<Source + 'src>>;
pub struct SourcesMut<'a, 'src: 'a> {
inner: IterMut<'a, SourceId, Box<Source + 'src>>,
}
impl<'src> SourceMap<'src> {
pub fn new() -> SourceMap<'src> {
SourceMap { map: HashMap::new() }
}
pub fn contains(&self, id: &SourceId) -> bool {
self.map.contains_key(id)
}
pub fn get(&self, id: &SourceId) -> Option<&(Source + 'src)> {
let source = self.map.get(id);
source.map(|s| {
let s: &(Source + 'src) = &**s;
s
})
}
pub fn get_mut(&mut self, id: &SourceId) -> Option<&mut (Source + 'src)> {
self.map.get_mut(id).map(|s| {
let s: &mut (Source + 'src) = &mut **s;
s
})
}
pub fn get_by_package_id(&self, pkg_id: &PackageId) -> Option<&(Source + 'src)> {
self.get(pkg_id.source_id())
}
pub fn insert(&mut self, id: &SourceId, source: Box<Source + 'src>) {
self.map.insert(id.clone(), source);
}
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
pub fn len(&self) -> usize {
self.map.len()
}
pub fn sources<'a>(&'a self) -> Sources<'a, 'src> {
self.map.values()
}
pub fn sources_mut<'a>(&'a mut self) -> SourcesMut<'a, 'src> {
SourcesMut { inner: self.map.iter_mut() }
}
}
impl<'a, 'src> Iterator for SourcesMut<'a, 'src> {
type Item = (&'a SourceId, &'a mut (Source + 'src));
fn next(&mut self) -> Option<(&'a SourceId, &'a mut (Source + 'src))> {
self.inner.next().map(|(a, b)| (a, &mut **b))
}
}
#[cfg(test)]
mod tests {
use super::{SourceId, Kind, GitReference};
use util::ToUrl;
#[test]
fn github_sources_equal() {
let loc = "https://github.com/foo/bar".to_url().unwrap();
let master = Kind::Git(GitReference::Branch("master".to_string()));
let s1 = SourceId::new(master.clone(), loc);
let loc = "git://github.com/foo/bar".to_url().unwrap();
let s2 = SourceId::new(master, loc.clone());
assert_eq!(s1, s2);
let foo = Kind::Git(GitReference::Branch("foo".to_string()));
let s3 = SourceId::new(foo, loc);
assert!(s1 != s3);
}
}