cargo-run 0.5.0

A powerful, fast, and developer-friendly CLI tool for managing project scripts in Rust. Think npm scripts, make, or just — but built specifically for the Rust ecosystem.
Documentation
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
//! This module provides the functionality to run scripts defined in `Scripts.toml`.

use std::{collections::HashMap, env, process::{Command, Stdio}, sync::{Arc, Mutex}, time::{Duration, Instant}};
use serde::Deserialize;
use emoji::symbols;
use colored::*;

/// Enum representing a script, which can be either a default command or a detailed script with additional metadata.
#[derive(Deserialize, Debug)]
#[serde(untagged)]
pub enum Script {
    Default(String),
    Inline {
        command: Option<String>,
        requires: Option<Vec<String>>,
        toolchain: Option<String>,
        info: Option<String>,
        env: Option<HashMap<String, String>>,
        include: Option<Vec<String>>,
        interpreter: Option<String>,
    },
    CILike {
        script: String,
        command: Option<String>,
        requires: Option<Vec<String>>,
        toolchain: Option<String>,
        info: Option<String>,
        env: Option<HashMap<String, String>>,
        include: Option<Vec<String>>,
        interpreter: Option<String>,
    }
}

/// Struct representing the collection of scripts defined in Scripts.toml.
#[derive(Deserialize)]
pub struct Scripts {
    pub global_env: Option<HashMap<String, String>>,
    pub scripts: HashMap<String, Script>
}

use crate::error::{CargoScriptError, create_tool_not_found_error, create_toolchain_not_found_error};

/// Run a script by name, executing any included scripts in sequence.
///
/// This function runs a script and any scripts it includes, measuring the execution time
/// for each script and printing performance metrics.
///
/// # Arguments
///
/// * `scripts` - A reference to the collection of scripts.
/// * `script_name` - The name of the script to run.
/// * `env_overrides` - A vector of command line environment variable overrides.
/// * `dry_run` - If true, only show what would be executed without actually running it.
///
/// # Errors
///
/// Returns an error if the script is not found or if execution fails.
pub fn run_script(scripts: &Scripts, script_name: &str, env_overrides: Vec<String>, dry_run: bool) -> Result<(), CargoScriptError> {
    if dry_run {
        println!("{}", "DRY-RUN MODE: Preview of what would be executed".bold().yellow());
        println!("{}\n", "=".repeat(80).yellow());
        dry_run_script(scripts, script_name, env_overrides, 0)?;
        println!("\n{}", "No commands were actually executed.".italic().green());
        return Ok(());
    }

    let script_durations = Arc::new(Mutex::new(HashMap::new()));

    fn run_script_with_level(
        scripts: &Scripts,
        script_name: &str,
        env_overrides: Vec<String>,
        level: usize,
        script_durations: Arc<Mutex<HashMap<String, Duration>>>,
    ) -> Result<(), CargoScriptError> {
        let mut env_vars = scripts.global_env.clone().unwrap_or_default();
        let indent = "  ".repeat(level);

        let script_start_time = Instant::now();

        if let Some(script) = scripts.scripts.get(script_name) {
            match script {
                Script::Default(cmd) => {
                    let msg = format!(
                        "{}{}  {}: [ {} ]",
                        indent,
                        symbols::other_symbol::CHECK_MARK.glyph,
                        "Running script".green(),
                        script_name
                    );
                    println!("{}\n", msg);
                    let final_env = get_final_env(&env_vars, &env_overrides);
                    apply_env_vars(&env_vars, &env_overrides);
                    execute_command(None, cmd, None, &final_env)?;
                }
                Script::Inline {
                    command,
                    info,
                    env,
                    include,
                    interpreter,
                    requires,
                    toolchain,
                    ..
                } | Script::CILike {
                    command,
                    info,
                    env,
                    include,
                    interpreter,
                    requires,
                    toolchain,
                    ..
                } => {
                    if let Err(e) = check_requirements(requires.as_deref().unwrap_or(&[]), toolchain.as_ref()) {
                        return Err(e);
                    }

                    let description = format!(
                        "{}  {}: {}",
                        emoji::objects::book_paper::BOOKMARK_TABS.glyph,
                        "Description".green(),
                        info.as_deref().unwrap_or("No description provided")
                    );

                    if let Some(include_scripts) = include {
                        let msg = format!(
                            "{}{}  {}: [ {} ]  {}",
                            indent,
                            symbols::other_symbol::CHECK_MARK.glyph,
                            "Running include script".green(),
                            script_name,
                            description
                        );
                        println!("{}\n", msg);
                        for include_script in include_scripts {
                            run_script_with_level(
                                scripts,
                                include_script,
                                env_overrides.clone(),
                                level + 1,
                                script_durations.clone(),
                            )?;
                        }
                    }

                    if let Some(cmd) = command {
                        let msg = format!(
                            "{}{}  {}: [ {} ]  {}",
                            indent,
                            symbols::other_symbol::CHECK_MARK.glyph,
                            "Running script".green(),
                            script_name,
                            description
                        );
                        println!("{}\n", msg);

                        if let Some(script_env) = env {
                            env_vars.extend(script_env.clone());
                        }
                        let final_env = get_final_env(&env_vars, &env_overrides);
                        apply_env_vars(&env_vars, &env_overrides);
                        execute_command(interpreter.as_deref(), cmd, toolchain.as_deref(), &final_env)?;
                    }
                }
            }

            let script_duration = script_start_time.elapsed();
            if level > 0 || scripts.scripts.get(script_name).map_or(false, |s| matches!(s, Script::Default(_) | Script::Inline { command: Some(_), .. } | Script::CILike { command: Some(_), .. })) {
                script_durations
                    .lock()
                    .unwrap()
                    .insert(script_name.to_string(), script_duration);
            }
            Ok(())
        } else {
            let available_scripts: Vec<String> = scripts.scripts.keys().cloned().collect();
            return Err(CargoScriptError::ScriptNotFound {
                script_name: script_name.to_string(),
                available_scripts,
            });
        }
    }

    run_script_with_level(scripts, script_name, env_overrides, 0, script_durations.clone())?;

    let durations = script_durations.lock().unwrap();
    if !durations.is_empty() {
        let total_duration: Duration = durations.values().cloned().sum();
        
        println!("\n");
        println!("{}", "Scripts Performance".bold().yellow());
        println!("{}", "-".repeat(80).yellow());
        for (script, duration) in durations.iter() {
            println!("✔️  Script: {:<25}  🕒 Running time: {:.2?}", script.green(), duration);
        }
        if !durations.is_empty() {
            println!("\n🕒 Total running time: {:.2?}", total_duration);
        }
    }
    
    Ok(())
}


/// Get the final environment variables map from global, script-specific, and command line overrides.
///
/// This function computes the final environment variables, giving precedence
/// to command line overrides over script-specific variables, and script-specific variables over global variables.
///
/// # Arguments
///
/// * `env_vars` - A reference to the global environment variables.
/// * `env_overrides` - A vector of command line environment variable overrides.
///
/// # Returns
///
/// A HashMap containing the final environment variables.
fn get_final_env(env_vars: &HashMap<String, String>, env_overrides: &[String]) -> HashMap<String, String> {
    let mut final_env = env_vars.clone();

    for override_str in env_overrides {
        if let Some((key, value)) = override_str.split_once('=') {
            final_env.insert(key.to_string(), value.to_string());
        }
    }

    final_env
}

/// Apply environment variables from global, script-specific, and command line overrides.
///
/// This function sets the environment variables for the script execution, giving precedence
/// to command line overrides over script-specific variables, and script-specific variables over global variables.
///
/// # Arguments
///
/// * `env_vars` - A reference to the global environment variables.
/// * `env_overrides` - A vector of command line environment variable overrides.
fn apply_env_vars(env_vars: &HashMap<String, String>, env_overrides: &[String]) {
    let final_env = get_final_env(env_vars, env_overrides);

    for (key, value) in &final_env {
        // SAFETY: Setting environment variables for child processes is safe.
        // We're in a single-threaded context when setting these variables,
        // and they're only used for the child process spawned immediately after.
        unsafe {
            env::set_var(key, value);
        }
    }
}

/// Execute a command using the specified interpreter, or the default shell if none is specified.
///
/// This function runs the command with the appropriate interpreter, depending on the operating system
/// and the specified interpreter.
///
/// # Arguments
///
/// * `interpreter` - An optional string representing the interpreter to use.
/// * `command` - The command to execute.
/// * `toolchain` - An optional string representing the toolchain to use.
/// * `env_vars` - A reference to the environment variables to set for the command.
///
/// # Errors
///
/// Returns an error if it fails to execute the command.
fn execute_command(interpreter: Option<&str>, command: &str, toolchain: Option<&str>, env_vars: &HashMap<String, String>) -> Result<(), CargoScriptError> {
    let mut cmd = if let Some(tc) = toolchain {
        let mut command_with_toolchain = format!("cargo +{} ", tc);
        command_with_toolchain.push_str(command);
        let mut cmd = Command::new("sh");
        cmd.arg("-c")
            .arg(command_with_toolchain)
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit());
        for (key, value) in env_vars {
            cmd.env(key, value);
        }
        cmd.spawn()
            .map_err(|e| CargoScriptError::ExecutionError {
                script: "unknown".to_string(),
                command: command.to_string(),
                source: e,
            })?
    } else {
        match interpreter {
            Some("bash") => {
                let mut cmd = Command::new("bash");
                cmd.arg("-c")
                    .arg(command)
                    .stdout(Stdio::inherit())
                    .stderr(Stdio::inherit());
                for (key, value) in env_vars {
                    cmd.env(key, value);
                }
                cmd.spawn()
                    .map_err(|e| CargoScriptError::ExecutionError {
                        script: "unknown".to_string(),
                        command: command.to_string(),
                        source: e,
                    })?
            },
            Some("zsh") => {
                let mut cmd = Command::new("zsh");
                cmd.arg("-c")
                    .arg(command)
                    .stdout(Stdio::inherit())
                    .stderr(Stdio::inherit());
                for (key, value) in env_vars {
                    cmd.env(key, value);
                }
                cmd.spawn()
                    .map_err(|e| CargoScriptError::ExecutionError {
                        script: "unknown".to_string(),
                        command: command.to_string(),
                        source: e,
                    })?
            },
            Some("powershell") => {
                let mut cmd = Command::new("powershell");
                cmd.args(&["-NoProfile", "-Command", command])
                    .stdout(Stdio::inherit())
                    .stderr(Stdio::inherit());
                for (key, value) in env_vars {
                    cmd.env(key, value);
                }
                cmd.spawn()
                    .map_err(|e| CargoScriptError::ExecutionError {
                        script: "unknown".to_string(),
                        command: command.to_string(),
                        source: e,
                    })?
            },
            Some("cmd") => {
                let mut cmd = Command::new("cmd");
                cmd.args(&["/C", command])
                    .stdout(Stdio::inherit())
                    .stderr(Stdio::inherit());
                for (key, value) in env_vars {
                    cmd.env(key, value);
                }
                cmd.spawn()
                    .map_err(|e| CargoScriptError::ExecutionError {
                        script: "unknown".to_string(),
                        command: command.to_string(),
                        source: e,
                    })?
            },
            Some(other) => {
                let mut cmd = Command::new(other);
                cmd.arg("-c")
                    .arg(command)
                    .stdout(Stdio::inherit())
                    .stderr(Stdio::inherit());
                for (key, value) in env_vars {
                    cmd.env(key, value);
                }
                cmd.spawn()
                    .map_err(|e| CargoScriptError::ExecutionError {
                        script: "unknown".to_string(),
                        command: command.to_string(),
                        source: e,
                    })?
            },
            None => {
                if cfg!(target_os = "windows") {
                    let mut cmd = Command::new("cmd");
                    cmd.args(&["/C", command])
                        .stdout(Stdio::inherit())
                        .stderr(Stdio::inherit());
                    for (key, value) in env_vars {
                        cmd.env(key, value);
                    }
                    cmd.spawn()
                        .map_err(|e| CargoScriptError::ExecutionError {
                            script: "unknown".to_string(),
                            command: command.to_string(),
                            source: e,
                        })?
                } else {
                    let mut cmd = Command::new("sh");
                    cmd.arg("-c")
                        .arg(command)
                        .stdout(Stdio::inherit())
                        .stderr(Stdio::inherit());
                    for (key, value) in env_vars {
                        cmd.env(key, value);
                    }
                    cmd.spawn()
                        .map_err(|e| CargoScriptError::ExecutionError {
                            script: "unknown".to_string(),
                            command: command.to_string(),
                            source: e,
                        })?
                }
            }
        }
    };

    cmd.wait().map_err(|e| CargoScriptError::ExecutionError {
        script: "unknown".to_string(),
        command: command.to_string(),
        source: e,
    })?;
    
    Ok(())
}

/// Display what would be executed in dry-run mode without actually running anything.
///
/// # Arguments
///
/// * `scripts` - A reference to the collection of scripts.
/// * `script_name` - The name of the script to preview.
/// * `env_overrides` - A vector of command line environment variable overrides.
/// * `level` - The nesting level for indentation.
fn dry_run_script(
    scripts: &Scripts,
    script_name: &str,
    env_overrides: Vec<String>,
    level: usize,
) -> Result<(), CargoScriptError> {
    let indent = "  ".repeat(level);
    let mut env_vars = scripts.global_env.clone().unwrap_or_default();

    if let Some(script) = scripts.scripts.get(script_name) {
        match script {
            Script::Default(cmd) => {
                println!(
                    "{}{}  {}: [ {} ]",
                    indent,
                    "📋".yellow(),
                    "Would run script".cyan(),
                    script_name.bold()
                );
                println!("{}    Command: {}", indent, cmd.green());
                let final_env = get_final_env(&env_vars, &env_overrides);
                if !final_env.is_empty() {
                    println!("{}    Environment variables:", indent);
                    for (key, value) in &final_env {
                        println!("{}      {} = {}", indent, key.cyan(), value.green());
                    }
                }
                println!();
            }
            Script::Inline {
                command,
                info,
                env,
                include,
                interpreter,
                requires,
                toolchain,
                ..
            } | Script::CILike {
                command,
                info,
                env,
                include,
                interpreter,
                requires,
                toolchain,
                ..
            } => {
                // Check requirements (but don't fail in dry-run, just warn)
                if let Some(reqs) = requires {
                    if !reqs.is_empty() {
                        println!(
                            "{}{}  {}: [ {} ]",
                            indent,
                            "🔍".yellow(),
                            "Would check requirements".cyan(),
                            script_name.bold()
                        );
                        for req in reqs {
                            println!("{}      - {}", indent, req.green());
                        }
                        println!();
                    }
                }

                if let Some(tc) = toolchain {
                    println!(
                        "{}{}  {}: {}",
                        indent,
                        "🔧".yellow(),
                        "Would use toolchain".cyan(),
                        tc.bold().green()
                    );
                    println!();
                }

                if let Some(desc) = info {
                    println!(
                        "{}{}  {}: {}",
                        indent,
                        "📝".yellow(),
                        "Description".cyan(),
                        desc.green()
                    );
                    println!();
                }

                if let Some(include_scripts) = include {
                    println!(
                        "{}{}  {}: [ {} ]",
                        indent,
                        "📋".yellow(),
                        "Would run include scripts".cyan(),
                        script_name.bold()
                    );
                    if let Some(desc) = info {
                        println!("{}    Description: {}", indent, desc.green());
                    }
                    println!();
                    for include_script in include_scripts {
                        dry_run_script(scripts, include_script, env_overrides.clone(), level + 1)?;
                    }
                }

                if let Some(cmd) = command {
                    println!(
                        "{}{}  {}: [ {} ]",
                        indent,
                        "📋".yellow(),
                        "Would run script".cyan(),
                        script_name.bold()
                    );
                    
                    if let Some(interp) = interpreter {
                        println!("{}    Interpreter: {}", indent, interp.green());
                    }
                    
                    if let Some(tc) = toolchain {
                        println!("{}    Toolchain: {}", indent, tc.green());
                    }
                    
                    println!("{}    Command: {}", indent, cmd.green());
                    
                    if let Some(script_env) = env {
                        env_vars.extend(script_env.clone());
                    }
                    
                    let final_env = get_final_env(&env_vars, &env_overrides);
                    if !final_env.is_empty() {
                        println!("{}    Environment variables:", indent);
                        for (key, value) in &final_env {
                            println!("{}      {} = {}", indent, key.cyan(), value.green());
                        }
                    }
                    println!();
                }
            }
        }
    } else {
        let available_scripts: Vec<String> = scripts.scripts.keys().cloned().collect();
        return Err(CargoScriptError::ScriptNotFound {
            script_name: script_name.to_string(),
            available_scripts,
        });
    }
    
    Ok(())
}

/// Check if the required tools and toolchain are installed.
/// 
/// This function checks if the required tools and toolchain are installed on the system.
/// If any of the requirements are not met, an error message is returned.
/// 
/// # Arguments
/// 
/// * `requires` - A slice of strings representing the required tools.
/// * `toolchain` - An optional string representing the required toolchain.
/// 
/// # Returns
/// 
/// An empty result if all requirements are met, otherwise an error.
/// 
/// # Errors
/// 
/// This function will return an error if any of the requirements are not met.
fn check_requirements(requires: &[String], toolchain: Option<&String>) -> Result<(), CargoScriptError> {
    for req in requires {
        if let Some((tool, version)) = req.split_once(' ') {
            let output = Command::new(tool)
                .arg("--version")
                .output()
                .map_err(|_| create_tool_not_found_error(tool, Some(version)))?;
            let output_str = String::from_utf8_lossy(&output.stdout);

            if !output_str.contains(version) {
                return Err(create_tool_not_found_error(tool, Some(version)));
            }
        } else {
            // Just check if the tool is installed
            Command::new(req)
                .output()
                .map_err(|_| create_tool_not_found_error(req, None))?;
        }
    }

    if let Some(tc) = toolchain {
        let output = Command::new("rustup")
            .arg("toolchain")
            .arg("list")
            .output()
            .map_err(|_| create_tool_not_found_error("rustup", None))?;
        let output_str = String::from_utf8_lossy(&output.stdout);

        if !output_str.contains(tc) {
            return Err(create_toolchain_not_found_error(tc));
        }
    }

    Ok(())
}