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
use derive_more::{Display, From, Into};
use serde::{Deserialize, Serialize};
use std::ops::{Deref, DerefMut};

/// Represents some command with arguments to execute
#[derive(Clone, Debug, Display, From, Into, Hash, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct Cmd(String);

impl Cmd {
    /// Creates a new command from the given `cmd`
    pub fn new(cmd: impl Into<String>) -> Self {
        Self(cmd.into())
    }

    /// Returns reference to the program portion of the command
    pub fn program(&self) -> &str {
        match self.0.split_once(' ') {
            Some((program, _)) => program.trim(),
            None => self.0.trim(),
        }
    }

    /// Returns reference to the arguments portion of the command
    pub fn arguments(&self) -> &str {
        match self.0.split_once(' ') {
            Some((_, arguments)) => arguments.trim(),
            None => "",
        }
    }
}

#[cfg(feature = "schemars")]
impl Cmd {
    pub fn root_schema() -> schemars::schema::RootSchema {
        schemars::schema_for!(Cmd)
    }
}

impl Deref for Cmd {
    type Target = String;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for Cmd {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}