cargo-run 0.6.0

A powerful, fast, and developer-friendly CLI tool for managing project scripts in Rust. Workspace-aware, cargo-script ready, with hooks, parallel execution, watch mode, and CI/CD templates.
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
//! Error handling module for cargo-script CLI tool.
//!
//! This module provides custom error types and utilities for better error messages.

use colored::*;
use std::fmt;

/// Custom error type for cargo-script operations.
#[derive(Debug)]
pub enum CargoScriptError {
    /// Script file not found or cannot be read
    ScriptFileNotFound {
        path: String,
        source: std::io::Error,
    },
    /// Invalid TOML syntax in Scripts.toml
    InvalidToml {
        path: String,
        message: String,
        line: Option<usize>,
    },
    /// Script not found in Scripts.toml
    ScriptNotFound {
        script_name: String,
        available_scripts: Vec<String>,
    },
    /// Required tool is missing or wrong version
    ToolNotFound {
        tool: String,
        required_version: Option<String>,
        suggestion: String,
    },
    /// Toolchain not installed
    ToolchainNotFound {
        toolchain: String,
        suggestion: String,
    },
    /// Script execution error
    ExecutionError {
        script: String,
        command: String,
        source: std::io::Error,
    },
    /// Windows self-replacement error (trying to replace cargo-script while it's running)
    WindowsSelfReplacementError {
        script: String,
        command: String,
    },
    /// Workspace `Cargo.toml` could not be found at or above the given path
    WorkspaceNotFound {
        path: String,
    },
    /// One or more scripts failed during a parallel execution
    ParallelExecutionFailed {
        failed_scripts: Vec<String>,
    },
    /// Requested template does not exist in the registry
    TemplateNotFound {
        name: String,
        available: Vec<String>,
    },
    /// `cargo script` (single-file packages) is not available on the current toolchain
    CargoScriptNotAvailable {
        suggestion: String,
    },
    /// A pre/post/on_success/on_failure hook failed
    HookFailed {
        hook_name: String,
        script_name: String,
        reason: String,
    },
    /// Watch mode error (file system event subscription failed)
    WatchError {
        path: String,
        message: String,
    },
    /// A required script argument/parameter was not provided
    MissingScriptArgument {
        script_name: String,
        argument: String,
    },
}

impl fmt::Display for CargoScriptError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CargoScriptError::ScriptFileNotFound { path, source } => {
                write!(
                    f,
                    "{}\n\n{}\n  {}\n  {}\n\n{}\n  {}\n  {}",
                    "❌ Script file not found".red().bold(),
                    "Error:".yellow().bold(),
                    format!("Path: {}", path).white(),
                    format!("Reason: {}", source).white(),
                    "Quick fix:".yellow().bold(),
                    format!("Run '{}' to create Scripts.toml in the current directory", "cargo script init".green()).white(),
                    format!("Or use '{}' to specify a different file path", "--scripts-path <path>".green()).white()
                )
            }
            CargoScriptError::InvalidToml { path, message, line } => {
                let line_info = if let Some(l) = line {
                    format!("\n  Line {}: {}", l, "See error details above".yellow())
                } else {
                    String::new()
                };
                write!(
                    f,
                    "{}\n\n{}\n  {}\n  {}{}\n\n{}\n  {}\n  {}\n  {}",
                    "❌ Invalid TOML syntax".red().bold(),
                    "Error:".yellow().bold(),
                    format!("File: {}", path).white(),
                    format!("Message: {}", message).white(),
                    line_info,
                    "Quick fix:".yellow().bold(),
                    "Check your Scripts.toml syntax. Common issues:".white(),
                    "  - Missing quotes around strings\n  - Trailing commas in arrays\n  - Invalid table syntax".white(),
                    format!("Validate your file with: {}", "cargo script validate".green()).white()
                )
            }
            CargoScriptError::ScriptNotFound {
                script_name,
                available_scripts,
            } => {
                let suggestions = find_similar_scripts(script_name, available_scripts);
                let suggestion_text = if !suggestions.is_empty() {
                    format!(
                        "\n\n{}\n  {}",
                        "Did you mean:".yellow().bold(),
                        suggestions
                            .iter()
                            .map(|s| format!("{}", s.green()))
                            .collect::<Vec<_>>()
                            .join("\n")
                    )
                } else if !available_scripts.is_empty() {
                    format!(
                        "\n\n{}\n  {}",
                        "Available scripts:".yellow().bold(),
                        available_scripts
                            .iter()
                            .take(10)
                            .map(|s| format!("{}", s.cyan()))
                            .collect::<Vec<_>>()
                            .join("\n")
                    )
                } else {
                    String::new()
                };

                write!(
                    f,
                    "{}\n\n{}\n  {}{}\n\n{}\n  {}\n  {}",
                    "❌ Script not found".red().bold(),
                    "Error:".yellow().bold(),
                    format!("Script '{}' not found in Scripts.toml", script_name.bold()).white(),
                    suggestion_text,
                    "Quick fix:".yellow().bold(),
                    format!("Run '{}' to see all available scripts", "cargo script show".green()).white(),
                    format!("Or use '{}' to initialize Scripts.toml if it doesn't exist", "cargo script init".green()).white()
                )
            }
            CargoScriptError::ToolNotFound {
                tool,
                required_version,
                suggestion,
            } => {
                let version_info = if let Some(v) = required_version {
                    format!(" (required: {})", v)
                } else {
                    String::new()
                };
                write!(
                    f,
                    "{}\n\n{}\n  {}{}\n\n{}\n  {}",
                    "❌ Required tool not found".red().bold(),
                    "Error:".yellow().bold(),
                    format!("Tool '{}'{} is not installed or not in PATH", tool.bold(), version_info).white(),
                    suggestion,
                    "Suggestion:".yellow().bold(),
                    format!("Install '{}' and ensure it's available in your PATH", tool).white()
                )
            }
            CargoScriptError::ToolchainNotFound {
                toolchain,
                suggestion,
            } => {
                write!(
                    f,
                    "{}\n\n{}\n  {}\n\n{}\n{}",
                    "❌ Toolchain not installed".red().bold(),
                    "Error:".yellow().bold(),
                    format!("Toolchain '{}' is not installed", toolchain.bold()).white(),
                    "Suggestion:".yellow().bold(),
                    suggestion
                )
            }
            CargoScriptError::ExecutionError {
                script,
                command,
                source,
            } => {
                // Check if this is a Windows self-replacement error
                let is_windows_self_replace = cfg!(target_os = "windows")
                    && (command.contains("cargo install --path .") || command.contains("cargo install --path"))
                    && (source.to_string().contains("Access is denied") 
                        || source.to_string().contains("os error 5")
                        || source.to_string().contains("failed to move"));

                if is_windows_self_replace {
                    write!(
                        f,
                        "{}\n\n{}\n  {}\n  {}\n\n{}\n  {}\n  {}\n  {}\n\n{}\n  {}",
                        "❌ Cannot replace cargo-script while it's running (Windows limitation)".red().bold(),
                        "Error:".yellow().bold(),
                        format!("Script: {}", script.bold()).white(),
                        format!("Command: {}", command).white(),
                        "Why:".yellow().bold(),
                        "Windows locks executable files while they're running for security and stability.".white(),
                        "When cargo-script runs 'cargo install --path .', it tries to replace itself,".white(),
                        "but Windows prevents this because cargo-script.exe is currently in use.".white(),
                        "Solution:".yellow().bold(),
                        format!("Run '{}' directly in your terminal (not via cargo script)", command.green()).white()
                    )
                } else {
                    write!(
                        f,
                        "{}\n\n{}\n  {}\n  {}\n  {}\n\n{}\n  {}",
                        "❌ Script execution failed".red().bold(),
                        "Error:".yellow().bold(),
                        format!("Script: {}", script.bold()).white(),
                        format!("Command: {}", command).white(),
                        format!("Reason: {}", source).white(),
                        "Suggestion:".yellow().bold(),
                        "Check the command syntax and ensure all required tools are installed".white()
                    )
                }
            }
            CargoScriptError::WindowsSelfReplacementError { script, command } => {
                write!(
                    f,
                    "{}\n\n{}\n  {}\n  {}\n\n{}\n  {}\n  {}\n  {}\n\n{}\n  {}",
                    "❌ Cannot replace cargo-script while it's running (Windows limitation)".red().bold(),
                    "Error:".yellow().bold(),
                    format!("Script: {}", script.bold()).white(),
                    format!("Command: {}", command).white(),
                    "Why:".yellow().bold(),
                    "Windows locks executable files while they're running for security and stability.".white(),
                    "When cargo-script runs 'cargo install --path .', it tries to replace itself,".white(),
                    "but Windows prevents this because cargo-script.exe is currently in use.".white(),
                    "Solution:".yellow().bold(),
                    format!("Run '{}' directly in your terminal (not via cargo script)", command.green()).white()
                )
            }
            CargoScriptError::WorkspaceNotFound { path } => {
                write!(
                    f,
                    "{}\n\n{}\n  {}\n\n{}\n  {}\n  {}",
                    "❌ Workspace not found".red().bold(),
                    "Error:".yellow().bold(),
                    format!("No Cargo.toml with a [workspace] section was found at or above '{}'", path).white(),
                    "Quick fix:".yellow().bold(),
                    "Run cargo-run from inside a Cargo workspace, or".white(),
                    "explicitly declare members in [workspace] of your Scripts.toml.".white(),
                )
            }
            CargoScriptError::ParallelExecutionFailed { failed_scripts } => {
                let list = failed_scripts
                    .iter()
                    .map(|s| format!("    - {}", s.red()))
                    .collect::<Vec<_>>()
                    .join("\n");
                write!(
                    f,
                    "{}\n\n{}\n  {} script(s) failed in parallel execution:\n{}",
                    "❌ Parallel execution failed".red().bold(),
                    "Error:".yellow().bold(),
                    failed_scripts.len(),
                    list,
                )
            }
            CargoScriptError::TemplateNotFound { name, available } => {
                let list = if available.is_empty() {
                    "  (no templates registered)".to_string()
                } else {
                    available
                        .iter()
                        .map(|t| format!("{}", t.green()))
                        .collect::<Vec<_>>()
                        .join("\n")
                };
                write!(
                    f,
                    "{}\n\n{}\n  Template '{}' is not registered\n\n{}\n{}\n\n{}\n  {}",
                    "❌ Template not found".red().bold(),
                    "Error:".yellow().bold(),
                    name.bold(),
                    "Available templates:".yellow().bold(),
                    list,
                    "Quick fix:".yellow().bold(),
                    format!("Run '{}' to list templates", "cargo script init --list-templates".green()).white(),
                )
            }
            CargoScriptError::CargoScriptNotAvailable { suggestion } => {
                write!(
                    f,
                    "{}\n\n{}\n  cargo-script (single-file Rust packages) is not available\n\n{}\n{}",
                    "❌ cargo script not available".red().bold(),
                    "Error:".yellow().bold(),
                    "Suggestion:".yellow().bold(),
                    suggestion,
                )
            }
            CargoScriptError::HookFailed { hook_name, script_name, reason } => {
                write!(
                    f,
                    "{}\n\n{}\n  Hook '{}' for script '{}' failed\n  Reason: {}\n\n{}\n  {}",
                    "❌ Hook execution failed".red().bold(),
                    "Error:".yellow().bold(),
                    hook_name.bold(),
                    script_name.bold(),
                    reason,
                    "Suggestion:".yellow().bold(),
                    "Check that the hook script exists in Scripts.toml and exits successfully".white(),
                )
            }
            CargoScriptError::WatchError { path, message } => {
                write!(
                    f,
                    "{}\n\n{}\n  Failed to watch '{}'\n  {}\n\n{}\n  {}",
                    "❌ Watch mode error".red().bold(),
                    "Error:".yellow().bold(),
                    path,
                    message,
                    "Suggestion:".yellow().bold(),
                    "Ensure the path exists and the process has read access".white(),
                )
            }
            CargoScriptError::MissingScriptArgument { script_name, argument } => {
                write!(
                    f,
                    "{}\n\n{}\n  Script '{}' requires argument '{}'\n\n{}\n  {}",
                    "❌ Missing script argument".red().bold(),
                    "Error:".yellow().bold(),
                    script_name.bold(),
                    argument.bold(),
                    "Quick fix:".yellow().bold(),
                    format!("Pass it as: cargo script {} {}=<value>", script_name, argument).green().to_string(),
                )
            }
        }
    }
}

impl std::error::Error for CargoScriptError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            CargoScriptError::ScriptFileNotFound { source, .. } => Some(source),
            CargoScriptError::ExecutionError { source, .. } => Some(source),
            CargoScriptError::WindowsSelfReplacementError { .. } => None,
            _ => None,
        }
    }
}

/// Find similar script names using Levenshtein distance.
fn find_similar_scripts(query: &str, available: &[String]) -> Vec<String> {
    if available.is_empty() {
        return Vec::new();
    }

    let mut candidates: Vec<(String, usize)> = available
        .iter()
        .map(|s| {
            let distance = levenshtein_distance(query, s);
            (s.clone(), distance)
        })
        .collect();

    // Sort by distance and take the top 3 matches
    candidates.sort_by_key(|(_, d)| *d);
    candidates
        .into_iter()
        .take(3)
        .filter(|(_, d)| *d <= query.len().max(3)) // Only suggest if reasonably close
        .map(|(s, _)| s)
        .collect()
}

/// Calculate Levenshtein distance between two strings.
fn levenshtein_distance(s1: &str, s2: &str) -> usize {
    let s1_chars: Vec<char> = s1.chars().collect();
    let s2_chars: Vec<char> = s2.chars().collect();
    let s1_len = s1_chars.len();
    let s2_len = s2_chars.len();

    if s1_len == 0 {
        return s2_len;
    }
    if s2_len == 0 {
        return s1_len;
    }

    let mut matrix = vec![vec![0; s2_len + 1]; s1_len + 1];

    for i in 0..=s1_len {
        matrix[i][0] = i;
    }
    for j in 0..=s2_len {
        matrix[0][j] = j;
    }

    for i in 1..=s1_len {
        for j in 1..=s2_len {
            let cost = if s1_chars[i - 1] == s2_chars[j - 1] { 0 } else { 1 };
            matrix[i][j] = (matrix[i - 1][j] + 1)
                .min(matrix[i][j - 1] + 1)
                .min(matrix[i - 1][j - 1] + cost);
        }
    }

    matrix[s1_len][s2_len]
}

/// Helper function to create a tool not found error with installation suggestions.
pub fn create_tool_not_found_error(tool: &str, required_version: Option<&str>) -> CargoScriptError {
    let suggestion = match tool {
        "rustup" => "Install rustup: https://rustup.rs/".to_string(),
        "cargo" => "Install Rust: https://www.rust-lang.org/tools/install".to_string(),
        "python" => "Install Python: https://www.python.org/downloads/".to_string(),
        "docker" => "Install Docker: https://docs.docker.com/get-docker/".to_string(),
        "kubectl" => "Install kubectl: https://kubernetes.io/docs/tasks/tools/".to_string(),
        _ => format!("Install {} from your package manager or official website", tool),
    };

    CargoScriptError::ToolNotFound {
        tool: tool.to_string(),
        required_version: required_version.map(|s| s.to_string()),
        suggestion: format!("  {}", suggestion.cyan()),
    }
}

/// Helper function to create a toolchain not found error.
pub fn create_toolchain_not_found_error(toolchain: &str) -> CargoScriptError {
    let suggestion = if toolchain.starts_with("python:") {
        format!("Install Python {} using your system package manager", toolchain.replace("python:", ""))
    } else {
        format!("Install toolchain: rustup toolchain install {}", toolchain)
    };

    CargoScriptError::ToolchainNotFound {
        toolchain: toolchain.to_string(),
        suggestion: format!("  {}", suggestion.cyan()),
    }
}