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
use std::fmt::Display;

use crate::{
    error::{Error, ErrorExt},
    parse::Rule,
    Result,
};
use pest::iterators::Pair;
use strum::{Display, EnumString};

use super::parameter;

pub type VpsName = String;

#[derive(Debug, PartialEq, EnumString, Display)]
#[strum(serialize_all = "lowercase")]
pub enum VpsAction {
    Item,
    Lock,
    Unlock,
    Start,
    Stop,
    Reset,
}

#[derive(Debug, PartialEq)]
pub enum VpsCommand {
    /// # Example
    ///
    /// ```
    /// use transip_command::{VpsCommand, TransipCommand};
    ///
    /// let commandline = "vps list";
    /// assert_eq!(
    ///     commandline.parse::<TransipCommand>().unwrap(),
    ///     TransipCommand::Vps(VpsCommand::List),
    /// );
    /// ```
    List,

    /// # Example
    ///
    /// ```
    /// use transip_command::{TransipCommand, VpsAction, VpsCommand};
    ///
    /// let commandline = "vps reset vps9374";
    /// assert_eq!(
    ///     commandline.parse::<TransipCommand>().unwrap(),
    ///     TransipCommand::Vps(
    ///         VpsCommand::Action(
    ///             "vps9374".to_owned(),
    ///             VpsAction::Reset,
    ///         )
    ///     ),
    /// );
    /// ```
    Action(VpsName, VpsAction),
}

impl Display for VpsCommand {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            VpsCommand::Action(name, action) => write!(f, "{} {}", action, name),
            VpsCommand::List => write!(f, "list"),
        }
    }
}

impl<'a> TryFrom<Pair<'a, Rule>> for VpsCommand {
    type Error = Error;

    fn try_from(pair: Pair<'a, Rule>) -> Result<Self> {
        let commandline = pair.as_str().to_owned();
        let inner = pair.into_inner().next().unwrap();
        match inner.as_rule() {
            Rule::vps_list => Ok(VpsCommand::List),
            Rule::vps_item_action => {
                let mut inner = inner.into_inner();
                let action = inner.next().unwrap().as_str().trim();
                let name = parameter(inner.next().unwrap())?;
                action
                    .parse::<VpsAction>()
                    .map_err(|_| Error::ParseVpsCommand(commandline))
                    .map(|action| VpsCommand::Action(name, action))
            }
            _ => Err(Error::ParseVpsCommand(commandline)),
        }
    }
}

pub struct Parameter(String);

impl<'a> TryFrom<Pair<'a, Rule>> for Parameter {
    type Error = Error;

    fn try_from(pair: Pair<'a, Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::value => Ok(Parameter(pair.as_str().to_owned())),
            Rule::env => std::env::var(pair.as_str()).err_into().map(Parameter),
            _ => Err(Error::ParseTransipCommand("Failure".to_owned())),
        }
    }
}

#[cfg(test)]
mod test {
    use super::{VpsAction, VpsCommand};

    #[test]
    fn display() {
        assert_eq!(
            VpsCommand::Action("vps2".to_owned(), VpsAction::Start).to_string(),
            "start vps2".to_owned(),
        );

        assert_eq!(VpsCommand::List.to_string(), "list".to_owned(),);
    }
}