baraddur 0.1.4

Project-agnostic file watcher that surfaces issues before CI
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
#![forbid(unsafe_code)]

pub mod config;
pub mod git;
pub mod output;
pub mod pipeline;
pub mod watcher;

use anyhow::Result;
use std::fmt::Write as _;
use std::future::Future;
use std::path::{Path, PathBuf};
use std::time::Duration;
use tokio::task::JoinHandle;

use crate::output::style::{Theme, should_color};
use crate::output::{
    BrowseAction, Display, DisplayConfig, JsonDisplay, OutputFormat, PlainDisplay, TtyDisplay,
};
use crate::pipeline::StepResult;

/// Result of the spawned on_failure hook task. Outer Result is the join
/// result; inner is `run_hook`'s return — `Some(text)` if the hook produced
/// output, `None` if it was suppressed (timeout, non-zero exit, empty stdout).
type HookHandle = JoinHandle<Result<Option<String>>>;

pub struct App {
    pub config: config::Config,
    pub config_path: PathBuf,
    pub root: PathBuf,
    pub display_config: DisplayConfig,
    /// Active profile name, set by `--profile <name>`. Purely informational
    /// at runtime — step filtering already happened via `apply_profile` before
    /// `App` was constructed. Shown in the watch banner when present.
    pub profile: Option<String>,
}

/// Filters `cfg.steps` to the named profile's members, preserving declaration
/// order. Errors if the profile name isn't defined in `cfg.profiles` or if a
/// member name references a step that no longer exists (the latter should be
/// caught by `validate`, but we check defensively).
///
/// Composes with `--staged` / `--since` / `if_changed`: this narrows the step
/// list first, then later path filtering narrows further.
pub fn apply_profile(cfg: &mut config::Config, profile_name: &str) -> Result<()> {
    let members = cfg.profiles.get(profile_name).ok_or_else(|| {
        let mut available: Vec<&String> = cfg.profiles.keys().collect();
        available.sort();
        if available.is_empty() {
            anyhow::anyhow!("profile `{profile_name}` not found (no profiles defined in config)")
        } else {
            let list = available
                .iter()
                .map(|s| s.as_str())
                .collect::<Vec<_>>()
                .join(", ");
            anyhow::anyhow!("profile `{profile_name}` not found (defined: {list})")
        }
    })?;

    let wanted: std::collections::HashSet<&str> = members.iter().map(String::as_str).collect();
    cfg.steps.retain(|s| wanted.contains(s.name.as_str()));

    if cfg.steps.is_empty() {
        anyhow::bail!("profile `{profile_name}` resolved to zero steps");
    }

    Ok(())
}

/// Options for a one-shot `App::run_once` invocation.
#[derive(Debug, Default, Clone)]
pub struct RunOnceOptions {
    /// Skip the configured `[on_failure]` hook even if enabled.
    pub no_hook: bool,

    /// Initial trigger paths (relative to `App.root`). When `Some`, the
    /// pipeline filters steps by `if_changed` and substitutes `{files}`
    /// exactly as watch-mode does on a file-change. `None` runs every step.
    pub initial_trigger: Option<Vec<PathBuf>>,
}

impl App {
    /// Convenience wrapper that uses Ctrl+C as the shutdown signal.
    /// Production entry point.
    pub async fn run(self) -> Result<()> {
        let stop = async {
            let _ = tokio::signal::ctrl_c().await;
        };
        self.run_until(stop).await
    }

    /// Constructs the display the watch loop uses based on `display_config`.
    /// `JsonDisplay` when format is Json; otherwise `TtyDisplay` when attached
    /// to a terminal, `PlainDisplay` for non-TTY contexts.
    fn build_display(&self) -> Box<dyn Display> {
        let dc = &self.display_config;
        if dc.format == OutputFormat::Json {
            return Box::new(JsonDisplay::new());
        }
        let color = should_color(dc.is_tty);
        if dc.is_tty {
            Box::new(TtyDisplay::new(
                Theme::new(color),
                dc.verbosity,
                dc.no_clear,
            ))
        } else {
            Box::new(PlainDisplay::new(Theme::new(color), dc.verbosity))
        }
    }

    /// Runs the configured pipeline exactly once and returns whether every
    /// step passed. Uses `PlainDisplay` unconditionally (no spinner, no browse
    /// mode) so output is scriptable. Writes `.baraddur/last-run.log` and,
    /// unless `opts.no_hook`, runs the configured `[on_failure]` hook
    /// synchronously when the run fails.
    pub async fn run_once(self, opts: RunOnceOptions) -> Result<bool> {
        let dc = &self.display_config;
        let mut display: Box<dyn Display> = if dc.format == OutputFormat::Json {
            Box::new(JsonDisplay::new())
        } else {
            let color = should_color(dc.is_tty);
            Box::new(PlainDisplay::new(Theme::new(color), dc.verbosity))
        };

        display.banner(
            &self.root,
            &self.config_path,
            self.config.steps.len(),
            self.profile.as_deref(),
        );

        if let Some(paths) = opts.initial_trigger.as_deref() {
            display.set_trigger(paths);
        }

        let results = pipeline::run_pipeline(
            &self.config,
            &self.root,
            display.as_mut(),
            None,
            opts.initial_trigger.as_deref(),
            None,
        )
        .await?;

        write_run_log(&self.root, &results);

        let success = results.iter().all(|r| r.success);

        if !success && !opts.no_hook && self.config.on_failure.enabled {
            display.hook_started();
            let combined = pipeline::combine_failed_output(&results);
            match pipeline::run_hook(&self.config.on_failure, &self.root, &combined).await {
                Ok(Some(text)) => display.hook_output(&text),
                _ => display.hook_finished(),
            }
        }

        Ok(success)
    }

    /// Runs the pipeline once; if it passes, executes `wrapped` (replacing
    /// the current process on Unix, spawn+wait on Windows). Returns the exit
    /// code to surface from `baraddur gate`.
    ///
    /// Empty trigger (e.g. `--staged` with nothing staged) skips the pipeline
    /// and execs immediately — there's nothing to verify.
    ///
    /// The configured `[on_failure]` hook timeout is clamped to 15s for gate
    /// so the gate fails fast (vs the watch-mode default of 30s).
    pub async fn gate(mut self, wrapped: Vec<String>, opts: RunOnceOptions) -> Result<i32> {
        if wrapped.is_empty() {
            anyhow::bail!("gate: no command provided");
        }

        let skip_pipeline = matches!(&opts.initial_trigger, Some(paths) if paths.is_empty());

        if !skip_pipeline {
            self.config.on_failure.timeout_secs = self.config.on_failure.timeout_secs.min(15);
            let success = self.run_once(opts).await?;
            if !success {
                return Ok(1);
            }
        }

        exec_wrapped(&wrapped)
    }

    /// Runs the watch loop until either `stop` resolves or the watcher dies.
    /// Exposed so tests can drive the loop without sending SIGINT to the test runner.
    // `last_failed_steps` is initialized to None as a placeholder; the first
    // read only happens after at least one Completed has overwritten it, so
    // the initial None is correctly diagnosed as unused. The placeholder is
    // required for control-flow init.
    #[allow(unused_assignments)]
    pub async fn run_until<F>(self, stop: F) -> Result<()>
    where
        F: Future<Output = ()>,
    {
        tokio::pin!(stop);
        let dc = &self.display_config;

        let spinner_interval = if dc.is_tty {
            Some(Duration::from_millis(80))
        } else {
            None
        };

        let mut display: Box<dyn Display> = self.build_display();

        // Show startup banner once before the first run.
        display.banner(
            &self.root,
            &self.config_path,
            self.config.steps.len(),
            self.profile.as_deref(),
        );

        let wcfg = watcher::WatchConfig {
            root: self.root.clone(),
            debounce: Duration::from_millis(self.config.watch.debounce_ms),
            extensions: self.config.watch.extensions.clone(),
            ignore: self.config.watch.ignore.clone(),
        };
        let mut rx = watcher::start(wcfg)?;

        // Single long-lived OS thread drains crossterm events into a channel.
        // Per-iteration spawn_blocking readers leaked: their JoinHandles were
        // dropped on file-change cancellation but the threads kept blocking
        // inside event::read(), then stole the next keystroke and exited.
        let mut key_rx = if dc.is_tty {
            Some(spawn_key_reader())
        } else {
            None
        };

        if dc.verbosity == output::Verbosity::Debug {
            eprintln!("[debug] watcher started, running initial pipeline");
        }

        // In-flight on_failure hook task, set after a failing run and cleared
        // when it completes, the user saves a file, or shutdown begins.
        let mut hook_handle: Option<HookHandle> = None;

        // Relative paths of files that triggered the current pipeline run.
        // `None` on the initial run; set on each `FileChange` and consumed by
        // the next `run_pipeline` invocation for path-based step filtering.
        let mut trigger_paths: Option<Vec<PathBuf>> = None;

        // Names of steps that failed in the most recent completed run.
        // Captured on `Completed`; consumed by the browse-mode `f` key, which
        // narrows the next run to just these steps via `rerun_filter`. `None`
        // until at least one run has completed.
        let mut last_failed_steps: Option<Vec<String>> = None;

        // Name filter for the next pipeline run. `Some(names)` runs only
        // matching steps (browse-mode `f`); `None` runs everything that
        // path-filtering left. Reset to `None` after each run completes.
        let mut rerun_filter: Option<Vec<String>> = None;

        'main: loop {
            let outcome = tokio::select! {
                biased;

                _ = &mut stop => RunOutcome::Shutdown,

                maybe = rx.recv() => {
                    match maybe {
                        Some(paths) => RunOutcome::FileChange(paths),
                        None => RunOutcome::WatcherDied,
                    }
                }

                result = pipeline::run_pipeline(
                    &self.config,
                    &self.root,
                    display.as_mut(),
                    spinner_interval,
                    trigger_paths.as_deref(),
                    rerun_filter.as_deref(),
                ) => RunOutcome::Completed(result),
            };

            // Pipeline future is dropped here — all child processes killed,
            // all borrows released. `display` is available again.
            match outcome {
                RunOutcome::Completed(result) => {
                    let results = result?;
                    write_run_log(&self.root, &results);

                    // Remember which steps failed so the browse-mode `f` key
                    // can rerun them; reset the filter so the next iteration
                    // doesn't accidentally re-apply it.
                    last_failed_steps = Some(
                        results
                            .iter()
                            .filter(|r| !r.success)
                            .map(|r| r.name.clone())
                            .collect(),
                    );
                    rerun_filter = None;

                    // Cancel any leftover hook from a prior run; spawn a new
                    // one if this run failed and the user has on_failure enabled.
                    if let Some(h) = hook_handle.take() {
                        h.abort();
                        display.hook_finished();
                    }
                    if self.config.on_failure.enabled && results.iter().any(|r| !r.success) {
                        let cfg = self.config.on_failure.clone();
                        let cwd = self.root.clone();
                        let combined = pipeline::combine_failed_output(&results);
                        hook_handle = Some(tokio::spawn(async move {
                            pipeline::run_hook(&cfg, &cwd, &combined).await
                        }));
                        display.hook_started();
                    }
                }
                RunOutcome::FileChange(paths) => {
                    while rx.try_recv().is_ok() {}
                    if dc.verbosity == output::Verbosity::Debug {
                        eprintln!("[debug] file change — restarting pipeline");
                        for p in &paths {
                            eprintln!("[debug]   triggered by: {}", p.display());
                        }
                    }
                    if let Some(h) = hook_handle.take() {
                        h.abort();
                        display.hook_finished();
                    }
                    let rel = rel_paths(&paths, &self.root);
                    display.run_cancelled();
                    display.set_trigger(&rel);
                    trigger_paths = Some(rel);
                    continue;
                }
                RunOutcome::Shutdown => {
                    if let Some(h) = hook_handle.take() {
                        h.abort();
                        display.hook_finished();
                    }
                    return self.shutdown();
                }
                RunOutcome::WatcherDied => {
                    eprintln!("baraddur: file watcher stopped unexpectedly. exiting.");
                    return Ok(());
                }
            }

            // ── Idle: wait for the next file change or Ctrl+C ───────────────
            if dc.verbosity == output::Verbosity::Debug {
                eprintln!("[debug] idle — waiting for file change");
            }

            // In TTY mode, enter interactive browse mode so the user can
            // navigate steps and expand output with vim-style keybindings.
            if dc.is_tty {
                let key_rx = key_rx
                    .as_mut()
                    .expect("key_rx initialized when dc.is_tty is true");

                // Discard any keystrokes that queued up during the pipeline run.
                while key_rx.try_recv().is_ok() {}

                display.enter_browse_mode();

                loop {
                    tokio::select! {
                        biased;

                        _ = &mut stop => {
                            if let Some(h) = hook_handle.take() { h.abort(); display.hook_finished(); }
                            display.exit_browse_mode();
                            return self.shutdown();
                        }

                        maybe = rx.recv() => {
                            if let Some(h) = hook_handle.take() { h.abort(); display.hook_finished(); }
                            display.exit_browse_mode();
                            match maybe {
                                Some(paths) => {
                                    while rx.try_recv().is_ok() {}
                                    if dc.verbosity == output::Verbosity::Debug {
                                        eprintln!("[debug] file change — triggering pipeline");
                                        for p in &paths {
                                            eprintln!("[debug]   triggered by: {}", p.display());
                                        }
                                    }
                                    let rel = rel_paths(&paths, &self.root);
                                    display.set_trigger(&rel);
                                    trigger_paths = Some(rel);
                                    continue 'main;
                                }
                                None => {
                                    eprintln!("baraddur: file watcher stopped unexpectedly. exiting.");
                                    return Ok(());
                                }
                            }
                        }

                        maybe_key = key_rx.recv() => {
                            match maybe_key {
                                Some(key) => match display.handle_key(key) {
                                    BrowseAction::Noop => {}
                                    BrowseAction::Redraw => display.browse_redraw_if_active(),
                                    BrowseAction::Quit => {
                                        if let Some(h) = hook_handle.take() { h.abort(); display.hook_finished(); }
                                        display.exit_browse_mode();
                                        return self.shutdown();
                                    }
                                    BrowseAction::Rerun => {
                                        if let Some(h) = hook_handle.take() { h.abort(); display.hook_finished(); }
                                        display.exit_browse_mode();
                                        trigger_paths = None;
                                        rerun_filter = None;
                                        continue 'main;
                                    }
                                    BrowseAction::RerunFailed => {
                                        if let Some(h) = hook_handle.take() { h.abort(); display.hook_finished(); }
                                        display.exit_browse_mode();
                                        trigger_paths = None;
                                        rerun_filter = last_failed_steps.clone();
                                        continue 'main;
                                    }
                                    BrowseAction::RerunCursor(name) => {
                                        if let Some(h) = hook_handle.take() { h.abort(); display.hook_finished(); }
                                        display.exit_browse_mode();
                                        trigger_paths = None;
                                        rerun_filter = Some(vec![name]);
                                        continue 'main;
                                    }
                                },
                                None => {
                                    display.exit_browse_mode();
                                    eprintln!("baraddur: keyboard reader stopped unexpectedly. exiting.");
                                    return Ok(());
                                }
                            }
                        }

                        // Hook task completed: forward its output (if any) into
                        // the browse-mode footer. Never breaks the loop — user
                        // stays in browse until a file change or `q`.
                        res = await_hook(&mut hook_handle), if hook_handle.is_some() => {
                            hook_handle = None;
                            match res {
                                Ok(Ok(Some(text))) => display.hook_output(&text),
                                _ => display.hook_finished(),
                            }
                        }
                    }
                }
            }

            // Plain idle wait: non-TTY mode only (TTY mode loops inside browse above).
            // Loops so that an in-flight hook completion doesn't fall through —
            // we keep waiting for the next file-change or shutdown after it fires.
            'idle: loop {
                tokio::select! {
                    biased;

                    _ = &mut stop => {
                        if let Some(h) = hook_handle.take() { h.abort(); }
                        return self.shutdown();
                    }

                    maybe = rx.recv() => {
                        if let Some(h) = hook_handle.take() { h.abort(); }
                        match maybe {
                            Some(paths) => {
                                while rx.try_recv().is_ok() {}
                                if dc.verbosity == output::Verbosity::Debug {
                                    eprintln!("[debug] file change — triggering pipeline");
                                    for p in &paths {
                                        eprintln!("[debug]   triggered by: {}", p.display());
                                    }
                                }
                                let rel = rel_paths(&paths, &self.root);
                                display.set_trigger(&rel);
                                trigger_paths = Some(rel);
                                break 'idle; // fall through to loop top → rerun pipeline
                            }
                            None => {
                                eprintln!("baraddur: file watcher stopped unexpectedly. exiting.");
                                return Ok(());
                            }
                        }
                    }

                    res = await_hook(&mut hook_handle), if hook_handle.is_some() => {
                        hook_handle = None;
                        match res {
                            Ok(Ok(Some(text))) => display.hook_output(&text),
                            _ => display.hook_finished(),
                        }
                        // continue idle loop — wait for next event
                    }
                }
            }
        }
    }

    fn shutdown(&self) -> Result<()> {
        eprintln!("\nbaraddur: exiting...");

        // Double-tap handler: a second Ctrl+C force-exits immediately.
        tokio::spawn(async {
            tokio::signal::ctrl_c().await.ok();
            eprintln!("baraddur: force exit.");
            std::process::exit(130);
        });

        Ok(())
    }
}

/// Awaits the on_failure hook task if one is in flight; otherwise pends
/// forever. Used as a select! arm so the main loop can react to hook
/// completion without blocking when no hook is active.
async fn await_hook(
    handle: &mut Option<HookHandle>,
) -> std::result::Result<Result<Option<String>>, tokio::task::JoinError> {
    match handle.as_mut() {
        Some(h) => h.await,
        None => std::future::pending().await,
    }
}

/// Spawns a dedicated OS thread that loops on `crossterm::event::read()` and
/// forwards key events onto a channel. One reader per process — the channel
/// outlives any single browse-mode session, so file-change cancellation no
/// longer leaks blocked readers that steal subsequent keystrokes.
///
/// The thread exits when the receiver is dropped or `event::read()` errors.
fn spawn_key_reader() -> tokio::sync::mpsc::Receiver<crossterm::event::KeyEvent> {
    let (tx, rx) = tokio::sync::mpsc::channel(16);
    let _ = std::thread::Builder::new()
        .name("baraddur-keys".into())
        .spawn(move || {
            loop {
                match crossterm::event::read() {
                    Ok(crossterm::event::Event::Key(k)) => {
                        if tx.blocking_send(k).is_err() {
                            return;
                        }
                    }
                    Ok(_) => {}
                    Err(_) => return,
                }
            }
        });
    rx
}

/// Writes all step output for the last run to `.baraddur/last-run.log`.
/// Silently no-ops if the directory cannot be created or the file cannot be written.
fn write_run_log(root: &Path, results: &[StepResult]) {
    let log_dir = root.join(".baraddur");
    if std::fs::create_dir_all(&log_dir).is_err() {
        return;
    }

    let mut content = String::new();
    for r in results {
        let _ = writeln!(
            content,
            "═══ {} ({}) ═══",
            r.name,
            if r.success { "pass" } else { "FAIL" }
        );
        if !r.stdout.is_empty() {
            content.push_str(&r.stdout);
            if !r.stdout.ends_with('\n') {
                content.push('\n');
            }
        }
        if !r.stderr.is_empty() {
            content.push_str("--- stderr ---\n");
            content.push_str(&r.stderr);
            if !r.stderr.ends_with('\n') {
                content.push('\n');
            }
        }
        content.push('\n');
    }

    let _ = std::fs::write(log_dir.join("last-run.log"), &content);
}

fn rel_paths(paths: &[PathBuf], root: &Path) -> Vec<PathBuf> {
    paths
        .iter()
        .map(|p| p.strip_prefix(root).unwrap_or(p).to_path_buf())
        .collect()
}

/// Replaces the current process with `args` on Unix; spawns+waits on
/// Windows. Returns the exit code only on Windows or when exec fails — on
/// Unix the successful path never returns.
fn exec_wrapped(args: &[String]) -> Result<i32> {
    let (program, rest) = args
        .split_first()
        .ok_or_else(|| anyhow::anyhow!("no command provided"))?;

    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        // `exec` only returns when it fails — on success the process image
        // is replaced and this function never returns.
        let err = std::process::Command::new(program).args(rest).exec();
        Err(anyhow::Error::new(err).context(format!("exec `{program}`")))
    }

    #[cfg(not(unix))]
    {
        use anyhow::Context as _;
        let status = std::process::Command::new(program)
            .args(rest)
            .status()
            .with_context(|| format!("spawning `{program}`"))?;
        Ok(status.code().unwrap_or(1))
    }
}

enum RunOutcome {
    Completed(Result<Vec<StepResult>>),
    FileChange(Vec<PathBuf>),
    Shutdown,
    WatcherDied,
}

#[cfg(test)]
mod apply_profile_tests {
    use super::*;
    use crate::config::{Config, OnFailureConfig, OutputConfig, Step, WatchConfig};

    fn step(name: &str) -> Step {
        Step {
            name: name.into(),
            cmd: "true".into(),
            parallel: false,
            if_changed: Vec::new(),
        }
    }

    fn cfg_with_steps(names: &[&str]) -> Config {
        Config {
            watch: WatchConfig {
                extensions: vec!["rs".into()],
                debounce_ms: 1000,
                ignore: vec![],
            },
            output: OutputConfig::default(),
            on_failure: OnFailureConfig::default(),
            steps: names.iter().map(|n| step(n)).collect(),
            profiles: std::collections::HashMap::new(),
        }
    }

    #[test]
    fn filters_steps_to_profile_members_preserving_order() {
        let mut cfg = cfg_with_steps(&["fmt", "check", "clippy", "test"]);
        cfg.profiles
            .insert("quick".into(), vec!["check".into(), "fmt".into()]);

        apply_profile(&mut cfg, "quick").unwrap();

        let names: Vec<&str> = cfg.steps.iter().map(|s| s.name.as_str()).collect();
        assert_eq!(names, vec!["fmt", "check"]);
    }

    #[test]
    fn errors_when_profile_name_unknown() {
        let mut cfg = cfg_with_steps(&["fmt"]);
        cfg.profiles.insert("quick".into(), vec!["fmt".into()]);

        let err = apply_profile(&mut cfg, "missing").unwrap_err();
        let s = err.to_string();
        assert!(s.contains("profile `missing` not found"), "msg: {s}");
        assert!(s.contains("quick"), "expected available list in msg: {s}");
    }

    #[test]
    fn errors_when_no_profiles_defined() {
        let mut cfg = cfg_with_steps(&["fmt"]);
        let err = apply_profile(&mut cfg, "anything").unwrap_err();
        assert!(err.to_string().contains("no profiles defined"));
    }

    #[test]
    fn errors_when_profile_resolves_to_zero_steps() {
        let mut cfg = cfg_with_steps(&["fmt"]);
        cfg.profiles.insert("ghost".into(), vec!["nope".into()]);
        let err = apply_profile(&mut cfg, "ghost").unwrap_err();
        assert!(err.to_string().contains("zero steps"));
    }
}