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
// Copyright © 2015 - Samuel Dolt <samuel@dolt.ch>
//
// Licensed under the MIT license. This file may not be copied, modified,
// or distributed except according to those terms.
//
// See the COPYRIGHT file at the top-level directory of this distribution.

pub use Command;

/// This wrapper hold a command object and a arguments vectors.
pub struct CmdWrapper {
    cmd: Box<Command>,
    args: Vec<String>,
}

impl CmdWrapper {
    /// Create a new wrapper
    pub fn new(cmd: Box<Command>, args: Vec<String>) -> CmdWrapper {
        CmdWrapper {
            cmd: cmd,
            args: args,
        }
    }

    /// Get the name of the wrapped command
    pub fn name<'a>(&self) -> &'a str {
        self.cmd.name()
    }

    /// Get a string with help info
    pub fn help<'a>(&self) -> &'a str {
        self.cmd.help()
    }

    /// Print the help of the wrapper command
    pub fn print_help(&self) {
        println!("{}", self.cmd.help());
    }

    /// Run the command
    pub fn run(&self) {
        self.cmd.run(&self.args);
    }

    /// Return the embedded command
    pub fn unwrap(self) -> Box<Command> {
        self.cmd
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    struct FakeCmd;

    static mut FakeCmdRunCalled: bool = false;

    impl Command for FakeCmd {
        fn name<'a>(&self) -> &'a str {
            "fake"
        }
        fn help<'a>(&self) -> &'a str {
            "help for fake"
        }
        fn description<'a>(&self) -> &'a str {
            "descr. for fake"
        }
        fn run(&self, argv: &Vec<String>) {
            unsafe {
                FakeCmdRunCalled = true;
            }
            assert_eq!(argv[0], "test");
        }
    }

    #[test]
    fn test_cmd_wrapper() {
        let wrap = CmdWrapper::new(Box::new(FakeCmd), vec!["test".to_string()]);

        assert_eq!(wrap.name(), "fake");
        assert_eq!(wrap.help(), "help for fake");

        wrap.run();
        unsafe {
            assert_eq!(FakeCmdRunCalled, true);
        }

        let fake = wrap.unwrap();
        assert_eq!(fake.description(), "descr. for fake");
    }
}