mise 2026.2.24

The front-end to your dev env
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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
use std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;
use std::sync::Arc;

use crate::config::Config;
use crate::duration;
use crate::file;
use crate::task::Task;
use crate::task::task_fetcher::TaskFetcher;
use crate::ui::style;
use console::style as console_style;
use eyre::{Result, eyre};
use indexmap::IndexMap;
use itertools::Itertools;
use serde::Serialize;

/// Validate tasks for common errors and issues
#[derive(Debug, clap::Args)]
#[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)]
pub struct TasksValidate {
    /// Tasks to validate
    /// If not specified, validates all tasks
    #[clap(verbatim_doc_comment)]
    pub tasks: Option<Vec<String>>,

    /// Only show errors (skip warnings)
    #[clap(long, verbatim_doc_comment)]
    pub errors_only: bool,

    /// Output validation results in JSON format
    #[clap(long, verbatim_doc_comment)]
    pub json: bool,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
enum Severity {
    Error,
    Warning,
}

#[derive(Debug, Clone, Serialize)]
struct ValidationIssue {
    task: String,
    severity: Severity,
    category: String,
    message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    details: Option<String>,
}

#[derive(Debug, Serialize)]
struct ValidationResults {
    tasks_validated: usize,
    errors: usize,
    warnings: usize,
    issues: Vec<ValidationIssue>,
}

impl TasksValidate {
    pub async fn run(self) -> Result<()> {
        let config = Config::get().await?;

        // Resolve all remote task files before validation
        // so we can properly validate remote tasks and circular dependencies
        let mut resolved_tasks: Vec<Task> = config.tasks().await?.values().cloned().collect();
        // always no_cache=false as the command doesn't take no-cache argument
        // MISE_TASK_REMOTE_NO_CACHE env var is still respected if set
        TaskFetcher::new(false)
            .fetch_tasks(&mut resolved_tasks)
            .await?;
        let all_tasks: BTreeMap<String, Task> = resolved_tasks
            .into_iter()
            .map(|t| (t.name.clone(), t))
            .collect();

        // Filter tasks to validate
        let tasks = if let Some(ref task_names) = self.tasks {
            self.get_specific_tasks(&all_tasks, task_names).await?
        } else {
            self.get_all_tasks(&all_tasks)
        };

        // Run validation
        let mut issues = Vec::new();
        for task in &tasks {
            issues.extend(self.validate_task(task, &all_tasks, &config).await);
        }

        // Filter by severity if needed
        if self.errors_only {
            issues.retain(|i| i.severity == Severity::Error);
        }

        let results = ValidationResults {
            tasks_validated: tasks.len(),
            errors: issues
                .iter()
                .filter(|i| i.severity == Severity::Error)
                .count(),
            warnings: issues
                .iter()
                .filter(|i| i.severity == Severity::Warning)
                .count(),
            issues,
        };

        // Output results
        if self.json {
            self.output_json(&results)?;
        } else {
            self.output_human(&results)?;
        }

        // Exit with error if there are errors
        if results.errors > 0 {
            return Err(eyre!("Validation failed with {} error(s)", results.errors));
        }

        Ok(())
    }

    fn get_all_tasks(&self, all_tasks: &BTreeMap<String, Task>) -> Vec<Task> {
        all_tasks.values().cloned().collect()
    }

    async fn get_specific_tasks(
        &self,
        all_tasks: &BTreeMap<String, Task>,
        task_names: &[String],
    ) -> Result<Vec<Task>> {
        let mut tasks = Vec::new();
        for name in task_names {
            // Check if task exists by name, display_name, or alias
            match all_tasks
                .get(name)
                .or_else(|| all_tasks.values().find(|t| &t.display_name == name))
                .or_else(|| {
                    all_tasks
                        .values()
                        .find(|t| t.aliases.contains(&name.to_string()))
                })
                .cloned()
            {
                Some(task) => tasks.push(task),
                None => {
                    return Err(eyre!(
                        "Task '{}' not found. Available tasks: {}",
                        name,
                        all_tasks.keys().map(style::ecyan).join(", ")
                    ));
                }
            }
        }
        Ok(tasks)
    }

    async fn validate_task(
        &self,
        task: &Task,
        all_tasks: &BTreeMap<String, Task>,
        config: &Arc<Config>,
    ) -> Vec<ValidationIssue> {
        let mut issues = Vec::new();

        // 1. Validate circular dependencies
        issues.extend(self.validate_circular_dependencies(task, all_tasks));

        // 2. Validate missing task references
        issues.extend(self.validate_missing_references(task, all_tasks));

        // 3. Validate usage spec parsing
        issues.extend(self.validate_usage_spec(task, config).await);

        // 4. Validate timeout format
        issues.extend(self.validate_timeout(task));

        // 5. Validate alias conflicts
        issues.extend(self.validate_aliases(task, all_tasks));

        // 6. Validate file existence
        issues.extend(self.validate_file_existence(task));

        // 7. Validate directory template
        issues.extend(self.validate_directory(task, config).await);

        // 8. Validate shell command
        issues.extend(self.validate_shell(task));

        // 9. Validate source globs
        issues.extend(self.validate_source_patterns(task));

        // 10. Validate output patterns
        issues.extend(self.validate_output_patterns(task));

        // 11. Validate run entries
        issues.extend(self.validate_run_entries(task, all_tasks));

        issues
    }

    fn validate_circular_dependencies(
        &self,
        task: &Task,
        all_tasks: &BTreeMap<String, Task>,
    ) -> Vec<ValidationIssue> {
        let mut issues = Vec::new();

        match task.all_depends(all_tasks) {
            Ok(_) => {}
            Err(e) => {
                let err_msg = e.to_string();
                if err_msg.contains("circular dependency") {
                    issues.push(ValidationIssue {
                        task: task.name.clone(),
                        severity: Severity::Error,
                        category: "circular-dependency".to_string(),
                        message: "Circular dependency detected".to_string(),
                        details: Some(err_msg),
                    });
                }
            }
        }

        issues
    }

    /// Check if a task exists by name, display_name, or alias
    fn task_exists(all_tasks: &BTreeMap<String, Task>, task_name: &str) -> bool {
        all_tasks.contains_key(task_name)
            || all_tasks.values().any(|t| t.display_name == task_name)
            || all_tasks
                .values()
                .any(|t| t.aliases.contains(&task_name.to_string()))
    }

    fn validate_missing_references(
        &self,
        task: &Task,
        all_tasks: &BTreeMap<String, Task>,
    ) -> Vec<ValidationIssue> {
        let mut issues = Vec::new();

        // Check all dependency types
        let all_deps = task
            .depends
            .iter()
            .map(|d| ("depends", &d.task))
            .chain(task.depends_post.iter().map(|d| ("depends_post", &d.task)))
            .chain(task.wait_for.iter().map(|d| ("wait_for", &d.task)));

        for (dep_type, dep_name) in all_deps {
            // Skip pattern wildcards for now (they're resolved at runtime)
            if dep_name.contains('*') || dep_name.contains('?') {
                continue;
            }

            // Check if task exists
            if !Self::task_exists(all_tasks, dep_name) {
                issues.push(ValidationIssue {
                    task: task.name.clone(),
                    severity: Severity::Error,
                    category: "missing-dependency".to_string(),
                    message: format!("Dependency '{}' not found", dep_name),
                    details: Some(format!(
                        "Referenced in '{}' but no matching task exists",
                        dep_type
                    )),
                });
            }
        }

        issues
    }

    async fn validate_usage_spec(&self, task: &Task, config: &Arc<Config>) -> Vec<ValidationIssue> {
        let mut issues = Vec::new();

        // Try to parse the usage spec
        match task.parse_usage_spec_for_display(config).await {
            Ok(_spec) => {
                // Successfully parsed
            }
            Err(e) => {
                issues.push(ValidationIssue {
                    task: task.name.clone(),
                    severity: Severity::Warning,
                    category: "usage-parse-error".to_string(),
                    message: "Failed to parse usage specification".to_string(),
                    details: Some(format!("{:#}", e)),
                });
            }
        }

        // If task has explicit usage field, validate it's not empty
        if !task.usage.is_empty() {
            // Check if usage contains common USAGE directive errors
            if task.usage.contains("#USAGE") || task.usage.contains("# USAGE") {
                issues.push(ValidationIssue {
                    task: task.name.clone(),
                    severity: Severity::Warning,
                    category: "usage-directive".to_string(),
                    message: "Usage field contains directive markers".to_string(),
                    details: Some(
                        "The 'usage' field should contain the spec directly, not #USAGE directives"
                            .to_string(),
                    ),
                });
            }
        }

        issues
    }

    fn validate_timeout(&self, task: &Task) -> Vec<ValidationIssue> {
        let mut issues = Vec::new();

        if let Some(ref timeout) = task.timeout {
            // Try to parse as duration
            if let Err(e) = duration::parse_duration(timeout) {
                issues.push(ValidationIssue {
                    task: task.name.clone(),
                    severity: Severity::Error,
                    category: "invalid-timeout".to_string(),
                    message: format!("Invalid timeout format: '{}'", timeout),
                    details: Some(format!("Parse error: {}", e)),
                });
            }
        }

        issues
    }

    fn validate_aliases(
        &self,
        task: &Task,
        all_tasks: &BTreeMap<String, Task>,
    ) -> Vec<ValidationIssue> {
        let mut issues = Vec::new();

        // Build a map of aliases to tasks
        let mut alias_map: HashMap<String, Vec<String>> = HashMap::new();
        for t in all_tasks.values() {
            for alias in &t.aliases {
                alias_map
                    .entry(alias.clone())
                    .or_default()
                    .push(t.name.clone());
            }
        }

        // Check for conflicts - only report once for the first task alphabetically
        for alias in &task.aliases {
            if let Some(tasks) = alias_map.get(alias)
                && tasks.len() > 1
            {
                // Only report the conflict for the first task (alphabetically) to avoid duplicates
                let mut sorted_tasks = tasks.clone();
                sorted_tasks.sort();
                if sorted_tasks[0] == task.name {
                    issues.push(ValidationIssue {
                        task: task.name.clone(),
                        severity: Severity::Error,
                        category: "alias-conflict".to_string(),
                        message: format!("Alias '{}' is used by multiple tasks", alias),
                        details: Some(format!("Tasks: {}", tasks.join(", "))),
                    });
                }
            }

            // Check if alias conflicts with a task name
            if all_tasks.contains_key(alias) {
                issues.push(ValidationIssue {
                    task: task.name.clone(),
                    severity: Severity::Error,
                    category: "alias-conflict".to_string(),
                    message: format!("Alias '{}' conflicts with task name", alias),
                    details: Some(format!("A task named '{}' already exists", alias)),
                });
            }
        }

        issues
    }

    fn validate_file_existence(&self, task: &Task) -> Vec<ValidationIssue> {
        let mut issues = Vec::new();

        if let Some(ref file) = task.file {
            if !file.exists() {
                issues.push(ValidationIssue {
                    task: task.name.clone(),
                    severity: Severity::Error,
                    category: "missing-file".to_string(),
                    message: format!("Task file not found: {}", file::display_path(file)),
                    details: None,
                });
            } else if !file::is_executable(file) {
                issues.push(ValidationIssue {
                    task: task.name.clone(),
                    severity: Severity::Warning,
                    category: "not-executable".to_string(),
                    message: format!("Task file is not executable: {}", file::display_path(file)),
                    details: Some(format!("Run: chmod +x {}", file::display_path(file))),
                });
            }
        }

        issues
    }

    async fn validate_directory(&self, task: &Task, config: &Arc<Config>) -> Vec<ValidationIssue> {
        let mut issues = Vec::new();

        if let Some(ref dir) = task.dir {
            // Try to render the directory template
            if dir.contains("{{") || dir.contains("{%") {
                // Contains template syntax - try to render it
                match task.dir(config).await {
                    Ok(rendered_dir) => {
                        if let Some(rendered) = rendered_dir
                            && !rendered.exists()
                        {
                            issues.push(ValidationIssue {
                                task: task.name.clone(),
                                severity: Severity::Warning,
                                category: "missing-directory".to_string(),
                                message: format!(
                                    "Task directory does not exist: {}",
                                    file::display_path(&rendered)
                                ),
                                details: Some(format!("Template: {}", dir)),
                            });
                        }
                    }
                    Err(e) => {
                        issues.push(ValidationIssue {
                            task: task.name.clone(),
                            severity: Severity::Error,
                            category: "invalid-directory-template".to_string(),
                            message: "Failed to render directory template".to_string(),
                            details: Some(format!("Template: {}, Error: {:#}", dir, e)),
                        });
                    }
                }
            } else {
                // Static path - check if it exists
                let dir_path = PathBuf::from(dir);
                if dir_path.is_absolute() && !dir_path.exists() {
                    issues.push(ValidationIssue {
                        task: task.name.clone(),
                        severity: Severity::Warning,
                        category: "missing-directory".to_string(),
                        message: format!("Task directory does not exist: {}", dir),
                        details: None,
                    });
                }
            }
        }

        issues
    }

    fn validate_shell(&self, task: &Task) -> Vec<ValidationIssue> {
        let mut issues = Vec::new();

        if let Some(ref shell) = task.shell {
            // Parse shell command (could be "bash -c" or just "bash")
            let shell_parts: Vec<&str> = shell.split_whitespace().collect();
            if let Some(shell_cmd) = shell_parts.first() {
                // Check if it's an absolute path
                let shell_path = PathBuf::from(shell_cmd);
                if shell_path.is_absolute() && !shell_path.exists() {
                    issues.push(ValidationIssue {
                        task: task.name.clone(),
                        severity: Severity::Error,
                        category: "invalid-shell".to_string(),
                        message: format!("Shell command not found: {}", shell_cmd),
                        details: Some(format!("Full shell: {}", shell)),
                    });
                }
            }
        }

        issues
    }

    fn validate_source_patterns(&self, task: &Task) -> Vec<ValidationIssue> {
        let mut issues = Vec::new();

        for source in &task.sources {
            // Try to compile as glob pattern
            if let Err(e) = globset::GlobBuilder::new(source).build() {
                issues.push(ValidationIssue {
                    task: task.name.clone(),
                    severity: Severity::Error,
                    category: "invalid-glob-pattern".to_string(),
                    message: format!("Invalid source glob pattern: '{}'", source),
                    details: Some(format!("{}", e)),
                });
            }
        }

        issues
    }

    fn validate_output_patterns(&self, task: &Task) -> Vec<ValidationIssue> {
        let mut issues = Vec::new();

        // Validate output patterns if they exist
        let paths = task.outputs.patterns();
        for path in paths {
            // Try to compile as glob pattern
            if let Err(e) = globset::GlobBuilder::new(&path).build() {
                issues.push(ValidationIssue {
                    task: task.name.clone(),
                    severity: Severity::Error,
                    category: "invalid-glob-pattern".to_string(),
                    message: format!("Invalid output glob pattern: '{}'", path),
                    details: Some(format!("{}", e)),
                });
            }
        }

        issues
    }

    fn validate_run_entries(
        &self,
        task: &Task,
        all_tasks: &BTreeMap<String, Task>,
    ) -> Vec<ValidationIssue> {
        let mut issues = Vec::new();

        // Validate run entries
        for entry in task.run() {
            match entry {
                crate::task::RunEntry::Script(script) => {
                    // Check if script is empty
                    if script.trim().is_empty() {
                        issues.push(ValidationIssue {
                            task: task.name.clone(),
                            severity: Severity::Warning,
                            category: "empty-script".to_string(),
                            message: "Task contains empty script entry".to_string(),
                            details: None,
                        });
                    }
                }
                crate::task::RunEntry::SingleTask { task: task_name } => {
                    // Check if referenced task exists (by name, display_name, or alias)
                    if !Self::task_exists(all_tasks, task_name) {
                        issues.push(ValidationIssue {
                            task: task.name.clone(),
                            severity: Severity::Error,
                            category: "missing-task-reference".to_string(),
                            message: format!(
                                "Task '{}' referenced in run entry not found",
                                task_name
                            ),
                            details: None,
                        });
                    }
                }
                crate::task::RunEntry::TaskGroup { tasks } => {
                    // Check if all tasks in group exist (by name, display_name, or alias)
                    for task_name in tasks {
                        if !Self::task_exists(all_tasks, task_name) {
                            issues.push(ValidationIssue {
                                task: task.name.clone(),
                                severity: Severity::Error,
                                category: "missing-task-reference".to_string(),
                                message: format!("Task '{}' in task group not found", task_name),
                                details: Some("Referenced in parallel task group".to_string()),
                            });
                        }
                    }
                }
            }
        }

        // Check if task has no run entries and no file
        // Allow tasks with dependencies but no run entries (meta/group tasks)
        if task.run().is_empty()
            && task.file.is_none()
            && task.depends.is_empty()
            && task.depends_post.is_empty()
        {
            issues.push(ValidationIssue {
                task: task.name.clone(),
                severity: Severity::Error,
                category: "no-execution".to_string(),
                message: "Task has no executable content".to_string(),
                details: Some(
                    "Task must have either 'run', 'run_windows', 'file', or 'depends' defined"
                        .to_string(),
                ),
            });
        }

        issues
    }

    fn output_json(&self, results: &ValidationResults) -> Result<()> {
        let json = serde_json::to_string_pretty(results)?;
        miseprintln!("{}", json);
        Ok(())
    }

    fn output_human(&self, results: &ValidationResults) -> Result<()> {
        if results.issues.is_empty() {
            miseprintln!(
                "{}",
                console_style(format!(
                    "✓ All {} task(s) validated successfully",
                    results.tasks_validated
                ))
                .green()
            );
            return Ok(());
        }

        // Group issues by task
        let mut issues_by_task: IndexMap<String, Vec<&ValidationIssue>> = IndexMap::new();
        for issue in &results.issues {
            issues_by_task
                .entry(issue.task.clone())
                .or_insert_with(Vec::new)
                .push(issue);
        }

        // Print summary
        miseprintln!(
            "\n{} task(s) validated with {} issue(s):\n",
            console_style(results.tasks_validated).bold(),
            console_style(results.errors + results.warnings).bold()
        );

        if results.errors > 0 {
            miseprintln!(
                "  {} {}",
                console_style("").red().bold(),
                console_style(format!("{} error(s)", results.errors))
                    .red()
                    .bold()
            );
        }
        if results.warnings > 0 {
            miseprintln!(
                "  {} {}",
                console_style("").yellow().bold(),
                console_style(format!("{} warning(s)", results.warnings))
                    .yellow()
                    .bold()
            );
        }

        miseprintln!();

        // Print issues grouped by task
        for (task_name, task_issues) in issues_by_task {
            miseprintln!(
                "{} {}",
                console_style("Task:").bold(),
                console_style(&task_name).cyan()
            );

            for issue in task_issues {
                let severity_icon = match issue.severity {
                    Severity::Error => console_style("").red().bold(),
                    Severity::Warning => console_style("").yellow().bold(),
                };

                miseprintln!(
                    "  {} {} [{}]",
                    severity_icon,
                    console_style(&issue.message).bold(),
                    console_style(&issue.category).dim()
                );

                if let Some(ref details) = issue.details {
                    for line in details.lines() {
                        miseprintln!("      {}", console_style(line).dim());
                    }
                }
            }

            miseprintln!();
        }

        Ok(())
    }
}

static AFTER_LONG_HELP: &str = color_print::cstr!(
    r#"<bold><underline>Examples:</underline></bold>

    # Validate all tasks
    $ <bold>mise tasks validate</bold>

    # Validate specific tasks
    $ <bold>mise tasks validate build test</bold>

    # Output results as JSON
    $ <bold>mise tasks validate --json</bold>

    # Only show errors (skip warnings)
    $ <bold>mise tasks validate --errors-only</bold>

<bold><underline>Validation Checks:</underline></bold>

The validate command performs the following checks:

  • <bold>Circular Dependencies</bold>: Detects dependency cycles
  • <bold>Missing References</bold>: Finds references to non-existent tasks
  • <bold>Usage Spec Parsing</bold>: Validates #USAGE directives and specs
  • <bold>Timeout Format</bold>: Checks timeout values are valid durations
  • <bold>Alias Conflicts</bold>: Detects duplicate aliases across tasks
  • <bold>File Existence</bold>: Verifies file-based tasks exist
  • <bold>Directory Templates</bold>: Validates directory paths and templates
  • <bold>Shell Commands</bold>: Checks shell executables exist
  • <bold>Glob Patterns</bold>: Validates source and output patterns
  • <bold>Run Entries</bold>: Ensures tasks reference valid dependencies
"#
);