gr/cmds/
amps.rs

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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
use std::path::Path;

use crate::{
    cli::amps::AmpsOptions::{self, Exec},
    dialog,
    error::GRError,
    io::{ShellResponse, TaskRunner},
    remote::ConfigFilePath,
    shell, Result,
};

pub fn execute(options: AmpsOptions, config_file: ConfigFilePath) -> Result<()> {
    match options {
        Exec(amp_name_args) => {
            let base_path = config_file.directory();
            let amps_scripts = base_path.join("amps");
            if amp_name_args.is_empty() {
                let runner = shell::BlockingCommand;
                let amps = list_amps(runner, amps_scripts.to_str().unwrap())?;
                let amp_script = dialog::fuzzy_select(amps)?;
                let stream_runner = shell::StreamingCommand;
                let amp_runner = Amp::new(dialog::prompt_args, &stream_runner);
                amp_runner.exec_amps(amp_script, base_path)?;
                return Ok(());
            }
            let stream_runner = shell::StreamingCommand;
            let amp_name_args: Vec<&str> = amp_name_args.split(' ').collect();
            let amp_name = amp_name_args[0];
            let amp_path = amps_scripts.join(amp_name);
            let args = amp_name_args[1..].join(" ");
            stream_runner.run(vec![&amp_path.to_str().unwrap(), &args.as_str()])?;
            Ok(())
        }
        _ => {
            let base_path = config_file.directory();
            let amps_scripts = base_path.join("amps");
            let runner = shell::BlockingCommand;
            let amps = list_amps(runner, amps_scripts.to_str().unwrap())?;
            for amp in amps {
                println!("{}", amp);
            }
            Ok(())
        }
    }
}

fn list_amps(
    runner: impl TaskRunner<Response = ShellResponse>,
    amps_path: &str,
) -> Result<Vec<String>> {
    let cmd = vec!["ls", amps_path];
    let response = runner.run(cmd)?;
    if response.body.is_empty() {
        return Err(GRError::PreconditionNotMet(format!(
            "No amps are available in {}. Please check \
            https://github.com/jordilin/gitar-amps for installation instructions",
            amps_path
        ))
        .into());
    }
    let amps: Vec<String> = response.body.split('\n').map(|s| s.to_string()).collect();
    Ok(amps)
}

enum AmpPrompts {
    Args,
    Help,
    Exit,
}

impl From<&String> for AmpPrompts {
    fn from(s: &String) -> Self {
        match s.as_str() {
            "-h" | "--help" | "help" | "h" => AmpPrompts::Help,
            "exit" | "cancel" | "quit" | "q" => AmpPrompts::Exit,
            _ => AmpPrompts::Args,
        }
    }
}

struct Amp<'a, A, R> {
    args_prompter_fn: A,
    runner: &'a R,
}

impl<'a, A, R> Amp<'a, A, R> {
    fn new(args: A, runner: &'a R) -> Self {
        Self {
            args_prompter_fn: args,
            runner,
        }
    }
}

impl<A: Fn() -> String, R: TaskRunner<Response = ShellResponse>> Amp<'_, A, R> {
    fn exec_amps(&self, amp: String, base_path: &Path) -> Result<()> {
        let mut args = (self.args_prompter_fn)();
        loop {
            match (&args).into() {
                AmpPrompts::Help => {
                    let cmd_path = base_path.join("amps").join(&amp);
                    let cmd = vec![cmd_path.to_str().unwrap(), "--help"];
                    self.runner.run(cmd)?;
                    args = (self.args_prompter_fn)();
                }
                AmpPrompts::Exit => {
                    return Ok(());
                }
                AmpPrompts::Args => break,
            }
        }
        let cmd_path = base_path.join("amps").join(amp);
        let mut cmd = vec![cmd_path.to_str().unwrap()];
        for arg in args.split_whitespace() {
            cmd.push(arg);
        }
        self.runner.run(cmd)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::cell::RefCell;

    use crate::test::utils::MockRunner;

    use super::*;

    #[test]
    fn test_exec_amp_with_help_and_run() {
        let response_help = ShellResponse::builder()
            .status(0)
            .body("this is the help".to_string())
            .build()
            .unwrap();
        let response = ShellResponse::builder()
            .status(0)
            .body("response output".to_string())
            .build()
            .unwrap();
        let amp_script = "list_releases".to_string();
        let runner = MockRunner::new(vec![response, response_help]);
        let prompted_args = RefCell::new(vec![
            "github.com/jordilin/gitar".to_string(),
            "help".to_string(),
        ]);
        let args_prompter_fn = || prompted_args.borrow_mut().pop().unwrap();
        let amp_runner = Amp::new(args_prompter_fn, &runner);
        let base_path = Path::new("/tmp");
        assert!(amp_runner.exec_amps(amp_script, base_path).is_ok());
        assert_eq!(2, *runner.run_count.borrow());
    }

    #[test]
    fn test_exec_amp_with_help_and_exit() {
        let response_help = ShellResponse::builder()
            .status(0)
            .body("this is the help".to_string())
            .build()
            .unwrap();
        let amp_script = "list_releases".to_string();
        let runner = MockRunner::new(vec![response_help]);
        let prompted_args = RefCell::new(vec!["exit".to_string(), "help".to_string()]);
        let args_prompter_fn = || prompted_args.borrow_mut().pop().unwrap();
        let amp_runner = Amp::new(args_prompter_fn, &runner);
        let base_path = Path::new("/tmp");
        assert!(amp_runner.exec_amps(amp_script, base_path).is_ok());
        assert_eq!(1, *runner.run_count.borrow());
    }

    #[test]
    fn test_list_amps_error_if_none_available() {
        let response = ShellResponse::builder()
            .status(0)
            .body("".to_string())
            .build()
            .unwrap();
        let runner = MockRunner::new(vec![response]);
        let amps_path = "/tmp/amps";
        let amps = list_amps(runner, amps_path);
        match amps {
            Err(err) => match err.downcast_ref::<GRError>() {
                Some(GRError::PreconditionNotMet(msg)) => {
                    assert_eq!(
                        "No amps are available in /tmp/amps. Please check \
                        https://github.com/jordilin/gitar-amps for installation instructions",
                        msg
                    );
                }
                _ => panic!("Expected error"),
            },
            Ok(_) => panic!("Expected error"),
        }
    }
}