use std::collections::BTreeSet;
use std::fs;
use std::path::{Path, PathBuf};
use rig_harness_protocol::{Home, env};
use super::plugin_list::{PluginList, Source, parse_string};
use super::{Result, VERSION};
pub const PACKAGE: &str = "rig-harness-agent";
const LOCK: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.lock"));
pub enum RigSource {
Local(PathBuf),
Registry,
}
impl RigSource {
pub fn detect() -> Result<Self> {
if let Some(checkout) = std::env::var_os(env::SOURCE).filter(|path| !path.is_empty()) {
let checkout = std::path::absolute(PathBuf::from(checkout))?;
if !is_checkout(&checkout) {
return Err(format!(
"RIG_SOURCE={} is not a rig checkout: it has no crates/rig-harness/Cargo.toml",
checkout.display()
)
.into());
}
return Ok(Self::Local(checkout));
}
let installed_from = Path::new(env!("CARGO_MANIFEST_DIR"));
let cargo_home = std::env::var_os("CARGO_HOME")
.filter(|path| !path.is_empty())
.map(PathBuf::from)
.or_else(|| std::env::home_dir().map(|home| home.join(".cargo")));
let in_cargo_cache = cargo_home.is_some_and(|cargo| installed_from.starts_with(cargo));
Ok(if is_checkout(installed_from) && !in_cargo_cache {
Self::Local(installed_from.to_path_buf())
} else {
Self::Registry
})
}
}
fn is_checkout(path: &Path) -> bool {
path.join("crates/rig-harness/Cargo.toml").is_file()
}
pub const CORE_CRATES: [&str; 7] = [
"rig-core",
"rig-ecs",
"rig-harness",
"rig-harness-protocol",
"rig-http",
"rig-memory",
"rig-tools",
];
pub fn crate_dir(checkout: &Path, name: &str) -> Option<PathBuf> {
if name == "rig" {
return Some(checkout.to_path_buf());
}
["crates", "plugins"]
.into_iter()
.map(|folder| checkout.join(folder).join(name))
.find(|directory| directory.join("Cargo.toml").is_file())
}
pub fn rig_crates(list: &PluginList, source: &RigSource) -> BTreeSet<String> {
let mut used: BTreeSet<String> = CORE_CRATES.map(str::to_owned).into();
let packages = list.plugins.iter().map(|plugin| &plugin.package);
let RigSource::Local(checkout) = source else {
let listed = packages.filter(|package| package.source == Source::Rig);
used.extend(listed.map(|package| package.name.clone()));
return used;
};
let mut pending: Vec<String> = Vec::new();
for package in packages {
match &package.source {
Source::Rig => pending.push(package.name.clone()),
Source::Path(directory) => pending.extend(dependencies(directory)),
Source::Git { .. } | Source::Version(_) => {}
}
}
while let Some(name) = pending.pop() {
let Some(directory) = crate_dir(checkout, &name) else {
continue;
};
if used.insert(name) && directory.starts_with(checkout.join("plugins")) {
pending.extend(dependencies(&directory));
}
}
used
}
fn dependencies(directory: &Path) -> Vec<String> {
let Ok(manifest) = fs::read_to_string(directory.join("Cargo.toml")) else {
return Vec::new();
};
let mut names = Vec::new();
let mut in_dependencies = false;
for line in manifest.lines().map(str::trim) {
if let Some(header) = line
.strip_prefix('[')
.and_then(|line| line.strip_suffix(']'))
{
let header = header.trim();
in_dependencies = header == "dependencies"
|| (header.starts_with("target.") && header.ends_with(".dependencies"));
continue;
}
let Some((name, value)) = line.split_once('=') else {
continue;
};
if in_dependencies && !line.starts_with('#') && !value.contains("optional = true") {
names.push(name.trim().trim_matches('"').to_owned());
}
}
names
}
pub fn rig_patch(checkout: &Path, used: &BTreeSet<String>) -> String {
let mut text = String::from("[patch.crates-io]\n");
for name in used {
if let Some(directory) = crate_dir(checkout, name) {
text.push_str(&format!(
"{name} = {{ path = {} }}\n",
quoted_path(&directory)
));
}
}
text
}
pub fn rig_version(source: &RigSource) -> String {
let RigSource::Local(checkout) = source else {
return VERSION.to_owned();
};
fs::read_to_string(checkout.join("Cargo.toml"))
.ok()
.and_then(|manifest| manifest_string(&manifest, "workspace.package", "version"))
.unwrap_or_else(|| VERSION.to_owned())
}
pub fn manifest_string(manifest: &str, table: &str, key: &str) -> Option<String> {
let mut current = String::new();
for line in manifest.lines() {
let line = line.trim();
if let Some(header) = line
.strip_prefix('[')
.and_then(|line| line.strip_suffix(']'))
{
current = header.trim().to_owned();
continue;
}
if current != table {
continue;
}
let Some((name, value)) = line.split_once('=') else {
continue;
};
if name.trim() == key {
return parse_string(value.trim()).map(|(value, _)| value);
}
}
None
}
pub fn generate(home: &Home, list: &PluginList, source: &RigSource) -> Result<()> {
let project = home.project();
write_if_changed(&project.join("Cargo.toml"), &manifest(home, list, source)?)?;
write_if_changed(&project.join("src/main.rs"), &main_rs(home, list, source))?;
write_if_changed(&project.join(".cargo/config.toml"), &cargo_config(home))?;
let lock = project.join("Cargo.lock");
if !lock.exists() {
match source {
RigSource::Local(checkout) => {
fs::copy(checkout.join("Cargo.lock"), lock)?;
}
RigSource::Registry => fs::write(lock, LOCK)?,
}
}
Ok(())
}
fn manifest(home: &Home, list: &PluginList, source: &RigSource) -> Result<String> {
let mut text = format!(
"# Generated by rig {VERSION} from {}. `rig build` and /reload rewrite this file.\n\
[package]\n\
name = \"{PACKAGE}\"\n\
version = \"0.0.0\"\n\
edition = \"2024\"\n\
publish = false\n\
\n\
# Its own workspace, so a RIG_HOME inside another workspace still builds.\n\
[workspace]\n\
\n\
[dependencies]\n",
home.plugins_toml().display()
);
text.push_str(&format!(
"rig-harness = {{ {} }}\n",
rig_source(source, "rig-harness")?
));
let mut listed = BTreeSet::new();
for package in list.plugins.iter().map(|plugin| &plugin.package) {
if !listed.insert(package.name.as_str()) {
continue;
}
let source = match &package.source {
Source::Path(path) => format!("path = {}", quoted_path(path)),
Source::Git { url, branch, rev } => {
let mut source = format!("git = {}", quoted(url));
if let Some(branch) = branch {
source.push_str(&format!(", branch = {}", quoted(branch)));
}
if let Some(rev) = rev {
source.push_str(&format!(", rev = {}", quoted(rev)));
}
source
}
Source::Version(version) => format!("version = {}", quoted(version)),
Source::Rig => rig_source(source, &package.name)?,
};
text.push_str(&format!("{} = {{ {source} }}\n", package.name));
}
if let RigSource::Local(checkout) = source {
text.push('\n');
text.push_str(&rig_patch(checkout, &rig_crates(list, source)));
}
text.push_str(&profile(list, source));
Ok(text)
}
fn profile(list: &PluginList, source: &RigSource) -> String {
let mut text = String::from(
"\n[profile.dev]\ndebug = \"line-tables-only\"\n\
\n[profile.dev.package.\"*\"]\nopt-level = 3\ndebug-assertions = false\n\
overflow-checks = false\n",
);
let mut edited: BTreeSet<String> = match source {
RigSource::Local(_) => rig_crates(list, source),
RigSource::Registry => BTreeSet::new(),
};
let packages = list.plugins.iter().map(|plugin| &plugin.package);
edited.extend(
packages
.filter(|package| matches!(package.source, Source::Path(_) | Source::Git { .. }))
.map(|package| package.name.clone()),
);
for name in edited {
text.push_str(&format!("\n[profile.dev.package.{name}]\nopt-level = 1\n"));
}
text
}
fn rig_source(source: &RigSource, name: &str) -> Result<String> {
Ok(match source {
RigSource::Local(checkout) => {
let directory = crate_dir(checkout, name).ok_or_else(|| {
format!(
"plugins.toml lists the crate `{name}` without a source, so as one of rig's \
own crates, but the rig checkout {} has no crates/{name} or plugins/{name}; \
give it `path`, `git` or `version` if it comes from elsewhere",
checkout.display()
)
})?;
format!("path = {}", quoted_path(&directory))
}
RigSource::Registry => format!("version = \"={VERSION}\""),
})
}
fn rig_origin(source: &RigSource, name: &str) -> String {
match source {
RigSource::Local(checkout) => crate_dir(checkout, name)
.map(|directory| format!("path {}", directory.display()))
.unwrap_or_default(),
RigSource::Registry => format!("version {VERSION}"),
}
}
fn main_rs(home: &Home, list: &PluginList, source: &RigSource) -> String {
let mut text = format!(
"// Generated by rig {VERSION} from {}. /reload rewrites this file.\n\
fn main() -> rig_harness::AppExit {{\n \
let mut app = rig_harness::App::new();\n \
// A failing system, observer or command from a plugin is logged.\n \
app.set_error_handler(rig_harness::error::warn);\n \
// Bevy's base and the headless loop come first, so the agent runs on\n \
// their clock and a windowing plugin listed below can replace the loop.\n \
app.add_plugins((rig_harness::HeadlessPlugins, rig_harness::RigHarnessPlugins));\n",
home.plugins_toml().display(),
);
for plugin in &list.plugins {
let package = &plugin.package;
let krate = package.name.as_str();
let from = match &package.source {
Source::Rig => rig_origin(source, krate),
other => other.to_string(),
};
text.push_str(&format!(
" rig_harness::load::<{}>(&mut app, {krate:?}, {from:?});\n",
plugin.type_path
));
}
text.push_str(
" // A debug build warns at start of agent-loop systems left unordered.\n \
#[cfg(debug_assertions)]\n \
rig_harness::check_stages_at_start(&mut app);\n",
);
text.push_str(" rig_harness::run(app)\n}\n");
text
}
fn cargo_config(home: &Home) -> String {
format!(
"# Generated by rig {VERSION}.\n[build]\ntarget-dir = {}\n",
quoted_path(&home.target())
)
}
pub fn write_if_changed(path: &Path, contents: &str) -> Result<()> {
if fs::read_to_string(path).is_ok_and(|current| current == contents) {
return Ok(());
}
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(path, contents)?;
Ok(())
}
pub fn quoted_path(path: &Path) -> String {
quoted(&path.to_string_lossy())
}
pub fn quoted(text: &str) -> String {
let mut quoted = String::from("\"");
for c in text.chars() {
match c {
'"' => quoted.push_str("\\\""),
'\\' => quoted.push_str("\\\\"),
c if c.is_control() => quoted.push_str(&format!("\\u{:04X}", u32::from(c))),
c => quoted.push(c),
}
}
quoted.push('"');
quoted
}
#[cfg(test)]
mod tests;