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
extern crate regex;
extern crate reqwest;
extern crate url;

use crate::checksum::{Algorithm, Checksum};
use core::fmt;
use log::debug;
use regex::Regex;
use std::string::ToString;
use url::Url;

pub mod checksum;

/// A parsed Maven coordinates record.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MavenCoordinates<'a> {
    pub group_id: &'a str,
    pub artifact_id: &'a str,
    pub packaging: Option<&'a str>,
    pub classifier: Option<&'a str>,
    pub version: &'a str,
}

impl fmt::Display for MavenCoordinates<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{group_id}:{artifact_id}{packaging}{classifier}:{version}",
            group_id = &self.group_id,
            artifact_id = &self.artifact_id,
            packaging = &self
                .packaging
                .map(|p| format!(":{}", p))
                .unwrap_or_else(|| "".to_string()),
            classifier = &self
                .classifier
                .map(|c| format!(":{}", c))
                .unwrap_or_else(|| "".to_string()),
            version = &self.version,
        )
    }
}

impl<'a> MavenCoordinates<'a> {
    /// Constructs a new, empty `MavenCoordinates`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rvn::MavenCoordinates;
    ///
    /// let coordinates = MavenCoordinates::new("com.fasterxml.jackson.core", "jackson-annotations", None, None, "2.9.9");
    /// ```
    pub fn new(
        group_id: &'a str,
        artifact_id: &'a str,
        packaging: Option<&'a str>,
        classifier: Option<&'a str>,
        version: &'a str,
    ) -> MavenCoordinates<'a> {
        MavenCoordinates {
            group_id,
            artifact_id,
            packaging,
            classifier,
            version,
        }
    }

    /// Parse the Maven coordinates from a string.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rvn::MavenCoordinates;
    ///
    /// let coordinates = MavenCoordinates::parse("com.fasterxml.jackson.core:jackson-annotations:2.9.9").unwrap();
    /// ```
    pub fn parse(maven_coordinates: &str) -> Result<MavenCoordinates, &'static str> {
        debug!("Trying to parse Maven coordinates: {}", maven_coordinates);

        // Parse Maven coordinates into named capture groups, with optional packaging OR packaging+classifier
        let regexp = Regex::new(r"^(?P<groupId>[\w.\-]+):(?P<artifactId>[\w.\-]+)(?:(?::(?P<packaging>[\w.\-]+))(?::(?P<classifier>[\w.\-]+)?)?)?:(?P<version>[\w.\-]+)$")
            .expect("Error compiling regex");

        match regexp.captures(maven_coordinates) {
            Some(capture) => Ok(MavenCoordinates::new(
                capture
                    .name("groupId")
                    .map(|m| m.as_str())
                    .expect("Missing groupId"),
                capture
                    .name("artifactId")
                    .map(|m| m.as_str())
                    .expect("Missing artifactId"),
                capture.name("packaging").map(|m| m.as_str()),
                capture.name("classifier").map(|m| m.as_str()),
                capture
                    .name("version")
                    .map(|m| m.as_str())
                    .expect("Missing version"),
            )),
            None => Err("Couldn't parse Maven coordinates"),
        }
    }

    /// Fetch the checksum associated with the Maven coordinates.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rvn::{MavenCoordinates};
    /// use rvn::checksum::Algorithm;
    /// use url::Url;
    ///
    /// let repository = Url::parse("https://repo1.maven.org/maven2").unwrap();
    /// let coordinates = MavenCoordinates::parse("com.fasterxml.jackson.core:jackson-annotations:jar:sources:2.9.9").unwrap();
    /// let checksum = coordinates.fetch_checksum(&repository, Algorithm::Sha1).unwrap();
    ///
    /// assert_eq!(checksum.value, "4ac77aa5799fcf00a9cde00cd7da4d08bdc038ff");
    /// assert_eq!(checksum.algorithm, Algorithm::Sha1);
    /// ```
    pub fn fetch_checksum(
        &self,
        repository: &Url,
        algorithm: Algorithm,
    ) -> Result<Checksum, reqwest::Error> {
        let group_id_formatted = str::replace(self.group_id, ".", "/");
        let artifact_uri = format!("{group_id}/{artifact_id}/{version}/{artifact_id}-{version}{classifier}.{packaging}.{algorithm}",
                               group_id = &group_id_formatted,
                               artifact_id = self.artifact_id,
                               version = self.version,
                               classifier = self.classifier.map(|c| format!("-{}", c)).unwrap_or_else(|| "".to_owned()),
                               packaging = self.packaging.unwrap_or("jar"),
                               algorithm = algorithm.to_string());

        let artifact_url = repository
            .clone()
            .append_segment(&artifact_uri)
            .expect("Couldn't append artifact URI to repository URL");

        reqwest::get(artifact_url.as_str())?
            .error_for_status()?
            .text()
            .map(|s| Checksum::new(algorithm, &s))
    }
}

trait MutSegments {
    fn append_segment(&mut self, uri: &str) -> Result<Url, &'static str>;
}

impl MutSegments for Url {
    fn append_segment(&mut self, uri: &str) -> Result<Url, &'static str> {
        self.path_segments_mut()
            .map_err(|_| "cannot be base")?
            .pop_if_empty()
            .push(&uri);

        Ok(self.to_owned())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parses_three_component_maven_coordinate() {
        let provided = "com.fasterxml.jackson.core:jackson-annotations:2.9.9";
        let expected = MavenCoordinates::new(
            "com.fasterxml.jackson.core",
            "jackson-annotations",
            None,
            None,
            "2.9.9",
        );

        assert_eq!(MavenCoordinates::parse(provided).unwrap(), expected);
    }

    #[test]
    fn test_parses_four_component_maven_coordinate() {
        let provided = "com.fasterxml.jackson.core:jackson-annotations:pom:2.9.9";
        let expected = MavenCoordinates::new(
            "com.fasterxml.jackson.core",
            "jackson-annotations",
            Some("pom"),
            None,
            "2.9.9",
        );

        assert_eq!(MavenCoordinates::parse(provided).unwrap(), expected);
    }

    #[test]
    fn test_parses_five_component_maven_coordinate() {
        let provided = "com.fasterxml.jackson.core:jackson-annotations:jar:sources:2.9.9";
        let expected = MavenCoordinates::new(
            "com.fasterxml.jackson.core",
            "jackson-annotations",
            Some("jar"),
            Some("sources"),
            "2.9.9",
        );

        assert_eq!(MavenCoordinates::parse(provided).unwrap(), expected);
    }

    #[test]
    fn test_parse_unorthodox_maven_coordinate() {
        let provided = "io.get-coursier:coursier-cli_2.12:jar:standalone:1.1.0-M14-4";
        let expected = MavenCoordinates::new(
            "io.get-coursier",
            "coursier-cli_2.12",
            Some("jar"),
            Some("standalone"),
            "1.1.0-M14-4",
        );

        assert_eq!(MavenCoordinates::parse(provided).unwrap(), expected);
    }
}