Skip to main content

tuff_core/
config.rs

1use std::path::Path;
2
3use serde::{Deserialize, Serialize};
4
5use crate::error::Result;
6use crate::paths;
7
8pub const DEFAULT_AGENT: &str = "open-agents";
9
10#[derive(Debug, Serialize, Deserialize)]
11#[serde(default)]
12pub struct TuffConfig {
13    #[serde(rename = "agents", alias = "targets", alias = "harnesses")]
14    pub agents: Vec<String>,
15    #[serde(rename = "defaultAgent", alias = "default_agent")]
16    pub default_agent: String,
17}
18
19impl Default for TuffConfig {
20    fn default() -> Self {
21        Self {
22            agents: vec![],
23            default_agent: DEFAULT_AGENT.to_string(),
24        }
25    }
26}
27
28pub fn read_config(repo_root: &Path) -> Result<TuffConfig> {
29    read_config_at(&paths::project_config(repo_root))
30}
31
32pub fn read_global_config(home: &Path) -> Result<TuffConfig> {
33    read_config_at(&paths::user_config(home))
34}
35
36/// Read a config, or the defaults when there is none. Reading never writes:
37/// a command that only consults the config, such as an add that fails or a
38/// global install, must not leave a `tuff.config.json` behind in whatever
39/// directory it ran from.
40fn read_config_at(path: &Path) -> Result<TuffConfig> {
41    if path.exists() {
42        let config: TuffConfig = serde_json::from_str(&std::fs::read_to_string(path)?)?;
43        Ok(config)
44    } else {
45        Ok(TuffConfig::default())
46    }
47}
48
49pub fn write_config(repo_root: &Path, config: &TuffConfig) -> Result<()> {
50    write_config_at(&paths::project_config(repo_root), config)
51}
52
53pub fn write_global_config(home: &Path, config: &TuffConfig) -> Result<()> {
54    write_config_at(&paths::user_config(home), config)
55}
56
57fn write_config_at(path: &Path, config: &TuffConfig) -> Result<()> {
58    if let Some(parent) = path.parent() {
59        std::fs::create_dir_all(parent)?;
60    }
61    std::fs::write(path, serde_json::to_string_pretty(config)? + "\n")?;
62    Ok(())
63}