Skip to main content

blyte_cli/
config.rs

1//! `blyte.toml` repository configuration: gate detection, rendering, and loading.
2
3use std::collections::BTreeMap;
4use std::path::{Path, PathBuf};
5use std::process::Command;
6
7/// Default value for `[dispatch] fix_round`: enabled (`true`) is the intended default.
8fn default_fix_round() -> bool {
9    true
10}
11
12#[derive(Debug, Clone, PartialEq, serde::Deserialize)]
13#[serde(deny_unknown_fields)]
14pub struct DispatchConfig {
15    pub gate: Option<String>,
16    pub setup: Option<String>,
17    pub base_check: Option<bool>,
18    pub comments: Option<String>,
19    /// Whether to run one fix round when the fresh review confirms fallbacks or raises concerns.
20    /// Defaults to `true`.
21    #[serde(default = "default_fix_round")]
22    pub fix_round: bool,
23    pub model: Option<String>,
24    pub max_seconds: Option<u64>,
25    pub max_turns: Option<u32>,
26    pub max_cost: Option<f64>,
27    pub fold_budget: Option<usize>,
28    pub network: Option<String>,
29    #[serde(default)]
30    pub env: BTreeMap<String, String>,
31    #[serde(default)]
32    pub allow_read: Vec<String>,
33}
34
35impl Default for DispatchConfig {
36    fn default() -> Self {
37        Self {
38            gate: None,
39            setup: None,
40            base_check: None,
41            comments: None,
42            fix_round: default_fix_round(),
43            model: None,
44            max_seconds: None,
45            max_turns: None,
46            max_cost: None,
47            fold_budget: None,
48            network: None,
49            env: BTreeMap::new(),
50            allow_read: Vec::new(),
51        }
52    }
53}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum CommentMode {
57    Gate,
58    Review,
59    Off,
60}
61
62pub fn comment_mode(value: Option<&str>) -> Result<CommentMode, String> {
63    match value {
64        None | Some("gate") => Ok(CommentMode::Gate),
65        Some("review") => Ok(CommentMode::Review),
66        Some("off") => Ok(CommentMode::Off),
67        Some(value) => Err(format!(
68            "blyte.toml: [dispatch] comments must be \"gate\", \"review\" or \"off\", not \"{value}\""
69        )),
70    }
71}
72
73#[derive(Debug, Default, Clone, PartialEq, serde::Deserialize)]
74#[serde(deny_unknown_fields)]
75pub struct ReviewConfig {
76    #[serde(default)]
77    pub risky: Vec<String>,
78}
79
80#[derive(Debug, Default, Clone, PartialEq, serde::Deserialize)]
81#[serde(deny_unknown_fields)]
82pub struct RepoConfig {
83    #[serde(default)]
84    pub dispatch: DispatchConfig,
85    #[serde(default)]
86    pub review: ReviewConfig,
87}
88
89pub fn match_risky_paths(
90    patterns: &[String],
91    changed_files: &[String],
92) -> Result<Vec<String>, String> {
93    if patterns.is_empty() || changed_files.is_empty() {
94        return Ok(Vec::new());
95    }
96    let set = build_risky_globset(patterns)?;
97    let mut matched = Vec::new();
98    for file in changed_files {
99        if set.is_match(file) && !matched.contains(file) {
100            matched.push(file.clone());
101        }
102    }
103    Ok(matched)
104}
105
106fn build_risky_globset(patterns: &[String]) -> Result<globset::GlobSet, String> {
107    let mut builder = globset::GlobSetBuilder::new();
108    for raw in patterns {
109        let pat = raw.trim();
110        if pat.is_empty() {
111            return Err("[review] risky contains an empty glob".to_string());
112        }
113        let glob = globset::GlobBuilder::new(pat)
114            .literal_separator(true)
115            .build()
116            .map_err(|e| format!("[review] risky glob `{raw}` is invalid: {e}"))?;
117        builder.add(glob);
118    }
119    builder
120        .build()
121        .map_err(|e| format!("[review] risky globs are invalid: {e}"))
122}
123
124pub fn load(root: &Path) -> Result<Option<RepoConfig>, String> {
125    let path = root.join("blyte.toml");
126    if !path.exists() {
127        return Ok(None);
128    }
129    let content = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
130    let config: RepoConfig =
131        toml::from_str(&content).map_err(|e| format!("{}: {e}", path.display()))?;
132    for (name, value) in &config.dispatch.env {
133        if name.starts_with("BLYTE_") {
134            return Err(format!(
135                "{}: variable `{name}` starts with BLYTE_: blyte's own settings are not set from blyte.toml",
136                path.display()
137            ));
138        }
139        if blyte_agent::shell::credential_like(name, value) {
140            return Err(format!(
141                "{}: variable `{name}` looks like a credential; credentials are never set from blyte.toml",
142                path.display()
143            ));
144        }
145    }
146    if !config.dispatch.allow_read.is_empty() {
147        let home = std::env::var_os("HOME").map(PathBuf::from);
148        let main = main_checkout(root).unwrap_or_else(|| root.to_path_buf());
149        expand_allow_read(&config.dispatch.allow_read, home.as_deref(), &main)?;
150    }
151    if !config.review.risky.is_empty() {
152        build_risky_globset(&config.review.risky)
153            .map_err(|e| format!("{}: {e}", path.display()))?;
154    }
155    Ok(Some(config))
156}
157
158pub fn expand_allow_read(
159    entries: &[String],
160    home: Option<&Path>,
161    main_checkout: &Path,
162) -> Result<Vec<PathBuf>, String> {
163    let mut expanded = Vec::with_capacity(entries.len());
164    for entry in entries {
165        if entry == "~" {
166            let h = home
167                .filter(|p| !p.as_os_str().is_empty())
168                .ok_or_else(|| format!("blyte.toml: cannot expand `{entry}`: HOME is not set"))?;
169            expanded.push(h.to_path_buf());
170        } else if let Some(suffix) = entry.strip_prefix("~/") {
171            let h = home
172                .filter(|p| !p.as_os_str().is_empty())
173                .ok_or_else(|| format!("blyte.toml: cannot expand `{entry}`: HOME is not set"))?;
174            expanded.push(h.join(suffix));
175        } else if entry == "$BLYTE_MAIN_CHECKOUT" {
176            expanded.push(main_checkout.to_path_buf());
177        } else if let Some(suffix) = entry.strip_prefix("$BLYTE_MAIN_CHECKOUT/") {
178            expanded.push(main_checkout.join(suffix));
179        } else if Path::new(entry).is_absolute() {
180            expanded.push(PathBuf::from(entry));
181        } else {
182            return Err(format!(
183                "blyte.toml: allow_read entry `{entry}` is a relative path; paths must be absolute, or start with ~/ or $BLYTE_MAIN_CHECKOUT"
184            ));
185        }
186    }
187    Ok(expanded)
188}
189
190pub fn main_checkout(root: &Path) -> Option<PathBuf> {
191    let out = Command::new("git")
192        .args(["rev-parse", "--path-format=absolute", "--git-common-dir"])
193        .current_dir(root)
194        .output()
195        .ok()?;
196    if !out.status.success() {
197        return None;
198    }
199    let common = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
200    if common.file_name()? != ".git" {
201        return None;
202    }
203    let parent = common.parent()?;
204    let parent_canon = parent.canonicalize().ok()?;
205    let root_canon = root.canonicalize().ok()?;
206    if parent_canon == root_canon {
207        return None;
208    }
209    Some(parent.to_path_buf())
210}
211
212pub fn load_with_fallback(root: &Path) -> Result<Option<(RepoConfig, bool)>, String> {
213    if let Some(cfg) = load(root)? {
214        return Ok(Some((cfg, false)));
215    }
216    if let Some(main) = main_checkout(root) {
217        if let Some(cfg) = load(&main)? {
218            return Ok(Some((cfg, true)));
219        }
220    }
221    Ok(None)
222}
223
224pub fn detect(root: &Path) -> Vec<String> {
225    // A Makefile's own targets are how a repository says it is checked: blyte-eval's
226    // `make lint` runs ruff and pyright, which per-language guessing would miss.
227    let make = make_targets(root);
228    if make.iter().any(|t| t == "check") {
229        return vec!["make check".to_string()];
230    }
231    let from_make: Vec<String> = ["lint", "test"]
232        .iter()
233        .filter(|t| make.iter().any(|m| m == *t))
234        .map(|t| format!("make {t}"))
235        .collect();
236    if !from_make.is_empty() {
237        return from_make;
238    }
239
240    let mut steps = Vec::new();
241
242    // Rust (Cargo.toml)
243    if root.join("Cargo.toml").exists() {
244        steps.push("cargo fmt --all --check".to_string());
245        steps.push("cargo clippy --all-targets -- -D warnings".to_string());
246        steps.push("cargo test --workspace --all-targets".to_string());
247    }
248
249    // Python (pyproject.toml)
250    if root.join("pyproject.toml").exists() {
251        let pyproject = std::fs::read_to_string(root.join("pyproject.toml")).unwrap_or_default();
252        let runner = if root.join("uv.lock").exists() {
253            "uv run "
254        } else {
255            "python3 -m "
256        };
257        if pyproject.contains("[tool.ruff") || root.join("ruff.toml").exists() {
258            steps.push(format!("{runner}ruff check ."));
259        }
260        if pyproject.contains("[tool.pytest") || root.join("tests").is_dir() {
261            steps.push(format!("{runner}pytest -q"));
262        }
263    }
264
265    // Node (package.json)
266    if root.join("package.json").exists() {
267        let runner = if root.join("pnpm-lock.yaml").exists() {
268            "pnpm"
269        } else if root.join("yarn.lock").exists() {
270            "yarn"
271        } else {
272            "npm"
273        };
274        if let Ok(content) = std::fs::read_to_string(root.join("package.json")) {
275            if let Ok(val) = serde_json::from_str::<serde_json::Value>(&content) {
276                if let Some(scripts) = val.get("scripts").and_then(|s| s.as_object()) {
277                    for script in ["lint", "typecheck", "test"] {
278                        if scripts.contains_key(script) {
279                            let cmd = if script == "test" {
280                                format!("{runner} test")
281                            } else if runner == "yarn" {
282                                format!("yarn {script}")
283                            } else {
284                                format!("{runner} run {script}")
285                            };
286                            steps.push(cmd);
287                        }
288                    }
289                }
290            }
291        }
292    }
293
294    // Go (go.mod)
295    if root.join("go.mod").exists() {
296        steps.push(r#"test -z "$(gofmt -l .)""#.to_string());
297        steps.push("go vet ./...".to_string());
298        steps.push("go test ./...".to_string());
299    }
300
301    steps
302}
303
304/// The targets a `Makefile` (or `makefile`, `GNUmakefile`) at `root` defines: lines of the form
305/// `name:` at the start of a line, excluding variable assignments (`name := …`) and special
306/// targets (`.PHONY`).
307fn make_targets(root: &Path) -> Vec<String> {
308    let text = ["GNUmakefile", "makefile", "Makefile"]
309        .iter()
310        .find_map(|f| std::fs::read_to_string(root.join(f)).ok())
311        .unwrap_or_default();
312    text.lines()
313        .filter_map(|l| {
314            let (name, rest) = l.split_once(':')?;
315            if rest.starts_with('=')
316                || name.starts_with(['.', '\t', ' ', '#'])
317                || name.contains(['=', '$', ' '])
318            {
319                return None;
320            }
321            Some(name.trim().to_string())
322        })
323        .collect()
324}