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
//! Crate name parsing.
use semver;

use errors::*;
use Dependency;
use {get_crate_name_from_github, get_crate_name_from_gitlab, get_crate_name_from_path};

/// A crate specifier. This can be a plain name (e.g. `docopt`), a name and a versionreq (e.g.
/// `docopt@^0.8`), a URL, or a path.
#[derive(Debug)]
pub struct CrateName<'a>(&'a str);

impl<'a> CrateName<'a> {
    /// Create a new `CrateName`
    pub fn new(name: &'a str) -> Self {
        CrateName(name)
    }

    /// Does this specify a versionreq?
    pub fn has_version(&self) -> bool {
        self.0.contains('@')
    }

    /// Is this a URI?
    pub fn is_url_or_path(&self) -> bool {
        self.is_github_url() || self.is_gitlab_url() || self.is_path()
    }

    fn is_github_url(&self) -> bool {
        self.0.contains("https://github.com")
    }

    fn is_gitlab_url(&self) -> bool {
        self.0.contains("https://gitlab.com")
    }

    fn is_path(&self) -> bool {
        // FIXME: how else can we check if the name is a (possibly invalid) path?
        self.0.contains('.') || self.0.contains('/') || self.0.contains('\\')
    }

    /// If this crate specifier includes a version (e.g. `docopt@0.8`), extract the name and
    /// version.
    pub fn parse_as_version(&self) -> Result<Option<Dependency>> {
        if self.has_version() {
            let xs: Vec<_> = self.0.splitn(2, '@').collect();
            let (name, version) = (xs[0], xs[1]);
            semver::VersionReq::parse(version).chain_err(|| "Invalid crate version requirement")?;

            Ok(Some(Dependency::new(name).set_version(version)))
        } else {
            Ok(None)
        }
    }

    /// Will parse this crate name on the assumption that it is a URI.
    pub fn parse_crate_name_from_uri(&self) -> Result<Dependency> {
        if self.is_github_url() {
            if let Ok(ref crate_name) = get_crate_name_from_github(self.0) {
                return Ok(Dependency::new(crate_name).set_git(self.0));
            }
        } else if self.is_gitlab_url() {
            if let Ok(ref crate_name) = get_crate_name_from_gitlab(self.0) {
                return Ok(Dependency::new(crate_name).set_git(self.0));
            }
        } else if self.is_path() {
            if let Ok(ref crate_name) = get_crate_name_from_path(self.0) {
                return Ok(Dependency::new(crate_name).set_path(self.0));
            }
        }

        bail!("Unable to obtain crate informations from `{}`.\n", self.0)
    }
}