alpm_types/
source.rs

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
use std::{
    fmt::{Display, Formatter},
    path::PathBuf,
    str::FromStr,
};

use url::Url;

use crate::Error;

/// Represents the location that a source file should be retrieved from
///
/// It can be either a local file (next to the PKGBUILD) or a URL.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Source {
    /// A local file source.
    ///
    /// The location must be a pure file name, without any path components (`/`).
    /// Hence, the file must be located directly next to the PKGBUILD.
    File {
        filename: Option<PathBuf>,
        location: PathBuf,
    },
    /// A URL source.
    Url { filename: Option<PathBuf>, url: Url },
}

impl Source {
    /// Returns the filename of the source if it is set.
    pub fn filename(&self) -> Option<&PathBuf> {
        match self {
            Self::File { filename, .. } | Self::Url { filename, .. } => filename.as_ref(),
        }
    }
}

impl FromStr for Source {
    type Err = Error;

    /// Parses a `Source` from string.
    ///
    /// It is either a filename (in the same directory as the PKGBUILD)
    /// or a url, optionally prefixed by a destination file name (separated by `::`).
    ///
    /// ## Errors
    ///
    /// This function returns an error in the following cases:
    ///
    /// - The destination file name or url/source file name are malformed.
    /// - The source file name is an absolute path.
    ///
    /// ## Examples
    ///
    /// ```
    /// use std::path::Path;
    /// use std::str::FromStr;
    ///
    /// use alpm_types::Source;
    /// use url::Url;
    ///
    /// let source = Source::from_str("foopkg-1.2.3.tar.gz::https://example.com/download").unwrap();
    /// assert_eq!(source.filename().unwrap(), Path::new("foopkg-1.2.3.tar.gz"));
    ///
    /// let Source::Url { url, .. } = source else {
    ///     panic!()
    /// };
    /// assert_eq!(url.host_str(), Some("example.com"));
    ///
    /// let source = Source::from_str("renamed-source.tar.gz::test.tar.gz").unwrap();
    /// assert_eq!(
    ///     source.filename().unwrap(),
    ///     Path::new("renamed-source.tar.gz")
    /// );
    ///
    /// let Source::File { location, .. } = source else {
    ///     panic!()
    /// };
    /// assert_eq!(location, Path::new("test.tar.gz"));
    /// ```
    fn from_str(mut s: &str) -> Result<Self, Self::Err> {
        let filename = if let Some((filename, location)) = s.split_once("::") {
            s = location;
            Some(filename.into())
        } else {
            None
        };

        match s.parse() {
            Ok(url) => Ok(Self::Url { filename, url }),
            Err(url::ParseError::RelativeUrlWithoutBase) => {
                if s.is_empty() {
                    Err(Error::FileNameIsEmpty)
                } else if s.contains(std::path::MAIN_SEPARATOR) {
                    Err(Error::FileNameContainsInvalidChars(
                        PathBuf::from(s),
                        std::path::MAIN_SEPARATOR,
                    ))
                } else if s.contains('\0') {
                    Err(Error::FileNameContainsInvalidChars(PathBuf::from(s), '\0'))
                } else {
                    Ok(Self::File {
                        filename,
                        location: s.into(),
                    })
                }
            }
            Err(e) => Err(e.into()),
        }
    }
}

impl Display for Source {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::File { filename, location } => {
                if let Some(filename) = filename {
                    write!(f, "{}::{}", filename.display(), location.display())
                } else {
                    write!(f, "{}", location.display())
                }
            }
            Self::Url { filename, url } => {
                if let Some(filename) = filename {
                    write!(f, "{}::{}", filename.display(), url)
                } else {
                    write!(f, "{}", url)
                }
            }
        }
    }
}

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

    use super::*;

    #[rstest]
    #[case("bikeshed_colour.patch::test", Ok(Source::File {
        filename: Some(PathBuf::from("bikeshed_colour.patch")),
        location: PathBuf::from("test"),
    }))]
    #[case("c:foo::test", Ok(Source::File {
        filename: Some(PathBuf::from("c:foo")),
        location: PathBuf::from("test"),
    }))]
    #[case(
        "./bikeshed_colour.patch",
        Err(Error::FileNameContainsInvalidChars(PathBuf::from("./bikeshed_colour.patch"), '/'))
    )]
    #[case("", Err(Error::FileNameIsEmpty))]
    #[case(
        "with\0null",
        Err(Error::FileNameContainsInvalidChars(PathBuf::from("with\0null"), '\0'))
    )]
    fn parse_filename(#[case] input: &str, #[case] expected: Result<Source, Error>) {
        let source = input.parse();
        assert_eq!(source, expected);

        if let Ok(source) = source {
            assert_eq!(
                source.filename(),
                input.split("::").next().map(PathBuf::from).as_ref()
            );
        }
    }

    #[rstest]
    #[case("bikeshed_colour.patch", Ok(Source::File {
        filename: None,
        location: PathBuf::from("bikeshed_colour.patch"),
    }))]
    #[case("renamed::local", Ok(Source::File {
        filename: Some(PathBuf::from("renamed")),
        location: PathBuf::from("local"),
    }))]
    #[case("foo-1.2.3.tar.gz::https://example.com/download", Ok(Source::Url {
        filename: Some(PathBuf::from("foo-1.2.3.tar.gz")),
        url: Url::parse("https://example.com/download").unwrap(),
    }))]
    #[case("my-git-repo::git+https://example.com/project/repo.git#commit=deadbeef?signed", Ok(Source::Url {
        filename: Some(PathBuf::from("my-git-repo")),
        url: Url::parse("git+https://example.com/project/repo.git#commit=deadbeef?signed").unwrap(),
    }))]
    #[case("file:///somewhere/else", Ok(Source::Url {
        filename: None,
        url: Url::parse("file:///somewhere/else").unwrap(),
    }))]
    #[case(
        "/absolute/path",
        Err(Error::FileNameContainsInvalidChars(PathBuf::from("/absolute/path"), '/'))
    )]
    #[case(
        "foo:::/absolute/path",
        Err(Error::FileNameContainsInvalidChars(PathBuf::from(":/absolute/path"), '/'))
    )]
    fn parse_source(#[case] input: &str, #[case] expected: Result<Source, Error>) {
        let source: Result<Source, Error> = input.parse();
        assert_eq!(source, expected);

        if let Ok(source) = source {
            assert_eq!(source.to_string(), input);
        }
    }
}