plzplz 0.0.19

A simple cross-platform task runner with helpful defaults
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
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
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
use anyhow::{Context, Result, bail};
use schemars::{JsonSchema, SchemaGenerator, json_schema};
use serde::Deserialize;
use serde::de::{self, Deserializer, SeqAccess, Visitor};
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::path::Path;
use toml_edit::DocumentMut;

pub const VALID_GIT_HOOKS: &[&str] = &[
    "applypatch-msg",
    "pre-applypatch",
    "post-applypatch",
    "pre-commit",
    "prepare-commit-msg",
    "commit-msg",
    "post-commit",
    "pre-rebase",
    "post-checkout",
    "post-merge",
    "pre-push",
    "pre-receive",
    "update",
    "post-receive",
    "post-update",
    "push-to-checkout",
    "pre-auto-gc",
    "post-rewrite",
    "sendemail-validate",
];

#[derive(Debug, Default, Clone, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct GlobalSettings {
    /// Tool environment wrapper applied to all tasks: "pnpm", "npm", "uv", or "uvx"
    #[serde(default, rename = "env")]
    #[schemars(rename = "env")]
    pub tool_env: Option<String>,
    /// Default working directory (relative to plz.toml) for all tasks
    #[serde(default)]
    pub dir: Option<String>,
}

#[derive(Debug)]
pub struct TaskGroup {
    pub extends: Option<GlobalSettings>,
    pub vars: Option<HashMap<String, String>>,
    pub tasks: HashMap<String, Task>,
}

impl<'de> Deserialize<'de> for TaskGroup {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct TaskGroupVisitor;

        impl<'de> Visitor<'de> for TaskGroupVisitor {
            type Value = TaskGroup;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("a task group table with optional 'extends' and task entries")
            }

            fn visit_map<M>(self, mut map: M) -> std::result::Result<TaskGroup, M::Error>
            where
                M: de::MapAccess<'de>,
            {
                let mut extends = None;
                let mut vars = None;
                let mut tasks = HashMap::new();

                while let Some(key) = map.next_key::<String>()? {
                    if key == "extends" {
                        extends = Some(map.next_value::<GlobalSettings>()?);
                    } else if key == "vars" {
                        vars = Some(map.next_value::<HashMap<String, String>>()?);
                    } else {
                        tasks.insert(key, map.next_value::<Task>()?);
                    }
                }

                Ok(TaskGroup {
                    extends,
                    vars,
                    tasks,
                })
            }
        }

        deserializer.deserialize_map(TaskGroupVisitor)
    }
}

impl JsonSchema for TaskGroup {
    fn schema_name() -> Cow<'static, str> {
        Cow::Borrowed("TaskGroup")
    }

    fn json_schema(generator: &mut SchemaGenerator) -> schemars::Schema {
        json_schema!({
            "type": "object",
            "description": "A group of related tasks with optional shared defaults",
            "properties": {
                "extends": generator.subschema_for::<GlobalSettings>(),
                "vars": {
                    "type": "object",
                    "description": "Variables for {{key}} substitution in task commands within this group",
                    "additionalProperties": { "type": "string" }
                }
            },
            "additionalProperties": generator.subschema_for::<Task>()
        })
    }
}

#[derive(Debug, Default, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct PlzSection {
    /// Semver version requirement for plz (e.g. ">=0.1.0", "^0.2")
    #[serde(default)]
    pub version: Option<String>,
}

#[derive(Debug, Default, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct HealthcheckSection {
    /// Glob patterns of files to exclude from all healthcheck checks (e.g. "vendor/**", "**/*.min.js")
    #[serde(default)]
    pub exclude: Vec<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct PlzConfig {
    /// plz tool settings (e.g. required version)
    #[serde(default)]
    pub plz: Option<PlzSection>,
    /// Healthcheck configuration (e.g. file patterns to exclude)
    #[serde(default)]
    pub healthcheck: Option<HealthcheckSection>,
    /// Global defaults that apply to all tasks (can be overridden per-task)
    #[serde(default)]
    pub extends: Option<GlobalSettings>,
    /// Task groups for namespacing related tasks (e.g. [taskgroup.rust.test])
    #[serde(default)]
    pub taskgroup: Option<HashMap<String, TaskGroup>>,
    /// Variables for {{key}} substitution in task commands
    #[serde(default)]
    pub vars: Option<HashMap<String, String>>,
    /// Tasks to run, keyed by name (e.g. [tasks.build]). Run with `plz <name>`.
    #[serde(default)]
    pub tasks: HashMap<String, Task>,
}

#[derive(Debug, Clone)]
pub struct StringOrVec(pub Vec<String>);

impl<'de> Deserialize<'de> for StringOrVec {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct StringOrVecVisitor;

        impl<'de> Visitor<'de> for StringOrVecVisitor {
            type Value = StringOrVec;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("a string or array of strings")
            }

            fn visit_str<E: de::Error>(self, v: &str) -> std::result::Result<StringOrVec, E> {
                Ok(StringOrVec(vec![v.to_string()]))
            }

            fn visit_seq<S: SeqAccess<'de>>(
                self,
                mut seq: S,
            ) -> std::result::Result<StringOrVec, S::Error> {
                let mut vec = Vec::new();
                while let Some(item) = seq.next_element::<String>()? {
                    vec.push(item);
                }
                Ok(StringOrVec(vec))
            }
        }

        deserializer.deserialize_any(StringOrVecVisitor)
    }
}

impl JsonSchema for StringOrVec {
    fn inline_schema() -> bool {
        true
    }

    fn schema_name() -> Cow<'static, str> {
        Cow::Borrowed("StringOrVec")
    }

    fn json_schema(_: &mut SchemaGenerator) -> schemars::Schema {
        json_schema!({
            "oneOf": [
                { "type": "string" },
                { "type": "array", "items": { "type": "string" } }
            ]
        })
    }
}

#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct Task {
    /// A shell command (or list of commands to run serially) to run
    #[serde(default)]
    pub run: Option<StringOrVec>,
    /// Multiple commands to run one after another (stops on first failure)
    #[serde(default)]
    pub run_serial: Option<Vec<String>>,
    /// Multiple commands to run concurrently
    #[serde(default)]
    pub run_parallel: Option<Vec<String>>,
    /// Prerequisite tasks to run before this task. Use dot notation for group tasks (e.g. "group.task").
    #[serde(default)]
    pub depends: Option<StringOrVec>,
    /// Tool environment wrapper: "pnpm" (uses `pnpm exec`), "npm" (uses `npx`), "uv" (uses `uv run`), or "uvx" (uses `uvx`)
    #[serde(default, rename = "env")]
    #[schemars(rename = "env")]
    pub tool_env: Option<String>,
    /// Working directory (relative to plz.toml)
    #[serde(default)]
    pub dir: Option<String>,
    /// Action to take when the task fails: a command string, { suggest_command = "..." }, or { message = "..." }
    #[serde(default)]
    pub fail_hook: Option<FailHook>,
    /// Description shown in `plz list`
    #[serde(default)]
    pub description: Option<String>,
    /// Git hook stage to associate this task with (e.g. "pre-commit", "pre-push")
    #[serde(default)]
    pub git_hook: Option<String>,
    /// Hide this task from interactive pickers and listings
    #[serde(default)]
    pub hide: bool,
}

#[derive(Debug)]
pub enum FailHook {
    Command(String),
    Suggest { suggest_command: String },
    Message(String),
}

impl JsonSchema for FailHook {
    fn inline_schema() -> bool {
        true
    }

    fn schema_name() -> Cow<'static, str> {
        Cow::Borrowed("FailHook")
    }

    fn json_schema(_: &mut SchemaGenerator) -> schemars::Schema {
        json_schema!({
            "oneOf": [
                {
                    "type": "string",
                    "description": "Shell command to run on failure"
                },
                {
                    "type": "object",
                    "properties": {
                        "suggest_command": {
                            "type": "string",
                            "description": "Command to suggest to the user on failure"
                        }
                    },
                    "required": ["suggest_command"],
                    "additionalProperties": false
                },
                {
                    "type": "object",
                    "properties": {
                        "message": {
                            "type": "string",
                            "description": "Message to display on failure"
                        }
                    },
                    "required": ["message"],
                    "additionalProperties": false
                }
            ]
        })
    }
}

impl<'de> Deserialize<'de> for FailHook {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct FailHookVisitor;

        impl<'de> Visitor<'de> for FailHookVisitor {
            type Value = FailHook;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("a string or a map with suggest_command")
            }

            fn visit_str<E: de::Error>(self, v: &str) -> std::result::Result<FailHook, E> {
                Ok(FailHook::Command(v.to_string()))
            }

            fn visit_map<M>(self, mut map: M) -> std::result::Result<FailHook, M::Error>
            where
                M: de::MapAccess<'de>,
            {
                let mut suggest_command = None;
                let mut message = None;
                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "suggest_command" => suggest_command = Some(map.next_value::<String>()?),
                        "message" => message = Some(map.next_value::<String>()?),
                        _ => {
                            let _ = map.next_value::<de::IgnoredAny>()?;
                        }
                    }
                }
                if let Some(cmd) = suggest_command {
                    Ok(FailHook::Suggest {
                        suggest_command: cmd,
                    })
                } else if let Some(msg) = message {
                    Ok(FailHook::Message(msg))
                } else {
                    Err(de::Error::missing_field("suggest_command or message"))
                }
            }
        }

        deserializer.deserialize_any(FailHookVisitor)
    }
}

fn substitute_vars(input: &str, vars: &HashMap<String, String>) -> Result<String> {
    let mut result = input.to_string();
    let mut keys: Vec<&String> = vars.keys().collect();
    keys.sort();
    for key in keys {
        result = result.replace(&format!("{{{{{key}}}}}"), &vars[key]);
    }
    // Check for unresolved {{...}} patterns
    if let Some(start) = result.find("{{") {
        if let Some(end) = result[start + 2..].find("}}") {
            let unresolved = &result[start + 2..start + 2 + end];
            bail!("Unresolved variable \"{{{{{unresolved}}}}}\"");
        }
    }
    Ok(result)
}

fn substitute_task_vars(task: &mut Task, vars: &HashMap<String, String>) -> Result<()> {
    if let Some(ref mut run) = task.run {
        for cmd in &mut run.0 {
            *cmd = substitute_vars(cmd, vars)?;
        }
    }
    if let Some(ref mut cmds) = task.run_serial {
        for cmd in cmds {
            *cmd = substitute_vars(cmd, vars)?;
        }
    }
    if let Some(ref mut cmds) = task.run_parallel {
        for cmd in cmds {
            *cmd = substitute_vars(cmd, vars)?;
        }
    }
    Ok(())
}

fn format_location(path: &str) -> String {
    if path.is_empty() {
        "plz.toml".to_string()
    } else {
        let parts: Vec<&str> = path.split('/').filter(|s: &&str| !s.is_empty()).collect();
        format!("[{}]", parts.join("."))
    }
}

fn collect_additional_properties_errors<'a>(
    warnings: &mut Vec<String>,
    errors: impl Iterator<Item = jsonschema::ValidationError<'a>>,
) {
    use jsonschema::error::ValidationErrorKind;
    for error in errors {
        match error.kind() {
            ValidationErrorKind::AdditionalProperties { unexpected } => {
                let location = format_location(&error.instance_path().to_string());
                for key in unexpected {
                    warnings.push(format!("unknown key \"{key}\" in {location}"));
                }
            }
            ValidationErrorKind::AnyOf { context } => {
                // Look for AdditionalProperties errors nested inside anyOf branches
                for branch_errors in context {
                    for inner in branch_errors {
                        if let ValidationErrorKind::AdditionalProperties { unexpected } =
                            inner.kind()
                        {
                            let location = format_location(&inner.instance_path().to_string());
                            for key in unexpected {
                                warnings.push(format!("unknown key \"{key}\" in {location}"));
                            }
                        }
                    }
                }
            }
            _ => {}
        }
    }
}

pub fn warn_unknown_keys(doc: &DocumentMut) -> Vec<String> {
    let schema = schemars::schema_for!(PlzConfig);
    let schema_json = serde_json::to_value(&schema).expect("schema serializes to JSON");
    let Ok(validator) = jsonschema::validator_for(&schema_json) else {
        return Vec::new();
    };

    let toml_str = doc.to_string();
    let json_value: serde_json::Value = match toml_edit::de::from_str(&toml_str) {
        Ok(v) => v,
        Err(_) => return Vec::new(),
    };

    let mut warnings = Vec::new();
    collect_additional_properties_errors(&mut warnings, validator.iter_errors(&json_value));
    warnings
}

pub fn load(path: &Path) -> Result<PlzConfig> {
    let content = std::fs::read_to_string(path)
        .with_context(|| format!("Failed to read {}", path.display()))?;

    let doc: DocumentMut = content
        .parse()
        .with_context(|| "Failed to parse plz.toml")?;

    let mut config: PlzConfig = toml_edit::de::from_document(doc.clone())
        .with_context(|| "Failed to deserialize config")?;

    // Warn about unknown keys
    for warning in warn_unknown_keys(&doc) {
        eprintln!("\x1b[33mwarning:\x1b[0m {warning}");
    }

    // Extract comments above [tasks.*] as descriptions (fallback when no explicit description)
    if let Some(tasks_table) = doc.get("tasks").and_then(|v| v.as_table()) {
        for (key, item) in tasks_table.iter() {
            if let Some(task) = config.tasks.get_mut(key)
                && task.description.is_none()
                && let Some(decor) = item.as_table().map(|t| t.decor())
                && let Some(prefix) = decor.prefix().and_then(|p| p.as_str())
            {
                task.description = extract_comment(prefix);
            }
        }
    }

    // Apply global defaults from [extends] to tasks.
    // Empty string means "explicitly no value" (opt out of extends).
    if let Some(ref extends) = config.extends {
        for task in config.tasks.values_mut() {
            if task.tool_env.is_none() {
                task.tool_env.clone_from(&extends.tool_env);
            }
            if task.dir.is_none() {
                task.dir.clone_from(&extends.dir);
            }
        }
    }
    for task in config.tasks.values_mut() {
        if task.tool_env.as_deref() == Some("") {
            task.tool_env = None;
        }
        if task.dir.as_deref() == Some("") {
            task.dir = None;
        }
    }

    if config.tasks.contains_key("plz") {
        bail!("\"plz\" is a reserved name and cannot be used as a task name.");
    }

    // Validate git_hook values
    for (name, task) in &config.tasks {
        if let Some(ref hook) = task.git_hook {
            if !VALID_GIT_HOOKS.contains(&hook.as_str()) {
                bail!(
                    "Task \"{name}\" has invalid git_hook \"{hook}\". Valid hooks: {}",
                    VALID_GIT_HOOKS.join(", ")
                );
            }
        }
    }

    // Apply extends cascade to taskgroup tasks:
    // top-level [extends] → [taskgroup.X.extends] → per-task values
    if let Some(ref mut groups) = config.taskgroup {
        for (group_name, group) in groups.iter_mut() {
            // Compute effective extends: top-level, then group overrides
            let effective_env = group
                .extends
                .as_ref()
                .and_then(|e| e.tool_env.clone())
                .or_else(|| config.extends.as_ref().and_then(|e| e.tool_env.clone()));
            let effective_dir = group
                .extends
                .as_ref()
                .and_then(|e| e.dir.clone())
                .or_else(|| config.extends.as_ref().and_then(|e| e.dir.clone()));

            for task in group.tasks.values_mut() {
                if task.tool_env.is_none() {
                    task.tool_env.clone_from(&effective_env);
                }
                if task.dir.is_none() {
                    task.dir.clone_from(&effective_dir);
                }
            }

            // Clear empty-string opt-outs
            for task in group.tasks.values_mut() {
                if task.tool_env.as_deref() == Some("") {
                    task.tool_env = None;
                }
                if task.dir.as_deref() == Some("") {
                    task.dir = None;
                }
            }

            // Validate git_hook values in group tasks
            for (task_name, task) in &group.tasks {
                if let Some(ref hook) = task.git_hook {
                    if !VALID_GIT_HOOKS.contains(&hook.as_str()) {
                        bail!(
                            "Task \"{group_name}:{task_name}\" has invalid git_hook \"{hook}\". Valid hooks: {}",
                            VALID_GIT_HOOKS.join(", ")
                        );
                    }
                }
            }

            // Extract comments from taskgroup tables
            if let Some(group_table) = doc
                .get("taskgroup")
                .and_then(|v| v.as_table())
                .and_then(|t| t.get(group_name.as_str()))
                .and_then(|v| v.as_table())
            {
                for (key, item) in group_table.iter() {
                    if key == "extends" || key == "vars" {
                        continue;
                    }
                    if let Some(task) = group.tasks.get_mut(key)
                        && task.description.is_none()
                        && let Some(decor) = item.as_table().map(|t| t.decor())
                        && let Some(prefix) = decor.prefix().and_then(|p| p.as_str())
                    {
                        task.description = extract_comment(prefix);
                    }
                }
            }
        }
    }

    // Apply [vars] substitution to top-level tasks
    if let Some(ref vars) = config.vars {
        for (name, task) in config.tasks.iter_mut() {
            substitute_task_vars(task, vars).with_context(|| format!("In task \"{name}\""))?;
        }
    }

    // Apply vars to taskgroup tasks (merge: top-level vars + group vars)
    if let Some(ref mut groups) = config.taskgroup {
        for (group_name, group) in groups.iter_mut() {
            let mut merged_vars: HashMap<String, String> = config.vars.clone().unwrap_or_default();
            if let Some(ref group_vars) = group.vars {
                merged_vars.extend(group_vars.clone());
            }
            if !merged_vars.is_empty() {
                for (task_name, task) in group.tasks.iter_mut() {
                    substitute_task_vars(task, &merged_vars)
                        .with_context(|| format!("In task \"{group_name}:{task_name}\""))?;
                }
            }
        }
    }

    // Validate depends references exist
    validate_depends(&config)?;

    // Detect circular dependencies
    detect_cycles(&config)?;

    Ok(config)
}

fn resolve_dep_ref(config: &PlzConfig, dep: &str) -> bool {
    if let Some((group, task)) = dep.split_once('.') {
        config.get_group_task(group, task).is_some()
    } else {
        config.tasks.contains_key(dep)
    }
}

fn validate_depends(config: &PlzConfig) -> Result<()> {
    for (name, task) in &config.tasks {
        if let Some(ref deps) = task.depends {
            for dep in &deps.0 {
                if !resolve_dep_ref(config, dep) {
                    bail!("Task \"{name}\" has depends \"{dep}\", but no task \"{dep}\" exists");
                }
            }
        }
    }
    if let Some(ref groups) = config.taskgroup {
        for (group_name, group) in groups {
            for (task_name, task) in &group.tasks {
                if let Some(ref deps) = task.depends {
                    for dep in &deps.0 {
                        if !resolve_dep_ref(config, dep) {
                            bail!(
                                "Task \"{group_name}.{task_name}\" has depends \"{dep}\", but no task \"{dep}\" exists"
                            );
                        }
                    }
                }
            }
        }
    }
    Ok(())
}

fn detect_cycles(config: &PlzConfig) -> Result<()> {
    // Build adjacency list: node_id -> [dep_ids]
    // node_id for top-level: task_name, for group: "group.task"
    let mut adj: HashMap<String, Vec<String>> = HashMap::new();

    for (name, task) in &config.tasks {
        if let Some(ref deps) = task.depends {
            adj.insert(name.clone(), deps.0.clone());
        }
    }
    if let Some(ref groups) = config.taskgroup {
        for (group_name, group) in groups {
            for (task_name, task) in &group.tasks {
                if let Some(ref deps) = task.depends {
                    let key = format!("{group_name}.{task_name}");
                    adj.insert(key, deps.0.clone());
                }
            }
        }
    }

    let mut visited = HashSet::new();
    let mut in_stack = HashSet::new();
    let mut path = Vec::new();

    for node in adj.keys() {
        if !visited.contains(node) {
            dfs_cycle(node, &adj, &mut visited, &mut in_stack, &mut path)?;
        }
    }

    Ok(())
}

fn dfs_cycle(
    node: &str,
    adj: &HashMap<String, Vec<String>>,
    visited: &mut HashSet<String>,
    in_stack: &mut HashSet<String>,
    path: &mut Vec<String>,
) -> Result<()> {
    visited.insert(node.to_string());
    in_stack.insert(node.to_string());
    path.push(node.to_string());

    if let Some(deps) = adj.get(node) {
        for dep in deps {
            if in_stack.contains(dep) {
                path.push(dep.clone());
                let cycle_start = path.iter().position(|n| n == dep).unwrap();
                let cycle = path[cycle_start..].join("");
                bail!("Circular dependency: {cycle}");
            }
            if !visited.contains(dep) {
                dfs_cycle(dep, adj, visited, in_stack, path)?;
            }
        }
    }

    path.pop();
    in_stack.remove(node);
    Ok(())
}

impl PlzConfig {
    pub fn get_group(&self, name: &str) -> Option<&TaskGroup> {
        self.taskgroup.as_ref()?.get(name)
    }

    pub fn get_group_task(&self, group: &str, task: &str) -> Option<&Task> {
        self.get_group(group)?.tasks.get(task)
    }

    pub fn check_version(&self) {
        let req_str = match self.plz.as_ref().and_then(|p| p.version.as_deref()) {
            Some(v) => v,
            None => return,
        };
        let current = env!("CARGO_PKG_VERSION");
        let Ok(version) = semver::Version::parse(current) else {
            return;
        };
        let Ok(req) = semver::VersionReq::parse(req_str) else {
            eprintln!(
                "\x1b[33mwarning:\x1b[0m [plz] version \"{req_str}\" is not a valid semver requirement"
            );
            return;
        };
        if !req.matches(&version) {
            eprintln!(
                "\x1b[33mwarning:\x1b[0m plz {current} does not match version requirement \"{req_str}\" in plz.toml. Run `plz update` to update."
            );
        }
    }
}

pub fn extract_comment(prefix: &str) -> Option<String> {
    let lines: Vec<&str> = prefix
        .lines()
        .filter_map(|line| {
            let trimmed = line.trim();
            if trimmed.starts_with('#') {
                Some(trimmed.trim_start_matches('#').trim())
            } else {
                None
            }
        })
        .collect();

    if lines.is_empty() {
        None
    } else {
        Some(lines.join(" "))
    }
}