summaryrefslogtreecommitdiff
path: root/src/packages.rs
blob: 5fb08d0dad32e90763a1e84309c3049c080d27cb (plain) (blame)
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
use std::{fs::File, io::Read};

use dnf::Dnf;
use pacman::Pacman;
use portage::Portage;
use serde::{Deserialize, Serialize};

use crate::error::{Error, Result};

mod dnf;
mod pacman;
mod portage;

#[derive(Debug, Serialize, Deserialize)]
pub struct PackageList {
    packages: Vec<Package>,
    manager: Manager,
}

impl PackageList {
    pub fn install(&self) -> Result<()> {
        self.manager
            .to_package_manager()
            .install(self.packages.clone())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Package {
    pub id: String,
    pub version: String,
    pub explicit: bool,
}

#[derive(Debug, Clone, clap::ValueEnum, Serialize, Deserialize)]
pub enum Manager {
    Dnf,
    Pacman,
    Portage,
}

impl Manager {
    pub fn from_sys() -> Result<Self> {
        #[cfg(not(target_os = "linux"))]
        return Err(Error::Unsupported);

        #[cfg(target_os = "linux")]
        {
            let mut os_release = File::open("/etc/os-release")?;
            let mut content = String::new();
            os_release.read_to_string(&mut content)?;

            let lines: Vec<&str> = content.split('\n').collect();
            for line in lines {
                let Some((key, value)) = line.split_once('=') else {
                    continue;
                };
                if key == "ID" {
                    return Self::from_str(value);
                }
            }
            Err(Error::Unsupported)
        }
    }

    fn from_str(value: &str) -> Result<Self> {
        Ok(match value {
            "fedora" => Box::new(Dnf),
            "arch" => Box::new(Pacman),
            "gentoo" => Box::new(Portage),
            _ => return Err(Error::Unsupported),
        })
    }

    pub fn to_package_manager(&self) -> Box<dyn PackageManager> {
        match self {
            Self::Dnf => Box::new(Dnf),
            Self::Pacman => Box::new(Pacman),
            Self::Portage => Box::new(Portage),
        }
    }
}

pub trait PackageManager {
    fn get_installed(&self) -> Result<PackageList>;

    fn install(&self, pkgs: Vec<Package>) -> Result<()>;
}