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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
//! # command
//!
//! Runs task commands/scripts.
//!

#[cfg(test)]
#[path = "command_test.rs"]
mod command_test;

use crate::logger;
use crate::toolchain;
use crate::types::{CommandSpec, Step, UnstableFeature};
use envmnt;
use run_script;
use run_script::{IoOptions, ScriptError, ScriptOptions};
use std::io;
use std::io::{Error, ErrorKind, Read};
use std::process::{Command, ExitStatus, Output, Stdio};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Once;

/// Returns the exit code (-1 if no exit code found)
pub(crate) fn get_exit_code(exit_status: Result<ExitStatus, Error>, force: bool) -> i32 {
    match exit_status {
        Ok(code) => {
            if !code.success() {
                match code.code() {
                    Some(value) => value,
                    None => -1,
                }
            } else {
                0
            }
        }
        Err(error) => {
            if !force {
                error!("Error while executing command, error: {:#?}", error);
            }

            -1
        }
    }
}

pub(crate) fn get_exit_code_from_output(output: &io::Result<Output>, force: bool) -> i32 {
    match output {
        &Ok(ref output_struct) => get_exit_code(Ok(output_struct.status), force),
        &Err(ref error) => {
            if !force {
                error!("Error while executing command, error: {:#?}", error);
            }

            -1
        }
    }
}

/// Validates the exit code code and if not 0 or unable to validate it, panic.
pub(crate) fn validate_exit_code(code: i32) {
    if code == -1 {
        error!("Error while executing command, unable to extract exit code.");
    } else if code != 0 {
        error!("Error while executing command, exit code: {}", code);
    }
}

fn is_silent() -> bool {
    let log_level = logger::get_log_level();
    is_silent_for_level(log_level)
}

fn is_silent_for_level(log_level: String) -> bool {
    let level = logger::get_level(&log_level);

    match level {
        logger::LogLevel::ERROR => true,
        _ => false,
    }
}

fn should_print_commands_by_default() -> bool {
    let log_level = logger::get_log_level();

    if should_print_commands_for_level(log_level) {
        true
    } else {
        // if log level defaults to not printing the script commands
        // we also check if we are running in a CI env.
        // Users will not see the commands while CI builds will have the commands printed out.
        envmnt::is("CARGO_MAKE_CI")
    }
}

fn should_print_commands_for_level(log_level: String) -> bool {
    let level = logger::get_level(&log_level);

    match level {
        logger::LogLevel::VERBOSE => true,
        _ => false,
    }
}

/// Runs the requested script text and returns its output.
pub(crate) fn run_script_get_output(
    script_lines: &Vec<String>,
    script_runner: Option<String>,
    cli_arguments: &Vec<String>,
    capture_output: bool,
    print_commands: Option<bool>,
) -> Result<(i32, String, String), ScriptError> {
    let mut options = ScriptOptions::new();
    options.runner = script_runner.clone();
    options.output_redirection = if capture_output {
        IoOptions::Pipe
    } else {
        IoOptions::Inherit
    };
    options.exit_on_error = true;
    options.print_commands = match print_commands {
        Some(bool_value) => bool_value,
        None => should_print_commands_by_default(),
    };

    if is_silent() {
        options.output_redirection = IoOptions::Pipe;
        options.print_commands = false;
    } else if !capture_output && envmnt::is("CARGO_MAKE_SCRIPT_FORCE_PIPE_STDIN") {
        options.input_redirection = IoOptions::Pipe;
    }

    run_script::run(script_lines.join("\n").as_str(), cli_arguments, &options)
}

/// Runs the requested script text and panics in case of any script error.
pub(crate) fn run_script_get_exit_code(
    script_lines: &Vec<String>,
    script_runner: Option<String>,
    cli_arguments: &Vec<String>,
    validate: bool,
) -> i32 {
    let output = run_script_get_output(&script_lines, script_runner, cli_arguments, false, None);

    let exit_code = match output {
        Ok(output_struct) => output_struct.0,
        _ => -1,
    };

    if validate {
        validate_exit_code(exit_code);
    }

    exit_code
}

/// Runs the requested command and return its output.
pub(crate) fn run_command_get_output(
    command_string: &str,
    args: &Option<Vec<String>>,
    capture_output: bool,
) -> io::Result<Output> {
    let ctrl_c_handling = UnstableFeature::CtrlCHandling.is_env_set();

    debug!("Execute Command: {}", &command_string);
    let mut command = Command::new(&command_string);

    match *args {
        Some(ref args_vec) => {
            command.args(args_vec);
        }
        None => debug!("No command args defined."),
    };

    command.stdin(Stdio::inherit());

    if ctrl_c_handling {
        if capture_output {
            command.stdout(Stdio::piped()).stderr(Stdio::piped());
        }
    } else if !capture_output {
        command.stdout(Stdio::inherit()).stderr(Stdio::inherit());
    }

    info!("Execute Command: {:#?}", &command);

    let output = if ctrl_c_handling {
        spawn_command(command)
    } else {
        command.output()
    };

    debug!("Output: {:#?}", &output);

    output
}

fn spawn_command(mut command: Command) -> io::Result<Output> {
    static CTRL_C_COUNT: AtomicU32 = AtomicU32::new(0);
    static SET_CTRL_C_HANDLER_ONCE: Once = Once::new();

    SET_CTRL_C_HANDLER_ONCE.call_once(|| {
        ctrlc::set_handler(|| {
            if CTRL_C_COUNT.fetch_add(1, Ordering::SeqCst) == 0 {
                info!("Shutting down...");
            }
        })
        .expect("Failed to set Ctrl+C handler.");
    });

    if CTRL_C_COUNT.load(Ordering::Relaxed) != 0 {
        Err(Error::new(
            ErrorKind::Other,
            "Shutting down - cannot run the command.",
        ))?;
    }

    let mut process = command.spawn()?;
    let process_stdout = process.stdout.take();
    let process_stderr = process.stderr.take();

    let mut killing_process = false;

    Ok(loop {
        if !killing_process && CTRL_C_COUNT.load(Ordering::Relaxed) >= 2 {
            process.kill()?;
            killing_process = true;
        }

        if let Some(status) = process.try_wait()? {
            let mut stdout = Vec::new();
            if let Some(mut process_stdout) = process_stdout {
                process_stdout.read_to_end(&mut stdout)?;
            }

            let mut stderr = Vec::new();
            if let Some(mut process_stderr) = process_stderr {
                process_stderr.read_to_end(&mut stderr)?;
            }

            break Output {
                status,
                stdout,
                stderr,
            };
        }
    })
}

/// Runs the requested command and panics in case of any error.
pub(crate) fn run_command(command_string: &str, args: &Option<Vec<String>>, validate: bool) -> i32 {
    let output = run_command_get_output(&command_string, &args, false);

    let exit_code = get_exit_code_from_output(&output, !validate);

    if validate {
        validate_exit_code(exit_code);
    }

    exit_code
}

/// Runs the requested command and returns the stdout if exit code is valid.
pub(crate) fn run_command_get_output_string(
    command_string: &str,
    args: &Option<Vec<String>>,
) -> Option<String> {
    let output = run_command_get_output(&command_string, &args, true);

    let exit_code = get_exit_code_from_output(&output, true);

    if exit_code == 0 {
        match output {
            Ok(output_struct) => {
                let stdout = String::from_utf8_lossy(&output_struct.stdout).into_owned();
                Some(stdout)
            }
            Err(_) => None,
        }
    } else {
        None
    }
}

/// Runs the given task command.
pub(crate) fn run(step: &Step) {
    let validate = !step.config.should_ignore_errors();

    match step.config.command {
        Some(ref command_string) => {
            let command_spec = match step.config.toolchain {
                Some(ref toolchain) => {
                    toolchain::wrap_command(&toolchain, &command_string, &step.config.args)
                }
                None => CommandSpec {
                    command: command_string.to_string(),
                    args: step.config.args.clone(),
                },
            };

            run_command(&command_spec.command, &command_spec.args, validate);
        }
        None => debug!("No command defined."),
    };
}