Skip to main content

cargo/core/source/
source_id.rs

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/// Unique identifier for a source of packages.
27#[derive(Clone, Copy, Eq, Debug)]
28pub struct SourceId {
29    inner: &'static SourceIdInner,
30}
31
32#[derive(PartialEq, Eq, Clone, Debug, Hash)]
33struct SourceIdInner {
34    /// The source URL
35    url: Url,
36    /// `git::canonicalize_url(url)` for the url field
37    canonical_url: Url,
38    /// The source kind
39    kind: Kind,
40    // e.g. the exact git revision of the specified branch for a Git Source
41    precise: Option<String>,
42    /// Name of the registry source for alternative registries
43    /// WARNING: This is not always set for alt-registries when the name is
44    /// not known.
45    name: Option<String>,
46}
47
48/// The possible kinds of code source. Along with SourceIdInner this fully defines the
49/// source
50#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
51enum Kind {
52    /// Kind::Git(<git reference>) represents a git repository
53    Git(GitReference),
54    /// represents a local path
55    Path,
56    /// represents a remote registry
57    Registry,
58    /// represents a local filesystem-based registry
59    LocalRegistry,
60    /// represents a directory-based registry
61    Directory,
62}
63
64/// Information to find a specific commit in a git repository
65#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
66pub enum GitReference {
67    /// from a tag
68    Tag(String),
69    /// from the HEAD of a branch
70    Branch(String),
71    /// from a specific revision
72    Rev(String),
73}
74
75impl SourceId {
76    /// Create a SourceId object from the kind and url.
77    ///
78    /// The canonical url will be calculated, but the precise field will not
79    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    /// Parses a source URL and returns the corresponding ID.
101    ///
102    /// ## Example
103    ///
104    /// ```
105    /// use cargo::core::SourceId;
106    /// SourceId::from_url("git+https://github.com/alexcrichton/\
107    ///                     libssh2-static-sys#80e71a3021618eb05\
108    ///                     656c58fb7c5ef5f12bc747f");
109    /// ```
110    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                        // map older 'ref' to branch
124                        "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    /// A view of the `SourceId` that can be `Display`ed as a URL
152    pub fn to_url(&self) -> SourceIdToUrl<'_> {
153        SourceIdToUrl {
154            inner: &*self.inner,
155        }
156    }
157
158    /// Create a SourceId from a filesystem path.
159    ///
160    /// Pass absolute path
161    pub fn for_path(path: &Path) -> CargoResult<SourceId> {
162        let url = path.to_url()?;
163        SourceId::new(Kind::Path, url)
164    }
165
166    /// Crate a SourceId from a git reference
167    pub fn for_git(url: &Url, reference: GitReference) -> CargoResult<SourceId> {
168        SourceId::new(Kind::Git(reference), url.clone())
169    }
170
171    /// Create a SourceId from a registry url
172    pub fn for_registry(url: &Url) -> CargoResult<SourceId> {
173        SourceId::new(Kind::Registry, url.clone())
174    }
175
176    /// Create a SourceId from a local registry path
177    pub fn for_local_registry(path: &Path) -> CargoResult<SourceId> {
178        let url = path.to_url()?;
179        SourceId::new(Kind::LocalRegistry, url)
180    }
181
182    /// Create a SourceId from a directory path
183    pub fn for_directory(path: &Path) -> CargoResult<SourceId> {
184        let url = path.to_url()?;
185        SourceId::new(Kind::Directory, url)
186    }
187
188    /// Returns the `SourceId` corresponding to the main repository.
189    ///
190    /// This is the main cargo registry by default, but it can be overridden in
191    /// a `.cargo/config`.
192    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    /// Get this source URL
226    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    /// Is this source from a filesystem path
239    pub fn is_path(self) -> bool {
240        self.inner.kind == Kind::Path
241    }
242
243    /// Is this source from a registry (either local or not)
244    pub fn is_registry(self) -> bool {
245        match self.inner.kind {
246            Kind::Registry | Kind::LocalRegistry => true,
247            _ => false,
248        }
249    }
250
251    /// Is this source from an alternative registry
252    /// DEPRECATED: This is not correct if the registry name is not known
253    /// (for example when loaded from an index).
254    pub fn is_alt_registry(self) -> bool {
255        self.is_registry() && self.inner.name.is_some()
256    }
257
258    /// Is this source from a git repository
259    pub fn is_git(self) -> bool {
260        match self.inner.kind {
261            Kind::Git(_) => true,
262            _ => false,
263        }
264    }
265
266    /// Creates an implementation of `Source` corresponding to this ID.
267    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    /// Get the value of the precise field
297    pub fn precise(self) -> Option<&'static str> {
298        self.inner.precise.as_ref().map(|s| &s[..])
299    }
300
301    /// Get the git reference if this is a git source, otherwise None.
302    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    /// Create a new SourceId from this source with the given `precise`
310    pub fn with_precise(self, v: Option<String>) -> SourceId {
311        SourceId::wrap(SourceIdInner {
312            precise: v,
313            ..(*self.inner).clone()
314        })
315    }
316
317    /// Whether the remote registry is the standard https://crates.io
318    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    /// Hash `self`
327    ///
328    /// For paths, remove the workspace prefix so the same source will give the
329    /// same hash in different locations.
330    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                // Don't replace the URL display for git references,
408                // because those are kind of expected to be URLs.
409                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
428// Custom equality defined as canonical URL equality for git sources and
429// URL equality for other sources, ignoring the `precise` and `name` fields.
430impl 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
476// The hash of SourceId is used in the name of some Cargo folders, so shouldn't
477// vary. `as_str` gives the serialisation of a url (which has a spec) and so
478// insulates against possible changes in how the url crate does hashing.
479impl 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
489/// A `Display`able view into a `SourceId` that will write it as a url
490pub 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    /// Returns a `Display`able view of this git reference, or None if using
538    /// the head of the "master" branch
539    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
547/// A git reference that can be `Display`ed
548pub 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}