summaryrefslogtreecommitdiffstats
path: root/src/urlutil.rs
blob: 51def16e8d4b081aa9f90f0b4f5bc824fe171ccc (plain)
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
use std::collections::BTreeSet;

/// The host of one `source=()` entry, or `None` when it names no host — a local
/// file, a relative path, or a `file://` URL.
///
/// Handles the `custom::` and `git+`/`svn+`/`npm+` prefixes a PKGBUILD puts before a
/// URL.
pub fn host_of(source: &str) -> Option<String> {
    let s = source.rsplit("::").next().unwrap_or(source);
    let s = s.rsplit('+').next().unwrap_or(s);
    let rest = s.split("://").nth(1)?;
    let host = rest.split('/').next()?;
    // `git+ssh://git@github.com/...` names the same place as
    // `https://github.com/...`; leaving the user in would make a scheme change
    // look like a new source host and cry wolf at a reviewer.
    let host = host.rsplit('@').next().unwrap_or(host);
    (!host.is_empty()).then(|| host.to_string())
}

/// The distinct hosts a `source=()` array names, sorted. A host appearing here
/// that was not in the accepted release's list is a new place the build fetches
/// code from (§5.3, §6).
pub fn hosts(sources: &[String]) -> BTreeSet<String> {
    sources.iter().map(|s| s.as_str()).filter_map(host_of).collect()
}

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

    #[test]
    fn a_plain_url_is_its_host() {
        assert_eq!(host_of("https://example.invalid/a.tar.gz").as_deref(), Some("example.invalid"));
    }

    #[test]
    fn scheme_and_filename_prefixes_are_stripped() {
        assert_eq!(host_of("git+https://github.com/a/b.git").as_deref(), Some("github.com"));
        assert_eq!(
            host_of("myname::https://cdn.example.org/x.tar").as_deref(),
            Some("cdn.example.org")
        );
        assert_eq!(
            host_of("myname::git+ssh://git@gitlab.example.org/a/b.git").as_deref(),
            Some("gitlab.example.org"),
            "the ssh user is not part of the host"
        );
    }

    #[test]
    fn local_files_have_no_host() {
        assert_eq!(host_of("fix.patch"), None);
        assert_eq!(host_of("./relative/thing.conf"), None);
    }

    #[test]
    fn hosts_are_deduplicated_and_sorted() {
        let h = hosts(&[
            "https://b.example/x.tar".to_string(),
            "https://a.example/y.tar".to_string(),
            "git+https://b.example/z.git".to_string(),
            "local.patch".to_string(),
        ]);
        assert_eq!(h.into_iter().collect::<Vec<_>>(), vec!["a.example", "b.example"]);
    }
}