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
use std::fmt;
use std::fmt::{Debug, Display, Formatter};

type ShellCallback = Box<dyn FnMut() -> Result<(), String>>;

pub struct ShellCommand {
    name: String,
    action: Option<ShellCallback>,
}

impl ShellCommand {
    pub fn new(name: &str) -> ShellCommand {
        ShellCommand {
            name: name.trim().to_string(),
            action: None,
        }
    }

    pub fn set_action(&mut self, action: ShellCallback) {
        self.action = Some(action);
    }

    pub fn with_action(mut self, action: ShellCallback) -> ShellCommand {
        self.set_action(action);

        self
    }

    pub fn trigger_action(&mut self) -> Result<(), String> {
        if let Some(action) = &mut self.action {
            action()
        } else {
            Ok(())
        }
    }

    pub fn set_name(&mut self, name: &str) {
        self.name = name.to_string();
    }

    pub fn with_name(mut self, name: &str) -> ShellCommand {
        self.set_name(name);

        self
    }

    pub fn get_name(&self) -> &str {
        &self.name
    }
}

impl Default for ShellCommand {
    fn default() -> Self {
        Self::new("Unnamed")
    }
}

impl Display for ShellCommand {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "Shell Command: {}", self.name)
    }
}

impl Debug for ShellCommand {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self)
    }
}

impl PartialEq for ShellCommand {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
    }
}