debian_analyzer/
vendor.rs

1//! Information about the distribution vendor
2use deb822_lossless::{Deb822, Paragraph};
3
4fn load_vendor_file(name: Option<&str>) -> std::io::Result<Deb822> {
5    let name = name.unwrap_or("default");
6
7    let path = std::path::Path::new("/etc/dpkg/origins").join(name);
8
9    let f = std::fs::read_to_string(path)?;
10
11    Ok(f.parse().unwrap())
12}
13
14/// Information about a distribution vendor
15pub struct Vendor {
16    /// The name of the vendor (e.g. "Debian", "Ubuntu")
17    pub name: String,
18
19    /// The URL of the bug tracker (e.g. "https://bugs.debian.org/")
20    pub bugs: url::Url,
21
22    /// The homepage of the vendor (e.g. "https://www.debian.org/")
23    pub url: url::Url,
24}
25
26impl std::str::FromStr for Vendor {
27    type Err = deb822_lossless::ParseError;
28
29    fn from_str(text: &str) -> Result<Self, Self::Err> {
30        let data = Deb822::from_str(text)?;
31
32        let data = data.paragraphs().next().unwrap();
33
34        Ok(data.into())
35    }
36}
37
38impl From<Paragraph> for Vendor {
39    fn from(data: Paragraph) -> Self {
40        // TODO: rely on derive
41        Vendor {
42            name: data.get("Vendor").unwrap(),
43            url: data.get("Vendor-URL").unwrap().parse().unwrap(),
44            bugs: data.get("Bugs").unwrap().parse().unwrap(),
45        }
46    }
47}
48
49/// Get the vendor information for a given vendor name
50pub fn get_vendor(name: Option<&str>) -> std::io::Result<Vendor> {
51    let data = load_vendor_file(name)?;
52
53    Ok(data.paragraphs().next().unwrap().into())
54}
55
56/// Get the vendor name for the current system
57pub fn get_vendor_name() -> std::io::Result<String> {
58    if let Ok(vendor) = std::env::var("DEB_VENDOR") {
59        Ok(vendor)
60    } else {
61        Ok(get_vendor(None)?.name)
62    }
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68    #[test]
69    fn test_get_vendor_name() {
70        let _ = get_vendor_name();
71    }
72
73    #[test]
74    fn test_paragraph_to_vendor() {
75        let data = r#"Vendor: Debian
76Vendor-URL: https://www.debian.org/
77Bugs: https://bugs.debian.org/"#;
78
79        let vendor: Vendor = data.parse().unwrap();
80
81        assert_eq!(vendor.name, "Debian");
82        assert_eq!(vendor.bugs, "https://bugs.debian.org/".parse().unwrap());
83        assert_eq!(vendor.url, "https://www.debian.org/".parse().unwrap());
84    }
85}