//! The workbench's configuration, one `key=value` a line, as its owner //! writes it: //! //! ```text //! name=Bench //! port=7100 //! address=203.0.113.7:7100 # where devices reach it, if known //! peer=203.0.113.9:7000 # DHT nodes to join through (any number) //! state=/var/lib/workbench # its identity, tasks and worktrees //! contact= # a device allowed to use it (any number) //! repo=cartopolis /src/cartopolis # a name and a local clone (any number) //! remote=origin # where `propose` pushes `agent/` //! job=check cargo check --offline --locked {package} //! job=test cargo test --offline --locked {package} {filter} //! job-minutes=10 # one job's wall clock //! task-minutes=60 # all of a task's jobs //! ``` //! //! A job's argv is the owner's: the agent names the job and may fill in //! `{package}` (as `-p `) and `{filter}`, both identifiers. use pinnacle_p2p::Addr; use pinnacle_p2p::identity::Card; use std::path::{Path, PathBuf}; pub struct Config { pub name: String, pub port: u16, pub address: Option, pub peers: Vec, pub state: PathBuf, pub contacts: Vec, pub repos: Vec<(String, PathBuf)>, pub remote: String, pub jobs: Vec<(String, Vec)>, pub job_minutes: u64, pub task_minutes: u64, } pub fn parse_addr(text: &str) -> Option { let (ip, port) = text.trim().rsplit_once(':')?; let mut out = [0u8; 4]; let mut parts = ip.split('.'); for b in &mut out { *b = parts.next()?.parse().ok()?; } parts.next().is_none().then_some(())?; Some(Addr { ip: out, port: port.parse().ok()?, }) } /// A name the agent may give for a repository, a job, a package or a test /// filter: letters, digits and `_ - :`, not starting with `-`. pub fn identifier(text: &str) -> bool { !text.is_empty() && text.len() <= 100 && !text.starts_with('-') && text .chars() .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | ':')) } impl Config { pub fn read(path: &Path) -> Result { let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; Config::parse(&text) } pub fn parse(text: &str) -> Result { let mut c = Config { name: "Workbench".into(), port: 7100, address: None, peers: Vec::new(), state: PathBuf::from("workbench-state"), contacts: Vec::new(), repos: Vec::new(), remote: "origin".into(), jobs: Vec::new(), job_minutes: 10, task_minutes: 60, }; for (n, line) in text.lines().enumerate() { let line = line.split(" #").next().unwrap_or("").trim(); if line.is_empty() || line.starts_with('#') { continue; } let bad = |what: &str| format!("line {}: {what}", n + 1); let (key, value) = line.split_once('=').ok_or_else(|| bad("not key=value"))?; let value = value.trim(); match key.trim() { "name" => c.name = value.into(), "port" => c.port = value.parse().map_err(|_| bad("a port"))?, "address" => c.address = Some(parse_addr(value).ok_or_else(|| bad("an address, ip:port"))?), "peer" => c .peers .push(parse_addr(value).ok_or_else(|| bad("an address, ip:port"))?), "state" => c.state = value.into(), "contact" => c .contacts .push(crate::card_of_hex(value).ok_or_else(|| bad("a card, hex"))?), "repo" => { let (name, path) = value.split_once(' ').ok_or_else(|| bad("a name and a path"))?; if !identifier(name) { return Err(bad("a repository's name: letters, digits, - and _")); } c.repos.push((name.into(), PathBuf::from(path.trim()))); } "remote" => c.remote = value.into(), "job" => { let mut words = value.split_whitespace().map(String::from); let name = words .next() .filter(|n| identifier(n)) .ok_or_else(|| bad("a job's name"))?; let argv: Vec = words.collect(); if argv.is_empty() { return Err(bad("a job's command")); } c.jobs.push((name, argv)); } "job-minutes" => c.job_minutes = value.parse().map_err(|_| bad("minutes"))?, "task-minutes" => c.task_minutes = value.parse().map_err(|_| bad("minutes"))?, other => return Err(bad(&format!("no setting “{other}”"))), } } Ok(c) } } #[cfg(test)] mod tests { use super::*; #[test] fn a_config_is_read() { let c = Config::parse( "name=Bench\nport=7200 # comment\npeer=10.0.2.2:7000\nrepo=demo /tmp/demo\n\ job=check cargo check --offline {package}\njob-minutes=3\n", ) .unwrap(); assert_eq!((c.name.as_str(), c.port, c.job_minutes), ("Bench", 7200, 3)); assert_eq!(c.peers[0].port, 7000); assert_eq!(c.repos, vec![("demo".into(), PathBuf::from("/tmp/demo"))]); assert_eq!(c.jobs[0].1, ["cargo", "check", "--offline", "{package}"]); assert!(Config::parse("job=-x cargo").is_err()); assert!(Config::parse("nonsense=1").is_err()); assert!(Config::parse("repo=../x /tmp").is_err()); } #[test] fn identifiers() { for good in ["pinnacle-net", "tests::verbs", "a_b"] { assert!(identifier(good), "{good}"); } for bad in ["", "-p", "a b", "a;b", "$(x)", "a/b", "..", "x\n"] { assert!(!identifier(bad), "{bad:?}"); } } }