use std::collections::BTreeSet;
use std::ffi::OsStr;
use std::fmt;
use std::fs::{self, File};
use std::io::{IsTerminal, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, ExitStatus, Stdio};
use std::time::{Duration, Instant, UNIX_EPOCH};
use rig_harness_protocol::{
AgentDescription, Home, SessionId, env, first_errors, secret_variables,
};
use super::plugin_list::PluginList;
use super::project::{self, PACKAGE, RigSource};
use super::{BEVY_VERSION, Result, locks};
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Staging {
Always,
OnlyNew,
Never,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildOutput {
Live,
LogOnly,
}
const ERROR_LINES: usize = 40;
#[derive(Debug)]
pub struct BuildFailure {
pub reason: String,
pub errors: Vec<String>,
pub log: PathBuf,
}
impl BuildFailure {
pub fn details(&self) -> String {
std::iter::once(&self.reason)
.chain(&self.errors)
.map(String::as_str)
.collect::<Vec<_>>()
.join("\n")
}
pub fn told(&self, output: BuildOutput) -> String {
match output {
BuildOutput::Live => self.to_string(),
BuildOutput::LogOnly => {
format!("{}\n(whole output: {})", self.details(), self.log.display())
}
}
}
}
impl fmt::Display for BuildFailure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.reason)?;
if let Some(first) = self.errors.first()
&& !self.reason.contains(first.as_str())
{
write!(f, ": {first}")?;
}
write!(f, " (whole output: {})", self.log.display())
}
}
impl std::error::Error for BuildFailure {}
pub fn compile(
home: &Home,
staged: &Path,
staging: Staging,
output: BuildOutput,
) -> std::result::Result<(), BuildFailure> {
let mut log = BuildLog::create(home, output, Box::new(std::io::stderr()));
match compile_logged(home, staged, staging, &mut log) {
Ok(()) => {
log.record("build succeeded");
Ok(())
}
Err(failure) => Err(log.fail(failure.to_string())),
}
}
fn compile_logged(home: &Home, staged: &Path, staging: Staging, log: &mut BuildLog) -> Result<()> {
let list = PluginList::load(&home.plugins_toml())?;
let source = RigSource::detect()?;
project::generate(home, &list, &source)?;
log.say("Compiling the agent…");
let mut command = cargo(home);
command.args(["build", "--package", PACKAGE]);
log.erase = cfg!(unix) && log.output == BuildOutput::Live && show_progress(&mut command);
let status = log.run(command)?;
let lock = fs::read(home.project().join("Cargo.lock")).ok();
let checked = home.project().join("Cargo.lock.checked");
if !status.success() || lock.is_none() || lock != fs::read(&checked).ok() {
log.say("Resolving dependencies…");
let rig_crates = project::rig_crates(&list, &source);
check_bevy(
home,
&list,
&rig_crates,
&project::rig_version(&source),
log,
)?;
if let Some(lock) = lock {
fs::write(&checked, lock).ok();
}
}
if !status.success() {
return Err(format!("cargo could not build the agent ({status})").into());
}
stage(home, staged, staging)
}
pub fn build(home: &Home) -> Result<()> {
let _lock = locks::hold_build_lock(home, BuildOutput::Live)?;
let staged = match SessionId::from_env()? {
Some(session) => home.staged_for(&session),
None => home.staged(),
};
Ok(compile(home, &staged, Staging::Always, BuildOutput::Live)?)
}
pub fn check(home: &Home) -> Result<AgentDescription> {
let _lock = locks::hold_build_lock(home, BuildOutput::Live)?;
compile(home, &home.staged(), Staging::Never, BuildOutput::Live)?;
described(home, &artifact(home))
}
fn artifact(home: &Home) -> PathBuf {
home.target()
.join("debug")
.join(format!("{PACKAGE}{}", std::env::consts::EXE_SUFFIX))
}
pub fn child(program: impl AsRef<OsStr>) -> Command {
let mut command = Command::new(program);
for secret in secret_variables() {
command.env_remove(secret);
}
command
}
fn cargo(home: &Home) -> Command {
let mut command = child("cargo");
command
.current_dir(home.project())
.env_remove("CARGO_TARGET_DIR")
.env("CARGO_TERM_COLOR", "never")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::piped());
command
}
fn show_progress(command: &mut Command) -> bool {
if std::io::stderr().is_terminal()
&& std::env::var_os("CARGO_TERM_PROGRESS_WHEN").is_none()
&& let Some(width) = terminal_width()
{
command
.env("CARGO_TERM_PROGRESS_WHEN", "always")
.env("CARGO_TERM_PROGRESS_WIDTH", width.to_string());
return true;
}
false
}
fn terminal_width() -> Option<u16> {
if let Some(columns) = std::env::var("COLUMNS")
.ok()
.and_then(|columns| columns.parse().ok())
{
return Some(columns);
}
let tty = File::open("/dev/tty").ok()?;
let output = child("stty")
.arg("size")
.stdin(tty)
.stderr(Stdio::null())
.output()
.ok()?;
String::from_utf8_lossy(&output.stdout)
.split_whitespace()
.nth(1)?
.parse()
.ok()
}
struct BuildLog {
path: PathBuf,
file: Option<File>,
lines: Vec<String>,
output: BuildOutput,
shown: Box<dyn Write>,
announced: bool,
erase: bool,
after_cr: bool,
}
impl BuildLog {
fn create(home: &Home, output: BuildOutput, shown: Box<dyn Write>) -> Self {
let path = home.build_log();
let file = fs::create_dir_all(home.root())
.and_then(|()| File::create(&path))
.inspect_err(|failure| {
eprintln!("warning: could not write {}: {failure}", path.display());
})
.ok();
Self {
path,
file,
lines: Vec::new(),
output,
shown,
announced: false,
erase: false,
after_cr: false,
}
}
fn say(&mut self, line: &str) {
if self.output == BuildOutput::Live {
writeln!(self.shown, "{line}").ok();
}
self.record(line);
}
fn record(&mut self, line: &str) {
if let Some(file) = &mut self.file
&& writeln!(file, "{line}").is_err()
{
self.file = None;
}
self.lines.push(line.to_owned());
}
fn run(&mut self, mut command: Command) -> Result<ExitStatus> {
let mut child = command.spawn()?;
self.pass_on(&mut child);
Ok(child.wait()?)
}
fn pass_on(&mut self, child: &mut Child) {
let Some(mut stderr) = child.stderr.take() else {
return;
};
let mut buffer = [0_u8; 8192];
let mut segment: Vec<u8> = Vec::new();
loop {
let read = match stderr.read(&mut buffer) {
Ok(0) | Err(_) => break,
Ok(read) => read,
};
let chunk = buffer.get(..read).unwrap_or_default();
if self.output == BuildOutput::Live {
self.show(chunk);
}
for &byte in chunk {
if byte == b'\r' || byte == b'\n' {
self.record_segment(&segment);
segment.clear();
} else {
segment.push(byte);
}
}
}
self.record_segment(&segment);
}
fn show(&mut self, chunk: &[u8]) {
let mut start = 0;
for (at, &byte) in chunk.iter().enumerate() {
if std::mem::take(&mut self.after_cr) && byte != b'\n' {
let before = chunk.get(start..at).unwrap_or_default();
self.shown.write_all(before).ok();
self.shown.write_all(b"\x1b[K").ok();
start = at;
}
self.after_cr = self.erase && byte == b'\r';
}
self.shown
.write_all(chunk.get(start..).unwrap_or_default())
.ok();
self.shown.flush().ok();
}
fn record_segment(&mut self, segment: &[u8]) {
let line = String::from_utf8_lossy(segment);
let line = line.trim_end();
if line.trim().is_empty() || line.trim_start().starts_with("Building [") {
return;
}
self.announce(line);
self.record(line);
}
fn announce(&mut self, line: &str) {
let working = ["Updating ", "Downloading ", "Compiling ", "Blocking "];
let line = line.trim_start();
if self.output == BuildOutput::LogOnly
&& !self.announced
&& working.iter().any(|word| line.starts_with(word))
{
self.announced = true;
let log = self.path.display();
writeln!(self.shown, "rig: building the agent (output in {log})…").ok();
}
}
fn fail(mut self, reason: String) -> BuildFailure {
let errors = first_errors(self.lines.iter().map(String::as_str), ERROR_LINES)
.into_iter()
.map(str::to_owned)
.collect();
self.record(&format!("build failed: {reason}"));
BuildFailure {
reason,
errors,
log: self.path,
}
}
}
fn stage(home: &Home, staged: &Path, staging: Staging) -> Result<()> {
let artifact = artifact(home);
let built = stamp(&artifact)?;
if let Err(why) = described(home, &artifact) {
if staging != Staging::Never {
fs::write(home.rejected(), &built)?;
}
return Err(format!("the new build does not start: {why}").into());
}
if staging == Staging::Never {
return Ok(());
}
let shared = home.staged();
if stamp(&shared).is_ok_and(|stamp| stamp != built) {
fs::remove_file(&shared)?;
}
let known = [home.good(), shared]
.iter()
.any(|binary| stamp(binary).is_ok_and(|stamp| stamp == built))
|| fs::read_to_string(home.rejected()).is_ok_and(|rejected| rejected == built);
if staging == Staging::OnlyNew && known {
return Ok(());
}
let temporary = home.bin().join("staged.tmp");
fs::create_dir_all(home.bin())?;
fs::copy(&artifact, &temporary)?;
File::options()
.write(true)
.open(&temporary)?
.set_modified(fs::metadata(&artifact)?.modified()?)?;
fs::rename(&temporary, staged)?;
prune_described(home);
Ok(())
}
fn prune_described(home: &Home) {
let stamps: BTreeSet<String> = fs::read_dir(home.bin())
.into_iter()
.flatten()
.flatten()
.filter_map(|entry| stamp(&entry.path()).ok())
.map(|stamp| home.described(&stamp))
.filter_map(|report| Some(report.file_name()?.to_owned()))
.map(|name| name.to_string_lossy().into_owned())
.collect();
let reports = home.described("-");
let Some(directory) = reports.parent() else {
return;
};
for entry in fs::read_dir(directory).into_iter().flatten().flatten() {
if !stamps.contains(&*entry.file_name().to_string_lossy()) {
fs::remove_file(entry.path()).ok();
}
}
}
const DESCRIBE_TIMEOUT: Duration = Duration::from_secs(10);
pub fn described(home: &Home, binary: &Path) -> Result<AgentDescription> {
if let Some(report) = good_report(home, binary) {
return Ok(report);
}
let kept = home.described(&stamp(binary)?);
let text = describe(home, binary)?;
let parent = kept.parent().ok_or("no directory for build reports")?;
fs::create_dir_all(parent)?;
let written = parent.join(format!(".{}.tmp", std::process::id()));
fs::write(&written, &text)?;
fs::rename(&written, &kept)?;
Ok(AgentDescription::parse(&text))
}
pub fn good_report(home: &Home, binary: &Path) -> Option<AgentDescription> {
let text = fs::read_to_string(home.described(&stamp(binary).ok()?)).ok()?;
Some(AgentDescription::parse(&text))
}
fn describe(home: &Home, binary: &Path) -> Result<String> {
let run = home.run(std::process::id());
let scratch = run.path().join("describe");
fs::remove_dir_all(&scratch).ok();
let scratch_home = scratch.join("home");
fs::create_dir_all(&scratch_home)?;
let report = scratch.join("report");
let mut command = child(binary);
command
.env(env::DESCRIBE, &report)
.env(env::HOME, &scratch_home)
.current_dir(&scratch_home)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::piped());
for name in env::AGENT_ONLY.iter().chain(&[env::LAUNCHER]) {
command.env_remove(name);
}
let result = wait_described(command.spawn()?, &report, DESCRIBE_TIMEOUT);
fs::remove_dir_all(&scratch).ok();
fs::remove_dir(run.path()).ok();
result
}
fn wait_described(mut child: Child, report: &Path, timeout: Duration) -> Result<String> {
let errors = child.stderr.take();
let errors = std::thread::spawn(move || {
let mut text = String::new();
if let Some(mut errors) = errors {
errors.read_to_string(&mut text).ok();
}
text
});
let deadline = Instant::now() + timeout;
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if Instant::now() > deadline {
child.kill().ok();
child.wait().ok();
return Err(format!(
"it did not describe itself within {} s",
timeout.as_secs_f32()
)
.into());
}
std::thread::sleep(Duration::from_millis(20));
};
let errors = errors.join().unwrap_or_default();
if !status.success() {
let said = errors.trim();
return Err(if said.is_empty() {
format!("describing it failed ({status})").into()
} else {
said.to_owned().into()
});
}
Ok(fs::read_to_string(report).unwrap_or_default())
}
pub fn reject(home: &Home, trial: &Path) -> Result<()> {
fs::write(home.rejected(), stamp(trial)?)?;
Ok(())
}
fn stamp(binary: &Path) -> Result<String> {
let metadata = fs::metadata(binary)?;
let modified = metadata
.modified()?
.duration_since(UNIX_EPOCH)
.map(|since| since.as_nanos())
.unwrap_or_default();
Ok(format!("{modified} {}\n", metadata.len()))
}
fn check_bevy(
home: &Home,
list: &PluginList,
rig_crates: &BTreeSet<String>,
rig_version: &str,
log: &mut BuildLog,
) -> Result<()> {
let packages = tree(home, &[], log)?;
check_rig(&packages, rig_crates, rig_version)?;
let Some((bevy, version)) = packages.iter().find_map(|line| {
let (name, version) = package(line)?;
(["bevy_app", "bevy_ecs"].contains(&name) && version != BEVY_VERSION)
.then_some((name, version))
}) else {
return Ok(());
};
let dependents = tree(home, &["--invert", &format!("{bevy}@{version}")], log)?;
let culprit = list
.plugins
.iter()
.map(|plugin| &plugin.package)
.find(|plugin| {
dependents
.iter()
.any(|line| package(line).is_some_and(|(name, _)| name == plugin.name))
});
Err(match culprit {
Some(plugin) => format!(
"plugin `{name}` uses Bevy {version}, but this rig agent is built on Bevy \
{BEVY_VERSION}. A Bevy plugin only works with the exact Bevy version of its app. \
Change {name}'s bevy dependencies to `={BEVY_VERSION}` (with default-features = \
false), or remove it from plugins.toml.",
name = plugin.name
),
None => format!(
"the agent project pulls in Bevy {version}, but this rig agent is built on Bevy \
{BEVY_VERSION}. Every Bevy crate must use exactly {BEVY_VERSION}."
),
}
.into())
}
fn check_rig(packages: &[String], rig_crates: &BTreeSet<String>, rig_version: &str) -> Result<()> {
for name in rig_crates {
let mut copies: Vec<&str> = packages
.iter()
.map(|line| line.trim_end_matches(" (*)"))
.filter(|line| package(line).is_some_and(|(package, _)| package == name.as_str()))
.collect();
copies.sort_unstable();
copies.dedup();
if let [first, second, ..] = copies.as_slice() {
return Err(format!(
"the agent project has two copies of `{name}`: {first} and {second}. A plugin \
must use the agent's rig crates: depend on `{name} = \"{rig_version}\"` (a \
version, not a path or git source); with RIG_SOURCE the agent project patches \
that version to the checkout. `rig plugin new` writes it so."
)
.into());
}
}
Ok(())
}
fn tree(home: &Home, args: &[&str], log: &mut BuildLog) -> Result<Vec<String>> {
let mut child = cargo(home)
.args(["tree", "--prefix", "none", "--format", "{p}"])
.args(args)
.stdout(Stdio::piped())
.spawn()?;
let out = child.stdout.take();
let reader = std::thread::spawn(move || {
let mut text = String::new();
if let Some(mut out) = out {
out.read_to_string(&mut text).ok();
}
text
});
log.pass_on(&mut child);
let stdout = reader
.join()
.map_err(|_| "reading cargo tree's output failed")?;
let status = child.wait()?;
if !status.success() {
return Err("cargo could not resolve the agent project's dependencies".into());
}
Ok(stdout.lines().map(str::to_owned).collect())
}
fn package(line: &str) -> Option<(&str, &str)> {
let mut words = line.split_whitespace();
let name = words.next()?;
let version = words.next()?.strip_prefix('v')?;
Some((name, version))
}
#[cfg(all(test, unix))]
mod tests;