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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
use dialoguer::{theme::ColorfulTheme, MultiSelect};

#[derive(Debug, clap::Parser)]
#[clap(
    name = "together",
    author = "Michael Lawrence",
    about = "Run multiple commands in parallel selectively by an interactive prompt."
)]
pub struct TogetherArgs {
    #[clap(subcommand)]
    pub command: Option<ArgsCommands>,

    #[clap(short, long, help = "Ignore configuration file.")]
    pub no_config: bool,

    #[clap(short, long = "cwd", help = "Directory to run commands in.")]
    pub working_directory: Option<String>,

    #[clap(short, long, help = "Only run the startup commands.")]
    pub init_only: bool,

    #[clap(short, long = "quiet", help = "Quiet mode for startup commands.")]
    pub quiet_startup: bool,

    #[clap(
        short,
        long,
        help = "Run all commands tagged under provided recipe(s). Use comma to separate multiple recipes.",
        value_delimiter = ','
    )]
    pub recipes: Option<Vec<String>>,
}

#[derive(Debug, clap::Parser)]
pub enum ArgsCommands {
    #[clap(
        name = "run",
        about = "Run multiple commands in parallel selectively by an interactive prompt."
    )]
    Run(RunCommand),

    #[clap(name = "rerun", about = "Rerun the last together session.")]
    Rerun(RerunCommand),

    #[clap(name = "load", about = "Run commands from a configuration file.")]
    Load(LoadCommand),
}

#[derive(Debug, clap::Parser)]
pub struct LoadCommand {
    #[clap(required = true, help = "Configuration file path.")]
    pub path: String,

    #[clap(short, long, help = "Only run the startup commands.")]
    pub init_only: bool,

    #[clap(
        short,
        long,
        help = "Run all commands tagged under provided recipe(s). Use comma to separate multiple recipes.",
        value_delimiter = ','
    )]
    pub recipes: Option<Vec<String>>,
}

#[derive(Debug, clap::Parser)]
pub struct RerunCommand {}

#[derive(Debug, Clone, clap::Parser)]
pub struct RunCommand {
    #[clap(
        last = true,
        required = true,
        help = "Commands to run. e.g. 'ls -l', 'echo hello'"
    )]
    pub commands: Vec<String>,

    #[clap(short, long, help = "Run all commands without prompting.")]
    pub all: bool,

    #[clap(
        short,
        long,
        help = "Exit on the first command that exits with a non-zero status."
    )]
    pub exit_on_error: bool,

    #[clap(
        short,
        long,
        help = "Quit the program when all commands have completed."
    )]
    pub quit_on_completion: bool,

    #[clap(short, long, help = "Enable raw stdout/stderr output.")]
    pub raw: bool,

    #[clap(short, long, help = "Only run the startup commands.")]
    pub init_only: bool,
}

pub struct Terminal;

impl Terminal {
    pub fn select_multiple<'a, T: std::fmt::Display>(
        prompt: &'a str,
        items: &'a [T],
    ) -> Vec<&'a T> {
        let mut opts_commands = vec![];
        let defaults = items.iter().map(|_| false).collect::<Vec<_>>();
        let multi_select = MultiSelect::with_theme(&ColorfulTheme::default())
            .with_prompt(prompt)
            .items(items)
            .defaults(&defaults[..])
            .interact();
        let selections = multi_select.map_err(map_dialoguer_err).unwrap();
        for index in selections {
            opts_commands.push(&items[index]);
        }
        opts_commands
    }
    pub fn select_single<'a, T: std::fmt::Display>(
        prompt: &'a str,
        items: &'a [T],
    ) -> Option<&'a T> {
        let index = Self::select_single_index(prompt, items)?;
        Some(&items[index])
    }
    pub fn select_single_index<'a, T: std::fmt::Display>(
        prompt: &'a str,
        items: &'a [T],
    ) -> Option<usize> {
        let index = dialoguer::Select::with_theme(&ColorfulTheme::default())
            .with_prompt(prompt)
            .items(items)
            .interact_opt()
            .map_err(map_dialoguer_err)
            .unwrap()?;
        Some(index)
    }
    pub fn select_ordered<'a, T: std::fmt::Display>(
        prompt: &'a str,
        items: &'a [T],
    ) -> Option<Vec<&'a T>> {
        let mut opts_commands = vec![];
        let sort = dialoguer::Sort::with_theme(&ColorfulTheme::default())
            .with_prompt(prompt)
            .items(items)
            .interact_opt()
            .map_err(map_dialoguer_err)
            .unwrap()?;
        for index in sort {
            opts_commands.push(&items[index]);
        }
        Some(opts_commands)
    }
    pub fn log(message: &str) {
        // print message with green colorized prefix
        crate::t_println!("{}[+] {}{}", "\x1b[32m", "\x1b[0m", message);
    }
    pub fn log_error(message: &str) {
        // print message with red colorized prefix
        crate::t_eprintln!("{}[!] {}{}", "\x1b[31m", "\x1b[0m", message);
    }
}

fn map_dialoguer_err(err: dialoguer::Error) -> ! {
    let dialoguer::Error::IO(io) = err;
    match io.kind() {
        std::io::ErrorKind::Interrupted | std::io::ErrorKind::BrokenPipe => {
            std::process::exit(0);
        }
        _ => {
            panic!("Unexpected error: {}", io);
        }
    }
}

pub mod stdout {
    /// macro for logging like println! but with a carriage return
    #[macro_export]
    macro_rules! t_println {
        () => {
            ::std::print!("\r\n");
        };
        ($fmt:tt) => {
            ::std::print!(concat!($fmt, "\r\n"));
        };
        ($fmt:tt, $($arg:tt)*) => {
            ::std::print!(concat!($fmt, "\r\n"), $($arg)*);
        };
    }

    /// macro for logging like eprintln! but with a carriage return
    #[macro_export]
    macro_rules! t_eprintln {
        () => {
            ::std::eprint!("\r\n");
        };
        ($fmt:tt) => {
            ::std::eprint!(concat!($fmt, "\r\n"));
        };
        ($fmt:tt, $($arg:tt)*) => {
            ::std::eprint!(concat!($fmt, "\r\n"), $($arg)*);
        };
    }
}

/// macro for logging like println! but with a green prefix
#[macro_export]
macro_rules! log {
    ($($arg:tt)*) => {
        $crate::terminal::Terminal::log(&format!($($arg)*));
    };
}

/// macro for logging like eprintln! but with a red prefix
#[macro_export]
macro_rules! log_err {
    ($($arg:tt)*) => {
        $crate::terminal::Terminal::log_error(&format!($($arg)*));
    };
}