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, Copy, PartialEq, Eq, serde::Deserialize)]
81#[serde(rename_all = "lowercase")]
82pub enum PublishApproval {
83    #[default]
84    Auto,
85    Ask,
86}
87
88#[derive(Debug, Default, Clone, PartialEq, serde::Deserialize)]
89#[serde(deny_unknown_fields)]
90pub struct SurfaceConfig {
91    #[serde(default)]
92    pub publish: PublishApproval,
93}
94
95#[derive(Debug, Default, Clone, PartialEq, serde::Deserialize)]
96#[serde(deny_unknown_fields)]
97pub struct RepoConfig {
98    #[serde(default)]
99    pub dispatch: DispatchConfig,
100    #[serde(default)]
101    pub review: ReviewConfig,
102    #[serde(default)]
103    pub surface: SurfaceConfig,
104}
105
106pub fn match_risky_paths(
107    patterns: &[String],
108    changed_files: &[String],
109) -> Result<Vec<String>, String> {
110    if patterns.is_empty() || changed_files.is_empty() {
111        return Ok(Vec::new());
112    }
113    let set = build_risky_globset(patterns)?;
114    let mut matched = Vec::new();
115    for file in changed_files {
116        if set.is_match(file) && !matched.contains(file) {
117            matched.push(file.clone());
118        }
119    }
120    Ok(matched)
121}
122
123fn build_risky_globset(patterns: &[String]) -> Result<globset::GlobSet, String> {
124    let mut builder = globset::GlobSetBuilder::new();
125    for raw in patterns {
126        let pat = raw.trim();
127        if pat.is_empty() {
128            return Err("[review] risky contains an empty glob".to_string());
129        }
130        let glob = globset::GlobBuilder::new(pat)
131            .literal_separator(true)
132            .build()
133            .map_err(|e| format!("[review] risky glob `{raw}` is invalid: {e}"))?;
134        builder.add(glob);
135    }
136    builder
137        .build()
138        .map_err(|e| format!("[review] risky globs are invalid: {e}"))
139}
140
141pub fn load(root: &Path) -> Result<Option<RepoConfig>, String> {
142    let path = root.join("blyte.toml");
143    if !path.exists() {
144        return Ok(None);
145    }
146    let content = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
147    let config: RepoConfig =
148        toml::from_str(&content).map_err(|e| format!("{}: {e}", path.display()))?;
149    for (name, value) in &config.dispatch.env {
150        if name.starts_with("BLYTE_") {
151            return Err(format!(
152                "{}: variable `{name}` starts with BLYTE_: blyte's own settings are not set from blyte.toml",
153                path.display()
154            ));
155        }
156        if blyte_agent::shell::credential_like(name, value) {
157            return Err(format!(
158                "{}: variable `{name}` looks like a credential; credentials are never set from blyte.toml",
159                path.display()
160            ));
161        }
162    }
163    if !config.dispatch.allow_read.is_empty() {
164        let home = std::env::var_os("HOME").map(PathBuf::from);
165        let main = main_checkout(root).unwrap_or_else(|| root.to_path_buf());
166        expand_allow_read(&config.dispatch.allow_read, home.as_deref(), &main)?;
167    }
168    if !config.review.risky.is_empty() {
169        build_risky_globset(&config.review.risky)
170            .map_err(|e| format!("{}: {e}", path.display()))?;
171    }
172    Ok(Some(config))
173}
174
175pub fn expand_allow_read(
176    entries: &[String],
177    home: Option<&Path>,
178    main_checkout: &Path,
179) -> Result<Vec<PathBuf>, String> {
180    let mut expanded = Vec::with_capacity(entries.len());
181    for entry in entries {
182        if entry == "~" {
183            let h = home
184                .filter(|p| !p.as_os_str().is_empty())
185                .ok_or_else(|| format!("blyte.toml: cannot expand `{entry}`: HOME is not set"))?;
186            expanded.push(h.to_path_buf());
187        } else if let Some(suffix) = entry.strip_prefix("~/") {
188            let h = home
189                .filter(|p| !p.as_os_str().is_empty())
190                .ok_or_else(|| format!("blyte.toml: cannot expand `{entry}`: HOME is not set"))?;
191            expanded.push(h.join(suffix));
192        } else if entry == "$BLYTE_MAIN_CHECKOUT" {
193            expanded.push(main_checkout.to_path_buf());
194        } else if let Some(suffix) = entry.strip_prefix("$BLYTE_MAIN_CHECKOUT/") {
195            expanded.push(main_checkout.join(suffix));
196        } else if Path::new(entry).is_absolute() {
197            expanded.push(PathBuf::from(entry));
198        } else {
199            return Err(format!(
200                "blyte.toml: allow_read entry `{entry}` is a relative path; paths must be absolute, or start with ~/ or $BLYTE_MAIN_CHECKOUT"
201            ));
202        }
203    }
204    Ok(expanded)
205}
206
207pub fn main_checkout(root: &Path) -> Option<PathBuf> {
208    let out = Command::new("git")
209        .args(["rev-parse", "--path-format=absolute", "--git-common-dir"])
210        .current_dir(root)
211        .output()
212        .ok()?;
213    if !out.status.success() {
214        return None;
215    }
216    let common = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
217    if common.file_name()? != ".git" {
218        return None;
219    }
220    let parent = common.parent()?;
221    let parent_canon = parent.canonicalize().ok()?;
222    let root_canon = root.canonicalize().ok()?;
223    if parent_canon == root_canon {
224        return None;
225    }
226    Some(parent.to_path_buf())
227}
228
229pub fn load_with_fallback(root: &Path) -> Result<Option<(RepoConfig, bool)>, String> {
230    if let Some(cfg) = load(root)? {
231        return Ok(Some((cfg, false)));
232    }
233    if let Some(main) = main_checkout(root) {
234        if let Some(cfg) = load(&main)? {
235            return Ok(Some((cfg, true)));
236        }
237    }
238    Ok(None)
239}
240
241pub fn detect(root: &Path) -> Vec<String> {
242    // A Makefile's own targets are how a repository says it is checked: blyte-eval's
243    // `make lint` runs ruff and pyright, which per-language guessing would miss.
244    let make = make_targets(root);
245    if make.iter().any(|t| t == "check") {
246        return vec!["make check".to_string()];
247    }
248    let from_make: Vec<String> = ["lint", "test"]
249        .iter()
250        .filter(|t| make.iter().any(|m| m == *t))
251        .map(|t| format!("make {t}"))
252        .collect();
253    if !from_make.is_empty() {
254        return from_make;
255    }
256
257    let mut steps = Vec::new();
258
259    // Rust (Cargo.toml)
260    if root.join("Cargo.toml").exists() {
261        steps.push("cargo fmt --all --check".to_string());
262        steps.push("cargo clippy --all-targets -- -D warnings".to_string());
263        steps.push("cargo test --workspace --all-targets".to_string());
264    }
265
266    // Python (pyproject.toml)
267    if root.join("pyproject.toml").exists() {
268        let pyproject = std::fs::read_to_string(root.join("pyproject.toml")).unwrap_or_default();
269        let runner = if root.join("uv.lock").exists() {
270            "uv run "
271        } else {
272            "python3 -m "
273        };
274        if pyproject.contains("[tool.ruff") || root.join("ruff.toml").exists() {
275            steps.push(format!("{runner}ruff check ."));
276        }
277        if pyproject.contains("[tool.pytest") || root.join("tests").is_dir() {
278            steps.push(format!("{runner}pytest -q"));
279        }
280    }
281
282    // Node (package.json)
283    if root.join("package.json").exists() {
284        let runner = if root.join("pnpm-lock.yaml").exists() {
285            "pnpm"
286        } else if root.join("yarn.lock").exists() {
287            "yarn"
288        } else {
289            "npm"
290        };
291        if let Ok(content) = std::fs::read_to_string(root.join("package.json")) {
292            if let Ok(val) = serde_json::from_str::<serde_json::Value>(&content) {
293                if let Some(scripts) = val.get("scripts").and_then(|s| s.as_object()) {
294                    for script in ["lint", "typecheck", "test"] {
295                        if scripts.contains_key(script) {
296                            let cmd = if script == "test" {
297                                format!("{runner} test")
298                            } else if runner == "yarn" {
299                                format!("yarn {script}")
300                            } else {
301                                format!("{runner} run {script}")
302                            };
303                            steps.push(cmd);
304                        }
305                    }
306                }
307            }
308        }
309    }
310
311    // Go (go.mod)
312    if root.join("go.mod").exists() {
313        steps.push(r#"test -z "$(gofmt -l .)""#.to_string());
314        steps.push("go vet ./...".to_string());
315        steps.push("go test ./...".to_string());
316    }
317
318    steps
319}
320
321/// The targets a `Makefile` (or `makefile`, `GNUmakefile`) at `root` defines: lines of the form
322/// `name:` at the start of a line, excluding variable assignments (`name := …`) and special
323/// targets (`.PHONY`).
324fn make_targets(root: &Path) -> Vec<String> {
325    let text = ["GNUmakefile", "makefile", "Makefile"]
326        .iter()
327        .find_map(|f| std::fs::read_to_string(root.join(f)).ok())
328        .unwrap_or_default();
329    text.lines()
330        .filter_map(|l| {
331            let (name, rest) = l.split_once(':')?;
332            if rest.starts_with('=')
333                || name.starts_with(['.', '\t', ' ', '#'])
334                || name.contains(['=', '$', ' '])
335            {
336                return None;
337            }
338            Some(name.trim().to_string())
339        })
340        .collect()
341}