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;
const GAP: usize = 2;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TokenState {
Unnamed,
Set,
Missing,
}
impl TokenState {
const fn word(self) -> &'static str {
match self {
Self::Unnamed => "-",
Self::Set => "set",
Self::Missing => "not set",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RemoteReport {
pub token: TokenState,
pub upload: Switch,
pub strict: Switch,
pub execute: Option<Switch>,
}
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)),
("env.unkeyed", joined(&ceiling.unkeyed)),
("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
}
type Row = [String; 3];
type Wanted = (Row, Vec<String>);
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 name in &wanted.unkeyed {
rows.push((
row(
format!(" read {name} unkeyed"),
outside.unkeyed.contains(name),
unapproved.unkeyed.contains(name),
),
attribution.lines(&Want::Unkeyed(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
}
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()))
}
fn column_width<'a>(cells: impl Iterator<Item = &'a str>) -> usize {
cells.map(|cell| cell.chars().count()).max().unwrap_or(0) + GAP
}
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
)
}
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
}
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}")
}
fn joined<T: Display>(set: &BTreeSet<T>) -> String {
if set.is_empty() {
return "-".to_owned();
}
set.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(", ")
}
fn directories(set: &BTreeSet<Directory>) -> String {
joined(&set.iter().map(path).collect())
}
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()
}
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()
}
fn workspace(approver: ApproverMode, workers: Workers) -> Workspace {
Workspace {
out: Directory::parse("out").unwrap(),
state: Directory::parse(".buildl").unwrap(),
ceiling: Ceiling {
unkeyed: BTreeSet::new(),
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,
}
}
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(),
)
}
const fn machine() -> RemoteReport {
RemoteReport {
token: TokenState::Missing,
upload: Switch::Off,
strict: Switch::Off,
execute: None,
}
}
fn remote_workspace(settings: RemoteSettings) -> Workspace {
Workspace {
remote: Some(settings),
..workspace(ApproverMode::Manifest, Workers::PerCore)
}
}
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}"
);
}
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"]),
unkeyed: BTreeSet::new(),
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",
" env.unkeyed -\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 {
unkeyed: BTreeSet::new(),
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 doctor_prints_env_unkeyed() {
let mut workspace = workspace(ApproverMode::Manifest, Workers::PerCore);
workspace.ceiling.unkeyed = env(&["PATH"]);
let wanted = WantedSet {
unkeyed: env(&["HOME", "PATH"]),
..WantedSet::default()
};
let outside = WantedSet {
unkeyed: env(&["HOME"]),
..WantedSet::default()
};
let unapproved = WantedSet {
unkeyed: env(&["PATH"]),
..WantedSet::default()
};
let chain = PluginChain::new(vec![go()]).unwrap();
let mut attribution = Attribution::default();
attribution.record(
Want::Unkeyed(EnvName::parse("PATH").unwrap()),
&chain,
&Label::parse("//:app").unwrap(),
);
let text = doctor_text(
&Doctor::new(
Checkup::new(workspace, wanted, outside, attribution, Vec::new()),
PathBuf::from("/path/to/myapp"),
unapproved,
),
&machine(),
);
assert!(
text.contains(concat!(
"ceiling\n",
" proc.run go, protoc\n",
" env.read HOME, PATH\n",
" env.unkeyed PATH\n",
" fs.read .\n",
)),
"{text}"
);
assert!(
text.ends_with(concat!(
"wants ceiling approved\n",
" read HOME unkeyed REFUSED -\n",
" read PATH unkeyed allowed no\n",
" declared by plugin go@1.2.0 for //:app\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}"
);
}
}