buildl-cli 0.1.0

The `buildl` binary — the command-line entry point to the buildl library.
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
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
//! The text `doctor` prints: the workspace, its approver, its run settings, its remote cache, its
//! ceiling, one row per want saying whether the ceiling allows it and whether it is approved,
//! each row followed by the plugins behind it, and every want a plugin does not allow.
//!
//! Its own file because it is the one command whose output is a report laid out in columns,
//! read by a person deciding what to allow.
//!
//! Responsibilities: [`doctor_text`], with [`RemoteReport`], what this machine adds to the
//! remote cache's settings.
//!
//! Non-responsibilities: computing the report, which the library does; and writing it, which
//! the command does.

use core::fmt::Display;
use std::collections::BTreeSet;

use buildl::Doctor;
use buildl::buildl_core::{
    Attribution, Directory, Execution, RemoteSettings, Want, WantedSet, Workers,
};

use crate::remote_switches::Switch;

/// The spaces after the longest cell of a column.
const GAP: usize = 2;

/// Whether a build would find the token `buildl.toml` names.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TokenState {
    /// The `[remote]` table names no token.
    Unnamed,
    /// The token is named and a build would read it.
    Set,
    /// The token is named and a build would fail to read it.
    Missing,
}

impl TokenState {
    /// The word `doctor` prints for this state.
    const fn word(self) -> &'static str {
        match self {
            Self::Unnamed => "-",
            Self::Set => "set",
            Self::Missing => "not set",
        }
    }
}

/// What `doctor` says of the remote cache beyond what `buildl.toml` holds: what this machine
/// has, and so what no manifest can say.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RemoteReport {
    /// Whether the token the manifest names can be found.
    pub token: TokenState,
    /// How `BUILDL_REMOTE_UPLOAD` reads.
    pub upload: Switch,
    /// How `BUILDL_REMOTE_STRICT` reads.
    pub strict: Switch,
    /// How `BUILDL_REMOTE_EXECUTE` reads; `None` when it is not set.
    pub execute: Option<Switch>,
}

/// The text of `doctor`'s report, ending in a newline.
///
/// Every path is relative to the workspace root but the root itself. Each column of the wants
/// table is as wide as its longest cell, its head included, and two spaces, so the text is the
/// same on every run.
///
/// The remote cache follows the run settings: `remote: none` when `buildl.toml` has no
/// `[remote]` table, and otherwise a `remote` section of the table's `url`, `instance`, `ca`,
/// `header` and `timeout`, whether the token is set (`-` when none is named), `upload` and
/// `strict` as this machine's variables read in `remote`, `execute` as the table holds it and as
/// `BUILDL_REMOTE_EXECUTE` reads, then `jobs`, `queue_timeout`, `retries` and one line for each
/// platform property in name order, or `properties: none`. The token itself is never in the
/// text.
///
/// Under a want that plugins' targets are behind, one line for each chain reads
/// `    declared by plugin go@1.2.0 for //services/api:server`. When a plugin does not allow a want
/// of its targets, a `plugin violations` section ends the report with one line for each, worded
/// as the refusal of a build would word it; the command still succeeds.
pub(crate) fn doctor_text(doctor: &Doctor, remote: &RemoteReport) -> String {
    let checkup = doctor.checkup();
    let workspace = checkup.workspace();
    let ceiling = &workspace.ceiling;
    let mut lines = vec![
        format!("workspace  {}", doctor.root().display()),
        format!("approver   {}", workspace.approver),
        format!("execution  {}", execution(&workspace.execution)),
    ];
    lines.extend(remote_lines(workspace.remote.as_ref(), remote));
    lines.push("ceiling".to_owned());
    let entries = [
        ("proc.run", joined(&ceiling.run)),
        ("env.read", joined(&ceiling.env)),
        ("fs.read", directories(&ceiling.read)),
        ("fs.write", directories(&ceiling.write)),
    ];
    let width = column_width(entries.iter().map(|(key, _)| *key));
    lines.extend(
        entries
            .iter()
            .map(|(key, value)| format!("  {key:<width$}{value}")),
    );

    let wants = wants(
        checkup.wanted(),
        checkup.outside(),
        doctor.unapproved(),
        checkup.attribution(),
    );
    let rows: Vec<Row> = wants.iter().map(|(row, _)| row.clone()).collect();
    let head = [
        "wants".to_owned(),
        "ceiling".to_owned(),
        "approved".to_owned(),
    ];
    let first = column_width(column(&head, &rows, 0));
    let second = column_width(column(&head, &rows, 1));
    let table =
        |[want, allowed, approved]: &Row| format!("{want:<first$}{allowed:<second$}{approved}");
    lines.push(table(&head));
    for (row, attributed) in &wants {
        lines.push(table(row));
        lines.extend(attributed.iter().map(|line| format!("    {line}")));
    }
    if !checkup.plugin_violations().is_empty() {
        lines.push("plugin violations".to_owned());
        lines.extend(
            checkup
                .plugin_violations()
                .iter()
                .map(|violation| format!("  {}: {violation}", violation.site)),
        );
    }
    let mut text = lines.join("\n");
    text.push('\n');
    text
}

/// One row of the wants table: the want, what the ceiling says of it, and whether it is
/// approved.
type Row = [String; 3];

/// A row of the wants table and the lines saying which plugins are behind its want.
type Wanted = (Row, Vec<String>);

/// The rows of the wants table, in the order of `wanted`: programs, variables, directories,
/// then the network, each with its attribution lines.
fn wants(
    wanted: &WantedSet,
    outside: &WantedSet,
    unapproved: &WantedSet,
    attribution: &Attribution,
) -> Vec<Wanted> {
    let approved = |no: bool| if no { "no" } else { "yes" };
    let row = |want: String, refused: bool, no: bool| {
        if refused {
            [want, "REFUSED".to_owned(), "-".to_owned()]
        } else {
            [want, "allowed".to_owned(), approved(no).to_owned()]
        }
    };
    let mut rows = Vec::new();
    for program in &wanted.programs {
        rows.push((
            row(
                format!("  run {program}"),
                outside.programs.contains(program),
                unapproved.programs.contains(program),
            ),
            attribution.lines(&Want::Program(program.clone())),
        ));
    }
    for name in &wanted.env {
        rows.push((
            row(
                format!("  read {name}"),
                outside.env.contains(name),
                unapproved.env.contains(name),
            ),
            attribution.lines(&Want::Env(name.clone())),
        ));
    }
    for directory in &wanted.write {
        rows.push((
            row(
                format!("  write {}", path(directory)),
                outside.write.contains(directory),
                unapproved.write.contains(directory),
            ),
            Vec::new(),
        ));
    }
    for label in &wanted.network {
        rows.push((
            [
                format!("  network {label}"),
                "-".to_owned(),
                approved(unapproved.network.contains(label)).to_owned(),
            ],
            attribution.lines(&Want::Network(label.clone())),
        ));
    }
    rows
}

/// The cells of column `index`, the head's first.
fn column<'a>(head: &'a Row, rows: &'a [Row], index: usize) -> impl Iterator<Item = &'a str> {
    std::iter::once(head[index].as_str()).chain(rows.iter().map(move |row| row[index].as_str()))
}

/// The width of a column holding `cells`: its longest cell and the gap.
fn column_width<'a>(cells: impl Iterator<Item = &'a str>) -> usize {
    cells.map(|cell| cell.chars().count()).max().unwrap_or(0) + GAP
}

/// The execution settings as one line: `workers`, `timeout` and `strategy`.
fn execution(execution: &Execution) -> String {
    let per_core = if execution.workers == Workers::PerCore {
        " (one per core)"
    } else {
        ""
    };
    format!(
        "workers {}{per_core}, timeout {}, strategy {}",
        execution.workers, execution.timeout, execution.strategy
    )
}

/// The lines about the remote cache `settings` name, or the one line saying there is none.
fn remote_lines(settings: Option<&RemoteSettings>, remote: &RemoteReport) -> Vec<String> {
    let Some(settings) = settings else {
        return vec!["remote: none".to_owned()];
    };
    let or_dash = |value: Option<String>| value.unwrap_or_else(|| "-".to_owned());
    let entries = [
        ("url", settings.url().to_string()),
        (
            "instance",
            or_dash(settings.instance().map(ToString::to_string)),
        ),
        ("ca", or_dash(settings.ca().map(ToString::to_string))),
        ("header", settings.header().to_string()),
        ("timeout", settings.timeout().to_string()),
        ("token", remote.token.word().to_owned()),
        ("upload", remote.upload.to_string()),
        ("strict", remote.strict.to_string()),
        (
            "execute",
            execute(settings.execute(), remote.execute.as_ref()),
        ),
        ("jobs", settings.jobs().to_string()),
        ("queue_timeout", settings.queue_timeout().to_string()),
        ("retries", settings.retries().to_string()),
    ];
    let width = column_width(entries.iter().map(|(key, _)| *key));
    let mut lines = vec!["remote".to_owned()];
    lines.extend(
        entries
            .iter()
            .map(|(key, value)| format!("  {key:<width$}{value}")),
    );
    if settings.properties().is_empty() {
        lines.push("  properties: none".to_owned());
    } else {
        lines.extend(
            settings
                .properties()
                .iter()
                .map(|(name, value)| format!("  property {name} = {value:?}")),
        );
    }
    lines.push("  --remote-upload and --remote-strict turn either on for one run".to_owned());
    lines.push(
        "  --remote-execute and --no-remote-execute change execute, and --remote-jobs changes \
         jobs, for one run"
            .to_owned(),
    );
    lines
}

/// The `execute` value: what `buildl.toml` holds and how `BUILDL_REMOTE_EXECUTE` reads.
fn execute(manifest: bool, variable: Option<&Switch>) -> String {
    let manifest = if manifest { "on" } else { "off" };
    let variable = variable.map_or_else(|| "not set".to_owned(), ToString::to_string);
    format!("{manifest} in buildl.toml, BUILDL_REMOTE_EXECUTE {variable}")
}

/// The members of `set` joined by `, `, or `-` when there are none.
fn joined<T: Display>(set: &BTreeSet<T>) -> String {
    if set.is_empty() {
        return "-".to_owned();
    }
    set.iter()
        .map(ToString::to_string)
        .collect::<Vec<_>>()
        .join(", ")
}

/// The directories of `set` joined by `, `, the root written `.`; or `-` when there are none.
fn directories(set: &BTreeSet<Directory>) -> String {
    joined(&set.iter().map(path).collect())
}

/// `directory` as a path relative to the root: `.` for the root itself.
fn path(directory: &Directory) -> String {
    if directory.is_root() {
        ".".to_owned()
    } else {
        directory.to_string()
    }
}

#[cfg(test)]
mod tests {
    #![expect(
        clippy::unwrap_used,
        reason = "tests unwrap known-valid fixtures; a panic is the intended failure signal"
    )]

    use std::collections::BTreeSet;
    use std::num::NonZeroUsize;
    use std::path::PathBuf;

    use buildl::Doctor;
    use buildl::buildl_core::{
        ApproverMode, Attribution, Ceiling, Checkup, DeclarationSite, Directory, EnvName,
        Execution, HeaderName, HostPath, InstanceName, Isolation, Label, Origin,
        PlatformProperties, PlatformPropertyName, PluginChain, PluginName, PluginRef,
        PluginVersion, PluginViolation, Program, Provenance, RemoteJobs, RemoteSettings, RemoteUrl,
        RetryCount, Timeout, TokenSource, Want, WantedSet, Workers, Workspace,
    };

    use super::{RemoteReport, TokenState, doctor_text};
    use crate::remote_switches::Switch;

    fn programs(names: &[&str]) -> BTreeSet<Program> {
        names
            .iter()
            .map(|name| Program::parse(*name).unwrap())
            .collect()
    }

    fn env(names: &[&str]) -> BTreeSet<EnvName> {
        names
            .iter()
            .map(|name| EnvName::parse(*name).unwrap())
            .collect()
    }

    /// The directories of `paths`, `.` being the root.
    fn dirs(paths: &[&str]) -> BTreeSet<Directory> {
        paths
            .iter()
            .map(|path| match *path {
                "." => Directory::root(),
                path => Directory::parse(path).unwrap(),
            })
            .collect()
    }

    fn labels(raws: &[&str]) -> BTreeSet<Label> {
        raws.iter().map(|raw| Label::parse(raw).unwrap()).collect()
    }

    /// The workspace of the documented example: `go` and `protoc` to run, `HOME` and `PATH` to read,
    /// every file to read, `out` and `.buildl` to write, under `approver`.
    fn workspace(approver: ApproverMode, workers: Workers) -> Workspace {
        Workspace {
            out: Directory::parse("out").unwrap(),
            state: Directory::parse(".buildl").unwrap(),
            ceiling: Ceiling {
                run: programs(&["go", "protoc"]),
                env: env(&["HOME", "PATH"]),
                read: dirs(&["."]),
                write: dirs(&[".buildl", "out"]),
            },
            execution: Execution {
                workers,
                timeout: Timeout::parse("10m").unwrap(),
                strategy: Isolation::Sandbox,
            },
            approver,
            plugins: std::collections::BTreeMap::new(),
            remote: None,
        }
    }

    /// A report of [`workspace`] wanting `wanted`, of which `outside` is outside the ceiling
    /// and `unapproved` is not approved.
    fn report(
        workspace: Workspace,
        wanted: WantedSet,
        outside: WantedSet,
        unapproved: WantedSet,
    ) -> String {
        doctor_text(
            &Doctor::new(
                Checkup::new(
                    workspace,
                    wanted,
                    outside,
                    Attribution::default(),
                    Vec::new(),
                ),
                PathBuf::from("/path/to/myapp"),
                unapproved,
            ),
            &machine(),
        )
    }

    /// A machine whose token is not found and whose variables are not set.
    const fn machine() -> RemoteReport {
        RemoteReport {
            token: TokenState::Missing,
            upload: Switch::Off,
            strict: Switch::Off,
            execute: None,
        }
    }

    /// [`workspace`] with the remote cache `settings`.
    fn remote_workspace(settings: RemoteSettings) -> Workspace {
        Workspace {
            remote: Some(settings),
            ..workspace(ApproverMode::Manifest, Workers::PerCore)
        }
    }

    /// The text of a report of `workspace` on `machine`, with nothing wanted.
    fn report_on(workspace: Workspace, machine: &RemoteReport) -> String {
        doctor_text(
            &Doctor::new(
                Checkup::new(
                    workspace,
                    WantedSet::default(),
                    WantedSet::default(),
                    Attribution::default(),
                    Vec::new(),
                ),
                PathBuf::from("/path/to/myapp"),
                WantedSet::default(),
            ),
            machine,
        )
    }

    #[test]
    fn a_workspace_without_a_remote_says_none() {
        let text = report_on(
            workspace(ApproverMode::Manifest, Workers::PerCore),
            &machine(),
        );

        assert!(
            text.contains("strategy sandbox\nremote: none\nceiling\n"),
            "{text}"
        );
    }

    #[test]
    fn a_remote_section_lists_every_setting_and_the_machine() {
        let settings =
            RemoteSettings::builder(RemoteUrl::parse("grpcs://cache.example.com:443").unwrap())
                .instance(InstanceName::parse("ci").unwrap())
                .ca(HostPath::parse("certs/ca.pem").unwrap())
                .header(HeaderName::parse("x-cache-token").unwrap())
                .timeout(Timeout::parse("45s").unwrap())
                .token(TokenSource::Env(EnvName::parse("CACHE_TOKEN").unwrap()))
                .build()
                .unwrap();
        let machine = RemoteReport {
            token: TokenState::Set,
            upload: Switch::On,
            strict: Switch::Invalid("yes".to_owned()),
            execute: Some(Switch::On),
        };

        let text = report_on(remote_workspace(settings), &machine);

        assert!(
            text.contains(concat!(
                "strategy sandbox\n",
                "remote\n",
                "  url            grpcs://cache.example.com:443\n",
                "  instance       ci\n",
                "  ca             certs/ca.pem\n",
                "  header         x-cache-token\n",
                "  timeout        45s\n",
                "  token          set\n",
                "  upload         on\n",
                "  strict         invalid (\"yes\" is neither 1 nor 0)\n",
                "  execute        off in buildl.toml, BUILDL_REMOTE_EXECUTE on\n",
                "  jobs           128\n",
                "  queue_timeout  1h\n",
                "  retries        5\n",
                "  properties: none\n",
                "  --remote-upload and --remote-strict turn either on for one run\n",
                "  --remote-execute and --no-remote-execute change execute, and --remote-jobs ",
                "changes jobs, for one run\n",
                "ceiling\n",
            )),
            "{text}"
        );
        assert!(!text.contains("CACHE_TOKEN"), "{text}");
    }

    #[test]
    fn an_unnamed_instance_authority_and_token_show_a_dash() {
        let settings = RemoteSettings::builder(RemoteUrl::parse("grpc://127.0.0.1:9092").unwrap())
            .build()
            .unwrap();
        let machine = RemoteReport {
            token: TokenState::Unnamed,
            ..machine()
        };

        let text = report_on(remote_workspace(settings), &machine);

        assert!(
            text.contains(concat!(
                "  instance       -\n",
                "  ca             -\n",
                "  header         authorization\n",
                "  timeout        30s\n",
                "  token          -\n",
                "  upload         off\n",
                "  strict         off\n",
            )),
            "{text}"
        );
    }

    /// The settings of a cache that executes, with every execution setting stated.
    fn executing_settings(properties: &[(&str, &str)]) -> RemoteSettings {
        let properties = properties
            .iter()
            .map(|(name, value)| {
                (
                    PlatformPropertyName::parse(*name).unwrap(),
                    (*value).to_owned(),
                )
            })
            .collect();
        RemoteSettings::builder(RemoteUrl::parse("grpcs://cache.example.com").unwrap())
            .execute(true)
            .jobs(RemoteJobs::from_integer(16).unwrap())
            .queue_timeout(Timeout::parse("20m").unwrap())
            .retries(RetryCount::from_integer(0).unwrap())
            .properties(PlatformProperties::new(properties))
            .build()
            .unwrap()
    }

    #[test]
    fn the_remote_section_lists_the_execution_settings() {
        let text = report_on(
            remote_workspace(executing_settings(&[("pool", "large")])),
            &machine(),
        );

        assert!(
            text.contains(concat!(
                "  strict         off\n",
                "  execute        on in buildl.toml, BUILDL_REMOTE_EXECUTE not set\n",
                "  jobs           16\n",
                "  queue_timeout  20m\n",
                "  retries        0\n",
                "  property pool = \"large\"\n",
                "  --remote-upload and --remote-strict turn either on for one run\n",
                "  --remote-execute and --no-remote-execute change execute, and --remote-jobs ",
                "changes jobs, for one run\n",
                "ceiling\n",
            )),
            "{text}"
        );
    }

    #[test]
    fn the_execute_variable_is_shown_as_this_machine_sets_it() {
        let line = |execute: Option<Switch>| {
            let machine = RemoteReport {
                execute,
                ..machine()
            };
            report_on(remote_workspace(executing_settings(&[])), &machine)
        };

        let off = line(Some(Switch::Off));
        let on = line(Some(Switch::On));
        let unset = line(None);
        let invalid = line(Some(Switch::Invalid("yes".to_owned())));

        assert!(
            off.contains("  execute        on in buildl.toml, BUILDL_REMOTE_EXECUTE off\n"),
            "{off}"
        );
        assert!(
            on.contains("  execute        on in buildl.toml, BUILDL_REMOTE_EXECUTE on\n"),
            "{on}"
        );
        assert!(
            unset.contains("  execute        on in buildl.toml, BUILDL_REMOTE_EXECUTE not set\n"),
            "{unset}"
        );
        assert!(
            invalid.contains(concat!(
                "  execute        on in buildl.toml, ",
                "BUILDL_REMOTE_EXECUTE invalid (\"yes\" is neither 1 nor 0)\n",
            )),
            "{invalid}"
        );
    }

    #[test]
    fn properties_are_listed_in_name_order() {
        let text = report_on(
            remote_workspace(executing_settings(&[
                ("pool", "large"),
                ("Pool2", "linux"),
                ("arch", "x86 64"),
            ])),
            &machine(),
        );

        assert!(
            text.contains(concat!(
                "  retries        0\n",
                "  property Pool2 = \"linux\"\n",
                "  property arch = \"x86 64\"\n",
                "  property pool = \"large\"\n",
            )),
            "{text}"
        );
        assert!(!text.contains("properties: none"), "{text}");
    }

    #[test]
    fn no_properties_say_none() {
        let text = report_on(remote_workspace(executing_settings(&[])), &machine());

        assert!(
            text.contains("  retries        0\n  properties: none\n  --remote-upload"),
            "{text}"
        );
    }

    #[test]
    fn a_named_token_a_build_cannot_read_says_not_set() {
        let settings =
            RemoteSettings::builder(RemoteUrl::parse("grpcs://cache.example.com").unwrap())
                .token(TokenSource::Env(EnvName::parse("CACHE_TOKEN").unwrap()))
                .build()
                .unwrap();

        let text = report_on(remote_workspace(settings), &machine());

        assert!(text.contains("  token          not set\n"), "{text}");
    }

    #[test]
    fn a_full_report_matches_the_documented_layout() {
        let wanted = WantedSet {
            programs: programs(&["curl", "go"]),
            env: env(&["HOME"]),
            write: dirs(&["out"]),
            network: labels(&["//:fetch"]),
        };
        let outside = WantedSet {
            programs: programs(&["curl"]),
            ..WantedSet::default()
        };
        let unapproved = WantedSet {
            programs: programs(&["curl"]),
            write: dirs(&["out"]),
            network: labels(&["//:fetch"]),
            ..WantedSet::default()
        };

        let remote = Workspace {
            remote: Some(
                RemoteSettings::builder(RemoteUrl::parse("grpc://127.0.0.1:9092").unwrap())
                    .execute(true)
                    .build()
                    .unwrap(),
            ),
            ..workspace(ApproverMode::Interactive, Workers::PerCore)
        };

        let text = report(remote, wanted, outside, unapproved);

        assert_eq!(
            text,
            concat!(
                "workspace  /path/to/myapp\n",
                "approver   interactive\n",
                "execution  workers 0 (one per core), timeout 10m, strategy sandbox\n",
                "remote\n",
                "  url            grpc://127.0.0.1:9092\n",
                "  instance       -\n",
                "  ca             -\n",
                "  header         authorization\n",
                "  timeout        30s\n",
                "  token          not set\n",
                "  upload         off\n",
                "  strict         off\n",
                "  execute        on in buildl.toml, BUILDL_REMOTE_EXECUTE not set\n",
                "  jobs           128\n",
                "  queue_timeout  1h\n",
                "  retries        5\n",
                "  properties: none\n",
                "  --remote-upload and --remote-strict turn either on for one run\n",
                "  --remote-execute and --no-remote-execute change execute, and --remote-jobs ",
                "changes jobs, for one run\n",
                "ceiling\n",
                "  proc.run  go, protoc\n",
                "  env.read  HOME, PATH\n",
                "  fs.read   .\n",
                "  fs.write  .buildl, out\n",
                "wants               ceiling  approved\n",
                "  run curl          REFUSED  -\n",
                "  run go            allowed  yes\n",
                "  read HOME         allowed  yes\n",
                "  write out         allowed  no\n",
                "  network //:fetch  -        no\n",
            )
        );
    }

    fn go() -> PluginRef {
        PluginRef {
            name: PluginName::parse("go").unwrap(),
            version: PluginVersion::parse("1.2.0").unwrap(),
            run: programs(&["go"]),
            env: BTreeSet::new(),
        }
    }

    #[test]
    fn doctor_text_names_plugins_and_violations() {
        let wanted = WantedSet {
            programs: programs(&["curl", "go"]),
            ..WantedSet::default()
        };
        let chain = PluginChain::new(vec![go()]).unwrap();
        let app = Label::parse("//:app").unwrap();
        let mut attribution = Attribution::default();
        attribution.record(Want::Program(Program::parse("curl").unwrap()), &chain, &app);
        let violation = PluginViolation {
            want: Want::Program(Program::parse("curl").unwrap()),
            site: DeclarationSite {
                label: app,
                provenance: Provenance::new(PathBuf::from("build.lua"), Directory::root()),
                origin: Origin::plugins(vec![go()]).unwrap(),
            },
            plugin: go(),
            allowed: BTreeSet::from(["go".to_owned()]),
        };
        let checkup = Checkup::new(
            workspace(ApproverMode::Manifest, Workers::PerCore),
            wanted,
            WantedSet::default(),
            attribution,
            vec![violation],
        );

        let text = doctor_text(
            &Doctor::new(
                checkup,
                PathBuf::from("/path/to/myapp"),
                WantedSet::default(),
            ),
            &machine(),
        );

        assert!(
            text.ends_with(concat!(
                "wants       ceiling  approved\n",
                "  run curl  allowed  yes\n",
                "    declared by plugin go@1.2.0 for //:app\n",
                "  run go    allowed  yes\n",
                "plugin violations\n",
                "  build.lua: //:app (plugin go@1.2.0): program curl is outside plugin go@1.2.0 ",
                "(proc.run allows: go)\n",
            )),
            "{text}"
        );
    }

    #[test]
    fn an_empty_ceiling_list_shows_a_dash() {
        let mut workspace = workspace(ApproverMode::Manifest, Workers::PerCore);
        workspace.ceiling.run.clear();
        workspace.ceiling.env.clear();

        let text = report(
            workspace,
            WantedSet::default(),
            WantedSet::default(),
            WantedSet::default(),
        );

        assert!(text.contains("  proc.run  -\n"), "{text}");
        assert!(text.contains("  env.read  -\n"), "{text}");
    }

    #[test]
    fn a_refused_want_has_no_approval() {
        let wanted = WantedSet {
            env: env(&["TOKEN"]),
            ..WantedSet::default()
        };

        let text = report(
            workspace(ApproverMode::Deny, Workers::PerCore),
            wanted.clone(),
            wanted.clone(),
            wanted,
        );

        assert!(text.ends_with("  read TOKEN  REFUSED  -\n"), "{text}");
    }

    #[test]
    fn per_core_workers_say_so() {
        let per_core = report(
            workspace(ApproverMode::Manifest, Workers::PerCore),
            WantedSet::default(),
            WantedSet::default(),
            WantedSet::default(),
        );
        let fixed = report(
            workspace(
                ApproverMode::Manifest,
                Workers::Fixed(NonZeroUsize::new(4).unwrap()),
            ),
            WantedSet::default(),
            WantedSet::default(),
            WantedSet::default(),
        );

        assert!(
            per_core
                .contains("execution  workers 0 (one per core), timeout 10m, strategy sandbox\n"),
            "{per_core}"
        );
        assert!(
            fixed.contains("execution  workers 4, timeout 10m, strategy sandbox\n"),
            "{fixed}"
        );
    }
}