baztet 1.0.0

Standalone Bazel project sync and execution CLI (Rust port of the hirschgarten engine)
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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
use std::collections::HashSet;
use std::process::ExitCode;

#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;

use baztet_core::{sync as sync_engine, BazelError, BazelRunner};
use camino::Utf8PathBuf;
use clap::{Parser, Subcommand};

// stderr presentation; --json and machine outputs stay untouched

use owo_colors::OwoColorize;
use owo_colors::Stream;

fn ok(msg: &str) {
    eprintln!(
        "{}",
        format!("✓ {msg}").if_supports_color(Stream::Stderr, |t| t.green().to_string())
    );
}

fn warn(msg: &str) {
    eprintln!(
        "{}",
        format!("! {msg}").if_supports_color(Stream::Stderr, |t| t.yellow().to_string())
    );
}

fn fail(msg: &str) {
    eprintln!(
        "{}",
        format!("✗ {msg}").if_supports_color(Stream::Stderr, |t| t.red().to_string())
    );
}

fn phase(n: u8, total: u8, label: &str, secs: f64) {
    eprintln!(
        "{}",
        format!("[{n}/{total}] {label} ({secs:.1}s)")
            .if_supports_color(Stream::Stderr, |t| t.blue().to_string())
    );
}

fn test_status_colored(status: &str) -> String {
    // pad the plain status first: width formatting on an ANSI-wrapped string
    // pads against escape bytes, not visible width; style after padding and
    // gate on the stream support
    format!("{status:>8}")
        .if_supports_color(Stream::Stdout, |t| match status {
            "PASSED" => t.bright_green().to_string(),
            "FAILED" => t.bright_red().to_string(),
            _ => t.bright_yellow().to_string(),
        })
        .to_string()
}

/// Does this BEP status fail the exit code? Any non-PASSED verdict does
/// (CI gates on the exit code); display buckets are finer than this.
fn status_is_failure(status: &str) -> bool {
    status != "PASSED"
}

#[derive(Parser)]
#[command(
    name = "baztet",
    version,
    about = "Standalone Bazel project sync and execution tool"
)]
struct Cli {
    /// path to the bazel binary (project view `bazel_binary` overrides)
    #[arg(long, global = true, env = "BAZTET_BAZEL")]
    bazel: Option<String>,

    /// workspace directory (defaults to the closest one above cwd)
    #[arg(long, global = true)]
    workspace: Option<Utf8PathBuf>,

    /// project view file (defaults to <workspace>/.bazelproject)
    #[arg(long, global = true)]
    project_view: Option<Utf8PathBuf>,

    /// snapshot cache directory (defaults to the platform cache dir;
    /// env: BAZTET_CACHE_DIR)
    #[arg(long, global = true, env = "BAZTET_CACHE_DIR")]
    cache_dir: Option<Utf8PathBuf>,

    /// skip bazel's output-file freshness scan (`--noexperimental_check_
    /// output_files`): warm syncs get faster, stale outputs are trusted
    #[arg(long, global = true)]
    no_output_check: bool,

    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Sync the project: query phase + aspect phase, save the snapshot.
    Sync {
        /// print the resulting snapshot as JSON to stdout
        #[arg(long)]
        json: bool,
        /// force a full re-query even when the project view is unchanged
        #[arg(long)]
        fresh: bool,
        /// stop after the fast query phase (skip aspect analysis)
        #[arg(long)]
        fast: bool,
    },
    /// Run `bazel build` on labels (or every synced target).
    #[command(after_help = "Anything after `--` is passed through to bazel.")]
    Build {
        labels: Vec<String>,
        /// args after `--` go straight to bazel
        #[arg(last = true)]
        passthrough: Vec<String>,
    },
    /// Run `bazel test` with BEP-based results and junit XML case reports.
    #[command(after_help = "Anything after `--` is passed through to bazel.")]
    Test {
        /// labels; defaults to every *_test target in the snapshot
        labels: Vec<String>,
        /// value for `--test_filter`
        #[arg(long)]
        filter: Option<String>,
        /// select test targets by label substring instead of listing all
        #[arg(long, short)]
        pattern: Option<String>,
        /// print per-case results from test.xml files
        #[arg(long)]
        cases: bool,
        /// print a machine-readable report to stdout
        #[arg(long)]
        json: bool,
        #[arg(last = true)]
        passthrough: Vec<String>,
    },
    /// Run one target with `bazel run` (output streamed).
    #[command(after_help = "Anything after `--` is passed through to bazel.")]
    Run {
        label: String,
        #[arg(last = true)]
        passthrough: Vec<String>,
    },
    /// Run `bazel coverage` and point at the merged lcov report.
    Coverage {
        labels: Vec<String>,
        #[arg(last = true)]
        passthrough: Vec<String>,
    },
    /// Check the environment: bazel binary/version, workspace, project view,
    /// snapshot, aspect deployment.
    Doctor,
    /// Benchmarks: startup, proto stream decode, snapshot roundtrip.
    Bench {
        /// number of synthetic targets to stream-decode
        #[arg(long, default_value = "50000")]
        targets: u64,
    },
    /// List imported run configurations (recipes) from the project view.
    Recipes {
        /// run one recipe: `baztet test --recipe acceptance-tests`
        #[arg(long, short)]
        run: Option<String>,
        /// print a machine-readable report to stdout
        #[arg(long)]
        json: bool,
    },
    /// List targets in the synced snapshot.
    Targets {
        /// label substring, or rule kind with '=' prefix (e.g. =java_library)
        #[arg(long, short)]
        filter: Option<String>,
        #[arg(long)]
        json: bool,
    },
    /// Show dependencies of a target.
    Deps {
        /// target label like //foo:bar
        label: String,
        /// show reverse dependencies instead
        #[arg(long)]
        reverse: bool,
        /// include transitive dependencies
        #[arg(long, short = 'r')]
        transitive: bool,
    },
}

fn main() -> ExitCode {
    // parse + env write before any runtime spawns worker threads:
    // process env is not thread-safe, and BAZTET_CACHE_DIR is read later
    let cli = Cli::parse();
    if let Some(dir) = &cli.cache_dir {
        std::env::set_var("BAZTET_CACHE_DIR", dir);
    }
    async_main(&cli)
}

#[tokio::main(flavor = "multi_thread")]
async fn async_main(cli: &Cli) -> ExitCode {
    match run(cli).await {
        Ok(code) => code,
        Err(e) => {
            fail(&format!("{e}"));
            for cause in e.chain().skip(1) {
                eprintln!("  ↳ {cause}");
            }
            for cause in e.chain() {
                if let Some(BazelError::Failure(_, code, _)) = cause.downcast_ref() {
                    return exit_code(*code);
                }
            }
            ExitCode::FAILURE
        }
    }
}

fn exit_code(code: i32) -> ExitCode {
    u8::try_from(code).map_or(ExitCode::FAILURE, ExitCode::from)
}

async fn run(cli: &Cli) -> anyhow::Result<ExitCode> {
    use baztet_core::exec::{ExecSpec, Recipe};

    fn spec(labels: Vec<String>, passthrough: Vec<String>) -> ExecSpec {
        ExecSpec {
            labels,
            extra_args: passthrough,
            ..Default::default()
        }
    }

    fn exit_for(command: &str, code: i32) -> ExitCode {
        if code != 0 {
            eprintln!("[baztet] {command} failed with exit code {code}");
        }
        exit_code(code)
    }

    fn test_labels(
        snapshot: &baztet_snapshot::Snapshot,
        labels: &[String],
        pattern: &Option<String>,
    ) -> anyhow::Result<Vec<String>> {
        if !labels.is_empty() {
            return Ok(labels.to_vec());
        }
        let tests: Vec<String> = snapshot
            .graph
            .iter()
            .filter(|t| t.kind.ends_with("_test") || t.kind.ends_with("test_suite"))
            .map(|t| t.label.clone())
            .collect();
        if tests.is_empty() {
            anyhow::bail!("no *_test targets in the snapshot; run `baztet sync` first");
        }
        if let Some(p) = pattern {
            let selected: Vec<String> = tests
                .iter()
                .filter(|l| l.contains(p.as_str()))
                .cloned()
                .collect();
            if selected.is_empty() {
                anyhow::bail!("no test target matches '{p}'");
            }
            return Ok(selected);
        }
        Ok(tests)
    }

    match &cli.command {
        Command::Sync { json, fresh, fast } => {
            let runner = runner_for(cli, true).await?;
            let pv_path = cli
                .project_view
                .clone()
                .unwrap_or_else(|| runner.workspace_root.join(".bazelproject"));
            if !pv_path.is_file() {
                anyhow::bail!("project view not found at {pv_path}");
            }
            let pv = baztet_projectview::parse(&pv_path, &runner.workspace_root)?;
            let report = sync_engine::sync(&runner, &pv, !fast, *fresh).await?;
            let snapshot = &report.snapshot;
            let path = snapshot.save()?;

            match report.reuse {
                sync_engine::Reuse::Everything => warn(&format!(
                    "nothing changed: snapshot reused ({} target(s), {} ide entries)",
                    snapshot.graph.len(),
                    snapshot.ide_infos.len()
                )),
                sync_engine::Reuse::Graph => {
                    phase(
                        1,
                        2,
                        "query graph reused",
                        report.query_secs.unwrap_or_default(),
                    );
                    phase(
                        2,
                        2,
                        "aspect outputs",
                        report.aspect_secs.unwrap_or_default(),
                    );
                }
                sync_engine::Reuse::FullQuery => {
                    phase(1, 2, "query", report.query_secs.unwrap_or_default());
                    // the aspect phase prints only when it ran (--fast skips it)
                    if let Some(secs) = report.aspect_secs {
                        phase(2, 2, "aspect build + BEP", secs);
                    }
                }
            }

            let line = format!(
                "synced {} target(s) · {} ide entries · snapshot {path}",
                snapshot.graph.len(),
                snapshot.ide_infos.len()
            );
            if snapshot.has_error {
                fail(&format!("{line} (some outputs failed)"));
            } else {
                ok(&line);
            }
            if *json {
                println!("{}", snapshot.to_json(true)?);
            }
            Ok(ExitCode::SUCCESS)
        }
        Command::Build {
            labels,
            passthrough,
        } => {
            let runner = runner_for(cli, false).await?;
            let snapshot = load_snapshot(workspace_of(cli)?)?;
            let labels = default_labels(&snapshot, labels)?;
            let result = runner
                .exec_build(
                    &load_pv(&runner, None)?,
                    &spec(labels.clone(), passthrough.clone()),
                )
                .await?;
            Ok(exit_for("build", result.code))
        }
        Command::Test {
            labels,
            filter,
            pattern,
            cases,
            json,
            passthrough,
        } => {
            let runner = runner_for(cli, false).await?;
            let snapshot = load_snapshot(workspace_of(cli)?)?;
            let labels = test_labels(&snapshot, labels, pattern)?;
            let mut spec = spec(labels, passthrough.clone());
            spec.test_filter = filter.clone();
            let result = runner.exec_test(&load_pv(&runner, None)?, &spec).await?;

            let bep = result
                .bep
                .as_ref()
                .ok_or_else(|| anyhow::anyhow!("no BEP output"))?;
            let per_target: Vec<(&String, &String)> = bep
                .test_summaries
                .iter()
                .map(|s| (&s.label, &s.status))
                .collect();
            let parsed = baztet_core::exec::test_cases_from_bep(&runner, bep);
            let failed = result.code != 0
                || bep
                    .test_summaries
                    .iter()
                    .any(|s| status_is_failure(&s.status));

            if *json {
                let report = serde_json::json!({
                    "exit_code": result.code,
                    "summaries": bep.test_summaries,
                    "cases": parsed.iter().map(|(label, cases)| {
                        serde_json::json!({
                            "label": label,
                            "cases": cases,
                        })
                    }).collect::<Vec<_>>(),
                });
                println!("{}", serde_json::to_string_pretty(&report)?);
            } else {
                let (mut pass, mut fail, mut other) = (0usize, 0usize, 0usize);
                for (label, status) in &per_target {
                    println!("{}  {label}", test_status_colored(status));
                    match status.as_str() {
                        "PASSED" => pass += 1,
                        // test verdicts that count against the exit code;
                        // anything else (CANCELLED, NO_STATUS, ...) is
                        // neither passed nor failed by a verdict
                        "FAILED" | "TIMEOUT" | "FLAKY" => fail += 1,
                        _ => other += 1,
                    }
                }
                if *cases {
                    use baztet_core::exec::TestCaseStatus;
                    for (label, case_list) in &parsed {
                        for case in case_list {
                            if !matches!(
                                case.status,
                                TestCaseStatus::Failed | TestCaseStatus::Error
                            ) {
                                continue;
                            }
                            let status = if case.status == TestCaseStatus::Error {
                                "ERROR"
                            } else {
                                "FAILED"
                            };
                            println!(
                                "    {:>8}  {}#{}  {}  ({label})",
                                status,
                                case.class_name,
                                case.name,
                                case.message.as_deref().unwrap_or("no message"),
                            );
                        }
                    }
                }
                let summary = format!(
                    "{pass} passed · {fail} failed · {other} other ({})",
                    per_target.len()
                );
                println!("{}", summary);
            }
            Ok(exit_for(
                "test",
                if failed && result.code == 0 {
                    3
                } else {
                    result.code
                },
            ))
        }
        Command::Run { label, passthrough } => {
            let runner = runner_for(cli, false).await?;
            let result = runner
                .exec_run(
                    &load_pv(&runner, None)?,
                    &spec(vec![label.clone()], passthrough.clone()),
                )
                .await?;
            Ok(exit_for("run", result.code))
        }
        Command::Coverage {
            labels,
            passthrough,
        } => {
            let runner = runner_for(cli, false).await?;
            let snapshot = load_snapshot(workspace_of(cli)?)?;
            let labels = default_labels(&snapshot, labels)?;
            let result = runner
                .exec_coverage(
                    &load_pv(&runner, None)?,
                    &spec(labels.clone(), passthrough.clone()),
                )
                .await?;
            if let Some(bep) = result.bep.as_ref() {
                // lcov merged report referenced in BEP build tool logs / outputs
                let merged: Vec<_> = bep
                    .named_sets
                    .values()
                    .flat_map(|s| &s.files)
                    .filter(|f| f.name.contains("lcov"))
                    .map(|f| f.relative_path())
                    .collect();
                for path in merged {
                    println!("{path}");
                }
            }
            Ok(exit_for("coverage", result.code))
        }
        Command::Recipes { run, json } => {
            let runner = runner_for(cli, false).await?;
            let pv = load_pv(&runner, cli.project_view.as_ref())?;
            let mut recipes: Vec<Recipe> = Vec::new();
            let mut missing = 0usize;
            for path in &pv.import_run_configurations {
                let rel = path.trim_start_matches('/');
                match std::fs::read_to_string(runner.workspace_root.join(rel)) {
                    Ok(xml) => {
                        if let Some(r) = baztet_core::exec::parse_recipe(&xml) {
                            recipes.push(r);
                        }
                    }
                    Err(_) => missing += 1,
                }
            }
            if *json {
                println!("{}", serde_json::to_string_pretty(&recipes)?);
            } else {
                if missing > 0 {
                    eprintln!("[baztet] {missing} recipe(s) not found on disk");
                }
                for r in &recipes {
                    println!(
                        "{}: {} {}  ({} env)",
                        r.name,
                        r.command,
                        r.target,
                        r.env.len()
                    );
                }
            }
            match run {
                Some(name) => {
                    let Some(recipe) = recipes.iter().find(|r| {
                        r.name.contains(name.as_str())
                            || name.is_empty()
                            || r.target.contains(name.as_str())
                    }) else {
                        anyhow::bail!("recipe '{name}' not found; see `baztet recipes`");
                    };
                    eprintln!(
                        "[baztet] recipe '{}': {} {}",
                        recipe.name, recipe.command, recipe.target
                    );
                    let mut spec = ExecSpec {
                        labels: vec![recipe.target.clone()],
                        env: recipe.env.clone(),
                        ..Default::default()
                    };
                    if recipe.command == "test" {
                        // acceptance/unit recipes run their target; no extra filter
                        let result = runner.exec_test(&pv, &spec).await?;
                        Ok(exit_for("test", result.code))
                    } else if recipe.command == "build" {
                        let result = runner.exec_build(&pv, &spec).await?;
                        Ok(exit_for("build", result.code))
                    } else if recipe.command == "run" {
                        spec.extra_args.push("--single_top_level_target".into());
                        let result = runner.exec_run(&pv, &spec).await?;
                        Ok(exit_for("run", result.code))
                    } else {
                        anyhow::bail!("unsupported recipe command: {}", recipe.command);
                    }
                }
                None => Ok(ExitCode::SUCCESS),
            }
        }
        Command::Doctor => {
            use std::fmt::Write as DocWrite;
            let mut report = String::new();
            let mut ok = true;

            writeln!(report, "baztet doctor")?;
            // bazel
            let binary = cli.bazel.as_deref().unwrap_or("bazel");
            let version = std::process::Command::new(binary).arg("--version").output();
            match version {
                Ok(out) if out.status.success() => {
                    writeln!(
                        report,
                        "bazel: {} ({})",
                        binary,
                        String::from_utf8_lossy(&out.stdout).trim()
                    )?;
                }
                _ => {
                    writeln!(report, "bazel: {binary} NOT FOUND or not runnable")?;
                    ok = false;
                }
            }
            // workspace
            let ws = workspace_of(cli)?;
            writeln!(report, "workspace: {ws}")?;
            // project view
            let pv_path = ws.join(".bazelproject");
            match pv_path.is_file() {
                true => writeln!(report, "project view: {pv_path}")?,
                false => writeln!(report, "project view: not present (scoped views elsewhere)")?,
            }
            // snapshot
            match baztet_snapshot::Snapshot::load(&ws) {
                Ok(snapshot) => writeln!(
                    report,
                    "snapshot: {} target(s), {} ide entries{}, last fingerprint {:?}",
                    snapshot.graph.len(),
                    snapshot.ide_infos.len(),
                    if snapshot.has_error {
                        " (has errors)"
                    } else {
                        ""
                    },
                    snapshot.sync_fingerprint,
                )?,
                Err(e) => writeln!(report, "snapshot: none ({e})")?,
            }
            // aspect dir
            let aspect = ws.join(baztet_core::sync::ASPECT_PREFIX);
            match aspect.join("config/aspect.bzl").is_file() {
                true => writeln!(report, "aspect: deployed at {aspect}")?,
                false => writeln!(report, "aspect: not deployed yet (first sync) and .bazelbsp (IDE) state unknown; not an error")?,
            }
            print!("{report}");
            Ok(if ok { ExitCode::SUCCESS } else { exit_code(1) })
        }
        Command::Bench { targets } => {
            let result = baztet_core::bench::run(*targets).await?;
            eprintln!(
                "[baztet] decoded {} targets in {:?}; 10k-target snapshot roundtrip {:?}",
                result.decoded, result.decode_duration, result.snapshot_roundtrip
            );
            Ok(ExitCode::SUCCESS)
        }
        Command::Targets { filter, json } => {
            let snapshot = load_snapshot(workspace_of(cli)?)?;
            let mut targets: Vec<&baztet_snapshot::TargetNode> = snapshot
                .graph
                .iter()
                .filter(|t| match filter {
                    Some(f) => {
                        if t.label.contains(f.as_str()) {
                            return true;
                        }
                        f.strip_prefix('=').is_some_and(|k| t.kind == k)
                    }
                    None => true,
                })
                .collect();
            targets.sort_by(|a, b| a.label.cmp(&b.label));
            if *json {
                println!("{}", serde_json::to_string_pretty(&targets)?);
            } else {
                for t in targets {
                    println!("{} [{}]", t.label, t.kind);
                }
            }
            Ok(ExitCode::SUCCESS)
        }
        Command::Deps {
            label,
            reverse,
            transitive,
        } => {
            if !label.starts_with("//") && !label.starts_with('@') {
                anyhow::bail!("not a bazel label: {label}");
            }
            let snapshot = load_snapshot(workspace_of(cli)?)?;
            let Some(idx) = snapshot.graph.index_of(label) else {
                anyhow::bail!("target {label} not in snapshot; run `baztet sync` first");
            };
            let graph = &snapshot.graph;
            let labels: Vec<String> = if *reverse {
                if !*transitive {
                    let mut out: Vec<String> = graph
                        .reverse_deps_indices(idx)
                        .into_iter()
                        .filter_map(|i| graph.get_by_index(i).map(|t| t.label.clone()))
                        .collect();
                    out.sort();
                    out
                } else {
                    let mut out = vec![];
                    let mut seen = HashSet::new();
                    let mut queue = vec![idx];
                    let mut pos = 0;
                    while pos < queue.len() {
                        let node_idx = queue[pos];
                        pos += 1;
                        for dep_idx in graph.reverse_deps_indices(node_idx) {
                            if seen.insert(dep_idx) {
                                out.push(graph.get_by_index(dep_idx).unwrap().label.clone());
                                queue.push(dep_idx);
                            }
                        }
                    }
                    out.sort();
                    out
                }
            } else {
                let direct = &graph.get_by_index(idx).unwrap().deps;
                let indices = if *transitive {
                    graph.transitive_deps(idx)
                } else {
                    direct.clone()
                };
                indices
                    .into_iter()
                    .skip(if *transitive { 1 } else { 0 })
                    .filter_map(|i| graph.get_by_index(i).map(|t| t.label.clone()))
                    .collect()
            };
            for l in &labels {
                println!("{l}");
            }
            // rule inputs outside the graph: external deps, generated files
            if !*reverse {
                for u in graph.unlinked_deps(idx) {
                    println!("# unlinked: {u}");
                }
            }
            Ok(ExitCode::SUCCESS)
        }
    }
}

fn default_labels(
    snapshot: &baztet_snapshot::Snapshot,
    labels: &[String],
) -> anyhow::Result<Vec<String>> {
    if !labels.is_empty() {
        return Ok(labels.to_vec());
    }
    if snapshot.specified_targets.is_empty() {
        anyhow::bail!("no targets to build; run `baztet sync` first");
    }
    Ok(snapshot.specified_targets.clone())
}

fn load_pv(
    runner: &BazelRunner,
    explicit: Option<&Utf8PathBuf>,
) -> anyhow::Result<baztet_projectview::ProjectView> {
    let path = explicit
        .cloned()
        .unwrap_or_else(|| runner.workspace_root.join(".bazelproject"));
    if !path.is_file() {
        if explicit.is_some() {
            anyhow::bail!("project view not found at {path}");
        }
        eprintln!("[baztet] no project view at {path}; running with default flags");
        return Ok(Default::default());
    }
    Ok(baztet_projectview::parse(&path, &runner.workspace_root)?)
}

/// Project view for exec commands; empty when the workspace has none.
fn workspace_of(cli: &Cli) -> anyhow::Result<Utf8PathBuf> {
    match &cli.workspace {
        Some(ws) => Ok(ws.clone()),
        None => {
            let cwd = Utf8PathBuf::try_from(std::env::current_dir()?)?;
            baztet_core::workspace::find_workspace_root(&cwd)
                .ok_or_else(|| anyhow::anyhow!("no bazel workspace above {cwd}"))
        }
    }
}

fn load_snapshot(ws_root: Utf8PathBuf) -> anyhow::Result<baztet_snapshot::Snapshot> {
    baztet_snapshot::Snapshot::load(&ws_root)
        .map_err(|e| anyhow::anyhow!("no snapshot under {ws_root}: {e} — run `baztet sync` first"))
}

/// Runner plus tuning flags (`--no-output-check`).
async fn runner_for(cli: &Cli, refresh: bool) -> anyhow::Result<BazelRunner> {
    let mut runner = discover(cli, refresh).await?;
    if cli.no_output_check {
        runner
            .tuning_flags
            .push("--noexperimental_check_output_files".to_string());
    }
    Ok(runner)
}

/// Discover workspace + bazel binary; without `refresh`, reuse the
/// snapshot's cached info text so exec commands skip the info spawn
/// (only when the snapshot's bazel_binary matches).
async fn discover(cli: &Cli, refresh: bool) -> anyhow::Result<BazelRunner> {
    let ws = workspace_of(cli)?;
    // --bazel wins; else the project view's `bazel_binary`; else `bazel`
    let binary = match &cli.bazel {
        Some(b) => b.clone(),
        None => {
            let pv_path = ws.join(".bazelproject");
            if pv_path.is_file() {
                baztet_projectview::parse(&pv_path, &ws)?
                    .bazel_binary()
                    .to_owned()
            } else {
                "bazel".to_string()
            }
        }
    };
    if !refresh {
        if let Ok(snapshot) = baztet_snapshot::Snapshot::load(&ws) {
            // reuse the cached info only when the snapshot came from the
            // same binary: a --bazel swap must not keep the old
            // execution_root (paths would resolve wrong silently)
            let cached = snapshot
                .bazel_info_text
                .as_ref()
                .filter(|_| snapshot.bazel_binary.as_deref() == Some(binary.as_str()));
            if let Some(text) = cached {
                let info = baztet_core::workspace::parse_info(text);
                return Ok(BazelRunner::from_cached_info(&binary, ws, info));
            }
        }
    }
    Ok(BazelRunner::discover(&binary, &ws).await?)
}