use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use super::Result;
use super::project::PACKAGE;
pub(super) const TEMPLATE: &str = include_str!("plugins.toml");
pub struct PluginList {
pub plugins: Vec<PluginEntry>,
}
pub struct PluginEntry {
pub type_path: String,
pub package: Package,
}
pub struct Package {
pub name: String,
pub source: Source,
}
#[derive(PartialEq, Eq, Debug)]
pub enum Source {
Path(PathBuf),
Git {
url: String,
branch: Option<String>,
rev: Option<String>,
},
Version(String),
Rig,
}
impl fmt::Display for Source {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Path(path) => write!(f, "path {}", path.display()),
Self::Git { url, branch, rev } => {
write!(f, "git {url}")?;
if let Some(branch) = branch {
write!(f, ", branch {branch}")?;
}
if let Some(rev) = rev {
write!(f, ", rev {rev}")?;
}
Ok(())
}
Self::Version(version) => write!(f, "version {version}"),
Self::Rig => write!(f, "rig"),
}
}
}
impl PluginList {
pub fn load(path: &Path) -> Result<Self> {
let text = match fs::read_to_string(path) {
Ok(text) => text,
Err(failure) if failure.kind() == ErrorKind::NotFound => {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(path, TEMPLATE)?;
TEMPLATE.to_owned()
}
Err(failure) => return Err(format!("{}: {failure}", path.display()).into()),
};
parse_file(path, &text)
}
}
fn parse_file(path: &Path, text: &str) -> Result<PluginList> {
let base = path.parent().unwrap_or(Path::new("."));
parse(text, base).map_err(|failure| format!("{}: {failure}", path.display()).into())
}
pub fn append(
path: &Path,
entry: &str,
check: impl FnOnce(&PluginList) -> Result<()>,
) -> Result<PluginList> {
PluginList::load(path)?;
let mut text = fs::read_to_string(path)?;
if !text.is_empty() && !text.ends_with('\n') {
text.push('\n');
}
text.push('\n');
text.push_str(entry);
let list = parse_file(path, &text)?;
check(&list).map_err(|failure| format!("{}: {failure}", path.display()))?;
fs::write(path, text)?;
Ok(list)
}
pub fn remove(path: &Path, type_path: &str) -> Result<()> {
let text =
fs::read_to_string(path).map_err(|failure| format!("{}: {failure}", path.display()))?;
let base = path.parent().unwrap_or(Path::new("."));
let kept = without_table(&text, type_path, base)
.map_err(|failure| format!("{}: {failure}", path.display()))?;
parse_file(path, &kept)?;
fs::write(path, kept)?;
Ok(())
}
fn without_table(text: &str, type_path: &str, base: &Path) -> Result<String> {
let list = parse(text, base)?;
let Some(index) = list
.plugins
.iter()
.position(|plugin| plugin.type_path == type_path)
else {
return Err(format!("`{type_path}` is not listed").into());
};
let lines: Vec<&str> = text.lines().collect();
let headers: Vec<usize> = lines
.iter()
.enumerate()
.filter(|(_, line)| without_comment(line).trim() == "[[plugin]]")
.map(|(number, _)| number)
.collect();
let start = headers
.get(index)
.copied()
.ok_or("the table is not found")?;
let mut end = headers.get(index + 1).copied().unwrap_or(lines.len());
while end > start + 1
&& lines
.get(end - 1)
.is_some_and(|line| without_comment(line).trim().is_empty())
{
end -= 1;
}
let mut from = start;
while from > 0
&& lines
.get(from - 1)
.is_some_and(|line| line.trim_start().starts_with('#'))
{
from -= 1;
}
let mut kept: Vec<&str> = lines.get(..from).unwrap_or_default().to_vec();
kept.extend(lines.get(end..).unwrap_or_default());
if kept.get(from).is_some_and(|line| line.trim().is_empty())
&& from
.checked_sub(1)
.and_then(|before| kept.get(before))
.is_some_and(|line| line.trim().is_empty())
{
kept.remove(from);
}
let mut kept = kept.join("\n");
kept.push('\n');
Ok(kept)
}
pub struct Listed {
pub entry: PluginEntry,
pub enabled: bool,
pub description: String,
lines: std::ops::Range<usize>,
}
const KEYS: [&str; 7] = ["plugin", "crate", "path", "git", "branch", "rev", "version"];
pub fn listed(path: &Path) -> Result<Vec<Listed>> {
PluginList::load(path)?;
let text = fs::read_to_string(path)?;
let base = path.parent().unwrap_or(Path::new("."));
entries(&text, base).map_err(|failure| format!("{}: {failure}", path.display()).into())
}
pub fn set_enabled(path: &Path, type_path: &str, enabled: bool) -> Result<bool> {
let text =
fs::read_to_string(path).map_err(|failure| format!("{}: {failure}", path.display()))?;
let base = path.parent().unwrap_or(Path::new("."));
let toggled = toggled(&text, type_path, enabled, base)
.map_err(|failure| format!("{}: {failure}", path.display()))?;
let Some(toggled) = toggled else {
return Ok(false);
};
fs::write(path, toggled)?;
Ok(true)
}
fn toggled(text: &str, type_path: &str, enabled: bool, base: &Path) -> Result<Option<String>> {
let listed = entries(text, base)?;
let of_type = |state: bool| {
listed
.iter()
.find(|listed| listed.entry.type_path == type_path && listed.enabled == state)
};
if of_type(enabled).is_some() {
return Ok(None);
}
let Some(entry) = of_type(!enabled) else {
return Err(format!(
"`{type_path}` is not listed; `rig plugin add` adds it, and `rig plugin list` \
shows what is"
)
.into());
};
let mut toggled = String::with_capacity(text.len() + 32);
for (number, line) in text.split_inclusive('\n').enumerate() {
match (entry.lines.contains(&number), enabled) {
(false, _) => toggled.push_str(line),
(true, true) => toggled.push_str(&uncommented(line)),
(true, false) => {
toggled.push_str("# ");
toggled.push_str(line);
}
}
}
let others = |text: &str| -> Result<Vec<String>> {
Ok(parse(text, base)?
.plugins
.into_iter()
.filter(|plugin| plugin.type_path != type_path)
.map(|plugin| {
format!(
"{} {} {}",
plugin.type_path, plugin.package.name, plugin.package.source
)
})
.collect())
};
let now = parse(&toggled, base)?;
if others(&toggled)? != others(text)?
|| now
.plugins
.iter()
.any(|plugin| plugin.type_path == type_path)
!= enabled
{
return Err(format!(
"`{type_path}`'s entry is laid out so that toggling it would change other entries; \
edit it by hand"
)
.into());
}
Ok(Some(toggled))
}
fn entries(text: &str, base: &Path) -> Result<Vec<Listed>> {
let active = parse(text, base)?.plugins;
let mut active = active.into_iter();
let lines: Vec<&str> = text.lines().collect();
let mut listed = Vec::new();
for (number, line) in lines.iter().enumerate() {
let after = lines.get(number + 1..).unwrap_or_default();
let (entry, keys, enabled) = if without_comment(line).trim() == "[[plugin]]" {
let keys = after
.iter()
.take_while(|line| {
let line = without_comment(line).trim();
!line.is_empty() && line != "[[plugin]]"
})
.count();
let Some(entry) = active.next() else {
break;
};
(entry, keys, true)
} else if commented(line).is_some_and(|rest| without_comment(rest).trim() == "[[plugin]]") {
let keys = after.iter().take_while(|line| commented_key(line)).count();
let mut table = String::from("[[plugin]]\n");
for key in after.iter().take(keys) {
table.push_str(&uncommented(key));
table.push('\n');
}
let Some(entry) = parse(&table, base)
.ok()
.and_then(|table| table.plugins.into_iter().next())
else {
continue;
};
(entry, keys, false)
} else {
continue;
};
let above = lines.get(..number).unwrap_or_default();
let comments: Vec<&str> = above
.iter()
.rev()
.take_while(|line| {
line.trim_start().starts_with('#')
&& !commented_key(line)
&& commented(line).is_none_or(|rest| rest.trim() != "[[plugin]]")
})
.filter_map(|line| commented(line))
.map(str::trim)
.collect();
let description = comments.into_iter().rev().collect::<Vec<_>>().join(" ");
listed.push(Listed {
entry,
enabled,
description,
lines: number..number + 1 + keys,
});
}
Ok(listed)
}
fn commented(line: &str) -> Option<&str> {
line.trim_start().strip_prefix('#')
}
fn commented_key(line: &str) -> bool {
commented(line)
.and_then(|rest| without_comment(rest).split_once('='))
.is_some_and(|(key, value)| {
KEYS.contains(&key.trim()) && parse_value(value.trim()).is_some()
})
}
fn uncommented(line: &str) -> String {
match line.split_once('#') {
Some((before, after)) => format!("{before}{}", after.strip_prefix(' ').unwrap_or(after)),
None => line.to_owned(),
}
}
pub(super) fn parse(text: &str, base: &Path) -> Result<PluginList> {
let mut tables: Vec<(usize, BTreeMap<String, String>)> = Vec::new();
for (number, line) in (1..).zip(text.lines()) {
let line = without_comment(line).trim();
if line.is_empty() {
continue;
}
if line == "[[plugin]]" {
tables.push((number, BTreeMap::new()));
continue;
}
let Some((key, value)) = line.split_once('=') else {
return Err(format!("line {number}: expected `key = value` or `[[plugin]]`").into());
};
let key = key.trim();
let value = parse_value(value.trim())
.ok_or_else(|| format!("line {number}: `{}` is not a string", value.trim()))?;
let Some((_, table)) = tables.last_mut() else {
return Err(format!("line {number}: `{key}` comes before the first [[plugin]]").into());
};
if table.insert(key.to_owned(), value).is_some() {
return Err(format!("line {number}: `{key}` is set twice").into());
}
}
let mut plugins: Vec<PluginEntry> = Vec::new();
let mut types = BTreeSet::new();
for (number, table) in tables {
let plugin = plugin(table, base)
.and_then(|plugin| {
if !types.insert(plugin.type_path.clone()) {
return Err(format!("`{}` is listed twice", plugin.type_path).into());
}
let package = &plugin.package;
if plugins.iter().any(|listed| {
listed.package.name == package.name && listed.package.source != package.source
}) {
return Err(
format!("`{}` is listed before with another source", package.name).into(),
);
}
Ok(plugin)
})
.map_err(|failure| format!("[[plugin]] at line {number}: {failure}"))?;
plugins.push(plugin);
}
Ok(PluginList { plugins })
}
fn plugin(mut table: BTreeMap<String, String>, base: &Path) -> Result<PluginEntry> {
let type_path = table
.remove("plugin")
.ok_or("`plugin` (the type path) is missing")?;
if !type_path.split("::").all(|segment| {
segment.chars().next().is_some_and(|c| !c.is_ascii_digit())
&& segment
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_')
}) {
return Err(format!("`{type_path}` is not a Rust type path").into());
}
let path = table.remove("path");
let git = table.remove("git");
let version = table.remove("version");
let branch = table.remove("branch");
let rev = table.remove("rev");
let name = table
.remove("crate")
.ok_or("`crate` (the package name) is missing")?;
if name.is_empty()
|| !name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
{
return Err(format!("`{name}` is not a crate name").into());
}
let source = match (path, git, version) {
(None, Some(url), None) => Source::Git { url, branch, rev },
_ if branch.is_some() || rev.is_some() => {
return Err("`branch` and `rev` only go with `git`".into());
}
(Some(path), None, None) => {
let path = base.join(path);
Source::Path(std::path::absolute(&path).unwrap_or(path))
}
(None, None, Some(version)) => Source::Version(version),
(None, None, None) => Source::Rig,
_ => return Err("set at most one of `path`, `git` and `version`".into()),
};
let package = Package { name, source };
if ["rig-harness", PACKAGE, "bevy"].contains(&package.name.as_str()) {
return Err(format!("`{}` is part of the agent itself", package.name).into());
}
if let Some(key) = table.keys().next() {
return Err(format!("unknown key `{key}`").into());
}
Ok(PluginEntry { type_path, package })
}
fn without_comment(line: &str) -> &str {
let mut in_string = false;
let mut escaped = false;
for (index, c) in line.char_indices() {
match c {
_ if escaped => escaped = false,
'\\' if in_string => escaped = true,
'"' => in_string = !in_string,
'#' if !in_string => return line.get(..index).unwrap_or(line),
_ => {}
}
}
line
}
fn parse_value(text: &str) -> Option<String> {
let (value, rest) = parse_string(text)?;
rest.trim().is_empty().then_some(value)
}
pub fn parse_string(text: &str) -> Option<(String, &str)> {
let mut chars = text.strip_prefix('"')?.char_indices();
let mut value = String::new();
while let Some((index, c)) = chars.next() {
match c {
'"' => return Some((value, text.get(index + 2..)?)),
'\\' => value.push(match chars.next()?.1 {
'n' => '\n',
't' => '\t',
'"' => '"',
'\\' => '\\',
escape @ ('u' | 'U') => {
let digits = if escape == 'u' { 4 } else { 8 };
let hex: String = chars.by_ref().take(digits).map(|(_, c)| c).collect();
if hex.len() != digits || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
return None;
}
char::from_u32(u32::from_str_radix(&hex, 16).ok()?)?
}
_ => return None,
}),
c => value.push(c),
}
}
None
}
#[cfg(test)]
mod tests;