1use std::cmp::{self, Ordering};
2use std::collections::HashSet;
3use std::fmt::{self, Formatter};
4use std::hash::{self, Hash};
5use std::path::Path;
6use std::ptr;
7use std::sync::atomic::Ordering::SeqCst;
8use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT};
9use std::sync::Mutex;
10
11use log::trace;
12use serde::de;
13use serde::ser;
14use url::Url;
15
16use crate::ops;
17use crate::sources::git;
18use crate::sources::DirectorySource;
19use crate::sources::{GitSource, PathSource, RegistrySource, CRATES_IO_INDEX};
20use crate::util::{CargoResult, Config, ToUrl};
21
22lazy_static::lazy_static! {
23 static ref SOURCE_ID_CACHE: Mutex<HashSet<&'static SourceIdInner>> = Mutex::new(HashSet::new());
24}
25
26#[derive(Clone, Copy, Eq, Debug)]
28pub struct SourceId {
29 inner: &'static SourceIdInner,
30}
31
32#[derive(PartialEq, Eq, Clone, Debug, Hash)]
33struct SourceIdInner {
34 url: Url,
36 canonical_url: Url,
38 kind: Kind,
40 precise: Option<String>,
42 name: Option<String>,
46}
47
48#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
51enum Kind {
52 Git(GitReference),
54 Path,
56 Registry,
58 LocalRegistry,
60 Directory,
62}
63
64#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
66pub enum GitReference {
67 Tag(String),
69 Branch(String),
71 Rev(String),
73}
74
75impl SourceId {
76 fn new(kind: Kind, url: Url) -> CargoResult<SourceId> {
80 let source_id = SourceId::wrap(SourceIdInner {
81 kind,
82 canonical_url: git::canonicalize_url(&url)?,
83 url,
84 precise: None,
85 name: None,
86 });
87 Ok(source_id)
88 }
89
90 fn wrap(inner: SourceIdInner) -> SourceId {
91 let mut cache = SOURCE_ID_CACHE.lock().unwrap();
92 let inner = cache.get(&inner).cloned().unwrap_or_else(|| {
93 let inner = Box::leak(Box::new(inner));
94 cache.insert(inner);
95 inner
96 });
97 SourceId { inner }
98 }
99
100 pub fn from_url(string: &str) -> CargoResult<SourceId> {
111 let mut parts = string.splitn(2, '+');
112 let kind = parts.next().unwrap();
113 let url = parts
114 .next()
115 .ok_or_else(|| failure::format_err!("invalid source `{}`", string))?;
116
117 match kind {
118 "git" => {
119 let mut url = url.to_url()?;
120 let mut reference = GitReference::Branch("master".to_string());
121 for (k, v) in url.query_pairs() {
122 match &k[..] {
123 "branch" | "ref" => reference = GitReference::Branch(v.into_owned()),
125
126 "rev" => reference = GitReference::Rev(v.into_owned()),
127 "tag" => reference = GitReference::Tag(v.into_owned()),
128 _ => {}
129 }
130 }
131 let precise = url.fragment().map(|s| s.to_owned());
132 url.set_fragment(None);
133 url.set_query(None);
134 Ok(SourceId::for_git(&url, reference)?.with_precise(precise))
135 }
136 "registry" => {
137 let url = url.to_url()?;
138 Ok(SourceId::new(Kind::Registry, url)?.with_precise(Some("locked".to_string())))
139 }
140 "path" => {
141 let url = url.to_url()?;
142 SourceId::new(Kind::Path, url)
143 }
144 kind => Err(failure::format_err!(
145 "unsupported source protocol: {}",
146 kind
147 )),
148 }
149 }
150
151 pub fn to_url(&self) -> SourceIdToUrl<'_> {
153 SourceIdToUrl {
154 inner: &*self.inner,
155 }
156 }
157
158 pub fn for_path(path: &Path) -> CargoResult<SourceId> {
162 let url = path.to_url()?;
163 SourceId::new(Kind::Path, url)
164 }
165
166 pub fn for_git(url: &Url, reference: GitReference) -> CargoResult<SourceId> {
168 SourceId::new(Kind::Git(reference), url.clone())
169 }
170
171 pub fn for_registry(url: &Url) -> CargoResult<SourceId> {
173 SourceId::new(Kind::Registry, url.clone())
174 }
175
176 pub fn for_local_registry(path: &Path) -> CargoResult<SourceId> {
178 let url = path.to_url()?;
179 SourceId::new(Kind::LocalRegistry, url)
180 }
181
182 pub fn for_directory(path: &Path) -> CargoResult<SourceId> {
184 let url = path.to_url()?;
185 SourceId::new(Kind::Directory, url)
186 }
187
188 pub fn crates_io(config: &Config) -> CargoResult<SourceId> {
193 config.crates_io_source_id(|| {
194 let cfg = ops::registry_configuration(config, None)?;
195 let url = if let Some(ref index) = cfg.index {
196 static WARNED: AtomicBool = ATOMIC_BOOL_INIT;
197 if !WARNED.swap(true, SeqCst) {
198 config.shell().warn(
199 "custom registry support via \
200 the `registry.index` configuration is \
201 being removed, this functionality \
202 will not work in the future",
203 )?;
204 }
205 &index[..]
206 } else {
207 CRATES_IO_INDEX
208 };
209 let url = url.to_url()?;
210 SourceId::for_registry(&url)
211 })
212 }
213
214 pub fn alt_registry(config: &Config, key: &str) -> CargoResult<SourceId> {
215 let url = config.get_registry_index(key)?;
216 Ok(SourceId::wrap(SourceIdInner {
217 kind: Kind::Registry,
218 canonical_url: git::canonicalize_url(&url)?,
219 url,
220 precise: None,
221 name: Some(key.to_string()),
222 }))
223 }
224
225 pub fn url(&self) -> &Url {
227 &self.inner.url
228 }
229
230 pub fn display_registry(self) -> String {
231 if self.is_default_registry() {
232 "crates.io index".to_string()
233 } else {
234 format!("`{}` index", url_display(self.url()))
235 }
236 }
237
238 pub fn is_path(self) -> bool {
240 self.inner.kind == Kind::Path
241 }
242
243 pub fn is_registry(self) -> bool {
245 match self.inner.kind {
246 Kind::Registry | Kind::LocalRegistry => true,
247 _ => false,
248 }
249 }
250
251 pub fn is_alt_registry(self) -> bool {
255 self.is_registry() && self.inner.name.is_some()
256 }
257
258 pub fn is_git(self) -> bool {
260 match self.inner.kind {
261 Kind::Git(_) => true,
262 _ => false,
263 }
264 }
265
266 pub fn load<'a>(self, config: &'a Config) -> CargoResult<Box<dyn super::Source + 'a>> {
268 trace!("loading SourceId; {}", self);
269 match self.inner.kind {
270 Kind::Git(..) => Ok(Box::new(GitSource::new(self, config)?)),
271 Kind::Path => {
272 let path = match self.inner.url.to_file_path() {
273 Ok(p) => p,
274 Err(()) => panic!("path sources cannot be remote"),
275 };
276 Ok(Box::new(PathSource::new(&path, self, config)))
277 }
278 Kind::Registry => Ok(Box::new(RegistrySource::remote(self, config))),
279 Kind::LocalRegistry => {
280 let path = match self.inner.url.to_file_path() {
281 Ok(p) => p,
282 Err(()) => panic!("path sources cannot be remote"),
283 };
284 Ok(Box::new(RegistrySource::local(self, &path, config)))
285 }
286 Kind::Directory => {
287 let path = match self.inner.url.to_file_path() {
288 Ok(p) => p,
289 Err(()) => panic!("path sources cannot be remote"),
290 };
291 Ok(Box::new(DirectorySource::new(&path, self, config)))
292 }
293 }
294 }
295
296 pub fn precise(self) -> Option<&'static str> {
298 self.inner.precise.as_ref().map(|s| &s[..])
299 }
300
301 pub fn git_reference(self) -> Option<&'static GitReference> {
303 match self.inner.kind {
304 Kind::Git(ref s) => Some(s),
305 _ => None,
306 }
307 }
308
309 pub fn with_precise(self, v: Option<String>) -> SourceId {
311 SourceId::wrap(SourceIdInner {
312 precise: v,
313 ..(*self.inner).clone()
314 })
315 }
316
317 pub fn is_default_registry(self) -> bool {
319 match self.inner.kind {
320 Kind::Registry => {}
321 _ => return false,
322 }
323 self.inner.url.to_string() == CRATES_IO_INDEX
324 }
325
326 pub fn stable_hash<S: hash::Hasher>(self, workspace: &Path, into: &mut S) {
331 if self.is_path() {
332 if let Ok(p) = self
333 .inner
334 .url
335 .to_file_path()
336 .unwrap()
337 .strip_prefix(workspace)
338 {
339 self.inner.kind.hash(into);
340 p.to_str().unwrap().hash(into);
341 return;
342 }
343 }
344 self.hash(into)
345 }
346
347 pub fn full_eq(self, other: SourceId) -> bool {
348 ptr::eq(self.inner, other.inner)
349 }
350
351 pub fn full_hash<S: hash::Hasher>(self, into: &mut S) {
352 ptr::NonNull::from(self.inner).hash(into)
353 }
354}
355
356impl PartialOrd for SourceId {
357 fn partial_cmp(&self, other: &SourceId) -> Option<Ordering> {
358 Some(self.cmp(other))
359 }
360}
361
362impl Ord for SourceId {
363 fn cmp(&self, other: &SourceId) -> Ordering {
364 self.inner.cmp(&other.inner)
365 }
366}
367
368impl ser::Serialize for SourceId {
369 fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
370 where
371 S: ser::Serializer,
372 {
373 if self.is_path() {
374 None::<String>.serialize(s)
375 } else {
376 s.collect_str(&self.to_url())
377 }
378 }
379}
380
381impl<'de> de::Deserialize<'de> for SourceId {
382 fn deserialize<D>(d: D) -> Result<SourceId, D::Error>
383 where
384 D: de::Deserializer<'de>,
385 {
386 let string = String::deserialize(d)?;
387 SourceId::from_url(&string).map_err(de::Error::custom)
388 }
389}
390
391fn url_display(url: &Url) -> String {
392 if url.scheme() == "file" {
393 if let Ok(path) = url.to_file_path() {
394 if let Some(path_str) = path.to_str() {
395 return path_str.to_string();
396 }
397 }
398 }
399
400 url.as_str().to_string()
401}
402
403impl fmt::Display for SourceId {
404 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
405 match self.inner.kind {
406 Kind::Git(ref reference) => {
407 write!(f, "{}", self.inner.url)?;
410 if let Some(pretty) = reference.pretty_ref() {
411 write!(f, "?{}", pretty)?;
412 }
413
414 if let Some(ref s) = self.inner.precise {
415 let len = cmp::min(s.len(), 8);
416 write!(f, "#{}", &s[..len])?;
417 }
418 Ok(())
419 }
420 Kind::Path => write!(f, "{}", url_display(&self.inner.url)),
421 Kind::Registry => write!(f, "registry `{}`", url_display(&self.inner.url)),
422 Kind::LocalRegistry => write!(f, "registry `{}`", url_display(&self.inner.url)),
423 Kind::Directory => write!(f, "dir {}", url_display(&self.inner.url)),
424 }
425 }
426}
427
428impl PartialEq for SourceId {
431 fn eq(&self, other: &SourceId) -> bool {
432 if ptr::eq(self.inner, other.inner) {
433 return true;
434 }
435 if self.inner.kind != other.inner.kind {
436 return false;
437 }
438 if self.inner.url == other.inner.url {
439 return true;
440 }
441
442 match (&self.inner.kind, &other.inner.kind) {
443 (Kind::Git(ref1), Kind::Git(ref2)) => {
444 ref1 == ref2 && self.inner.canonical_url == other.inner.canonical_url
445 }
446 _ => false,
447 }
448 }
449}
450
451impl PartialOrd for SourceIdInner {
452 fn partial_cmp(&self, other: &SourceIdInner) -> Option<Ordering> {
453 Some(self.cmp(other))
454 }
455}
456
457impl Ord for SourceIdInner {
458 fn cmp(&self, other: &SourceIdInner) -> Ordering {
459 match self.kind.cmp(&other.kind) {
460 Ordering::Equal => {}
461 ord => return ord,
462 }
463 match self.url.cmp(&other.url) {
464 Ordering::Equal => {}
465 ord => return ord,
466 }
467 match (&self.kind, &other.kind) {
468 (Kind::Git(ref1), Kind::Git(ref2)) => {
469 (ref1, &self.canonical_url).cmp(&(ref2, &other.canonical_url))
470 }
471 _ => self.kind.cmp(&other.kind),
472 }
473 }
474}
475
476impl Hash for SourceId {
480 fn hash<S: hash::Hasher>(&self, into: &mut S) {
481 self.inner.kind.hash(into);
482 match self.inner.kind {
483 Kind::Git(_) => self.inner.canonical_url.as_str().hash(into),
484 _ => self.inner.url.as_str().hash(into),
485 }
486 }
487}
488
489pub struct SourceIdToUrl<'a> {
491 inner: &'a SourceIdInner,
492}
493
494impl<'a> fmt::Display for SourceIdToUrl<'a> {
495 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
496 match *self.inner {
497 SourceIdInner {
498 kind: Kind::Path,
499 ref url,
500 ..
501 } => write!(f, "path+{}", url),
502 SourceIdInner {
503 kind: Kind::Git(ref reference),
504 ref url,
505 ref precise,
506 ..
507 } => {
508 write!(f, "git+{}", url)?;
509 if let Some(pretty) = reference.pretty_ref() {
510 write!(f, "?{}", pretty)?;
511 }
512 if let Some(precise) = precise.as_ref() {
513 write!(f, "#{}", precise)?;
514 }
515 Ok(())
516 }
517 SourceIdInner {
518 kind: Kind::Registry,
519 ref url,
520 ..
521 } => write!(f, "registry+{}", url),
522 SourceIdInner {
523 kind: Kind::LocalRegistry,
524 ref url,
525 ..
526 } => write!(f, "local-registry+{}", url),
527 SourceIdInner {
528 kind: Kind::Directory,
529 ref url,
530 ..
531 } => write!(f, "directory+{}", url),
532 }
533 }
534}
535
536impl GitReference {
537 pub fn pretty_ref(&self) -> Option<PrettyRef<'_>> {
540 match *self {
541 GitReference::Branch(ref s) if *s == "master" => None,
542 _ => Some(PrettyRef { inner: self }),
543 }
544 }
545}
546
547pub struct PrettyRef<'a> {
549 inner: &'a GitReference,
550}
551
552impl<'a> fmt::Display for PrettyRef<'a> {
553 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
554 match *self.inner {
555 GitReference::Branch(ref b) => write!(f, "branch={}", b),
556 GitReference::Tag(ref s) => write!(f, "tag={}", s),
557 GitReference::Rev(ref s) => write!(f, "rev={}", s),
558 }
559 }
560}
561
562#[cfg(test)]
563mod tests {
564 use super::{GitReference, Kind, SourceId};
565 use crate::util::ToUrl;
566
567 #[test]
568 fn github_sources_equal() {
569 let loc = "https://github.com/foo/bar".to_url().unwrap();
570 let master = Kind::Git(GitReference::Branch("master".to_string()));
571 let s1 = SourceId::new(master.clone(), loc).unwrap();
572
573 let loc = "git://github.com/foo/bar".to_url().unwrap();
574 let s2 = SourceId::new(master, loc.clone()).unwrap();
575
576 assert_eq!(s1, s2);
577
578 let foo = Kind::Git(GitReference::Branch("foo".to_string()));
579 let s3 = SourceId::new(foo, loc).unwrap();
580 assert_ne!(s1, s3);
581 }
582}