aboutsummaryrefslogtreecommitdiffstats
path: root/zone_core/src/container.rs
blob: 058d7f31a9df77ea3daf68d697467615db15b666 (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
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
use clap::Args;
use serde::{Deserialize, Serialize};
use std::{ffi::OsStr, fmt::Display, path::PathBuf};
use tabled::Tabled;

use crate::FilterContainer;

pub use self::error::ParsingError;
pub use self::status::Status;

mod error;
mod status;

#[derive(Debug, PartialEq, Eq, Default, Serialize, Deserialize, Tabled, Clone, Args)]
#[serde(rename_all = "camelCase")]
pub struct Container {
    #[tabled("ID")]
    pub id: u32,

    #[tabled("Template")]
    pub template: String,

    #[tabled("User")]
    pub owner: String,
}

impl Display for Container {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}-{}-{}", self.template, self.owner, self.id)
    }
}

impl From<Container> for String {
    fn from(c: Container) -> Self {
        format!("{}-{}-{}", c.template, c.owner, c.id)
    }
}

impl From<Container> for PathBuf {
    fn from(c: Container) -> Self {
        PathBuf::from(format!("{}/{}/{}", c.template, c.owner, c.id))
    }
}

impl TryFrom<String> for Container {
    type Error = ParsingError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        let v = s.split('-').collect::<Vec<_>>();
        match v[v.len() - 3..] {
            [i, o, t] => Ok(Container {
                id: i.parse()?,
                owner: o.into(),
                template: t.into(),
            }),
            _ => Err(s).map_err(ParsingError::from),
        }
    }
}

impl TryFrom<PathBuf> for Container {
    type Error = ParsingError;

    fn try_from(p: PathBuf) -> Result<Self, Self::Error> {
        let v = p.iter().map(OsStr::to_str).collect::<Vec<_>>();
        match v[v.len() - 3..] {
            [Some(i), Some(o), Some(t)] => Ok(Container {
                id: i.parse()?,
                owner: o.into(),
                template: t.into(),
            }),
            _ => Err(p).map_err(ParsingError::from),
        }
    }
}

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct ContainerOptions {
    pub id: Option<u32>,
    pub parent: Option<String>,
    pub owner: Option<String>,
}

impl From<Container> for ContainerOptions {
    fn from(c: Container) -> Self {
        Self {
            id: Some(c.id),
            parent: Some(c.template),
            owner: Some(c.owner),
        }
    }
}

impl From<&Container> for &ContainerOptions {
    fn from(c: &Container) -> Self {
        ContainerOptions {
            id: Some(c.id.to_owned()),
            parent: Some(c.template.to_owned()),
            owner: Some(c.owner.to_owned()),
        }
        .into()
    }
}

impl From<ContainerOptions> for &ContainerOptions {
    fn from(o: ContainerOptions) -> Self {
        o.into()
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, Args)]
pub struct CloneOptions {
    pub template: String,
    pub owner: String,
}

impl<T> FilterContainer for T
where
    T: Iterator,
    T::Item: TryInto<Container>,
{
    fn filter_container(&mut self, pred: &ContainerOptions) -> Vec<Container> {
        self.filter_map(|c| -> Option<Container> { c.try_into().ok() })
            .filter(|c| {
                pred.id.map_or(false, |p| p == c.id)
                    && pred.parent.as_ref().map_or(false, |p| p == &c.template)
                    && pred.owner.as_ref().map_or(false, |p| p == &c.owner)
            })
            .collect()
    }
}