Skip to main content

robin/config/
robin_config.rs

1use anyhow::{Context, Result};
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4use std::collections::HashMap;
5use std::fs;
6use std::path::{Path, PathBuf};
7
8use crate::CONFIG_FILE;
9
10/// Canonical location of the published JSON Schema for `.robin.json`. Generated
11/// configs point their `$schema` here so editors can offer autocomplete and
12/// validation.
13pub const SCHEMA_URL: &str =
14    "https://raw.githubusercontent.com/cesarferreira/robin/refs/heads/main/schema/robin.schema.json";
15
16/// Walks up from `start` (inclusive) looking for the first directory that
17/// contains a `.robin.json`. Returns the path to that config, or `None` when no
18/// ancestor holds one. This lets `robin` be run from any subdirectory of a
19/// project, mirroring how `git` and `cargo` locate their root files.
20pub fn find_config_from(start: &Path) -> Option<PathBuf> {
21    let mut dir = Some(start);
22    while let Some(current) = dir {
23        let candidate = current.join(CONFIG_FILE);
24        if candidate.is_file() {
25            return Some(candidate);
26        }
27        dir = current.parent();
28    }
29    None
30}
31
32/// Resolves the config path for read commands: the nearest `.robin.json` found
33/// by walking up from the current directory, falling back to `./.robin.json`
34/// so that "not found" errors still name a sensible location.
35pub fn find_config_path() -> PathBuf {
36    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
37    find_config_from(&cwd).unwrap_or_else(|| cwd.join(CONFIG_FILE))
38}
39
40#[derive(Debug, Default, Serialize, Deserialize)]
41pub struct RobinConfig {
42    /// Optional pointer to the JSON Schema, preserved across edits so editor
43    /// tooling keeps working. Serialized as the conventional `$schema` key.
44    #[serde(rename = "$schema", default, skip_serializing_if = "Option::is_none")]
45    pub schema: Option<String>,
46    #[serde(default, skip_serializing_if = "Vec::is_empty")]
47    pub include: Vec<String>,
48    pub scripts: HashMap<String, Value>,
49}
50
51/// Returns the executable part of a script entry.
52///
53/// A script may be written in three shapes:
54///   - a bare string:          `"cargo build"`
55///   - an array of commands:    `["cargo build", "cargo test"]`
56///   - an object with metadata: `{ "cmd": <string|array>, "desc": "..." }`
57///
58/// For the string/array forms the entry is itself the command; for the object
59/// form the command lives under `cmd`. Returns `None` for unsupported shapes.
60pub fn script_command(entry: &Value) -> Option<&Value> {
61    match entry {
62        Value::String(_) | Value::Array(_) => Some(entry),
63        Value::Object(map) => map.get("cmd"),
64        _ => None,
65    }
66}
67
68/// Returns the human-readable description of a script entry, when it uses the
69/// object form and carries a non-empty `desc`.
70pub fn script_description(entry: &Value) -> Option<&str> {
71    entry
72        .as_object()?
73        .get("desc")?
74        .as_str()
75        .filter(|s| !s.is_empty())
76}
77
78impl RobinConfig {
79    pub fn load(path: &Path) -> Result<Self> {
80        let mut config = Self::load_raw(path)?;
81
82        // Load and merge included configs
83        if !config.include.is_empty() {
84            let base_dir = path.parent().unwrap_or_else(|| Path::new("."));
85            config = config.merge_includes(base_dir)?;
86        }
87
88        Ok(config)
89    }
90
91    /// Parses a single config file without following `include` — the scripts are
92    /// exactly those declared in this file. Used by commands (like `migrate`)
93    /// that rewrite the file in place and must not inline included scripts.
94    pub fn load_raw(path: &Path) -> Result<Self> {
95        if !path.exists() {
96            return Err(anyhow::anyhow!(
97                "No .robin.json found. Run 'robin init' first"
98            ));
99        }
100
101        let content = fs::read_to_string(path)
102            .with_context(|| format!("Failed to read config file: {}", path.display()))?;
103
104        let config: Self = serde_json::from_str(&content)
105            .with_context(|| "The .robin.json file exists but contains malformed JSON. Please check the file format.")?;
106
107        Ok(config)
108    }
109
110    fn merge_includes(&self, base_dir: &Path) -> Result<Self> {
111        let mut merged_scripts = self.scripts.clone();
112
113        for include_path in &self.include {
114            let full_path = base_dir.join(include_path);
115            let included_config = Self::load(&full_path)
116                .with_context(|| format!("Failed to load included config: {}", include_path))?;
117
118            // Merge scripts from included config; existing keys take precedence.
119            for (key, value) in included_config.scripts {
120                merged_scripts.entry(key).or_insert(value);
121            }
122        }
123
124        Ok(Self {
125            schema: self.schema.clone(),
126            include: self.include.clone(),
127            scripts: merged_scripts,
128        })
129    }
130
131    pub fn save(&self, path: &Path) -> Result<()> {
132        let content =
133            serde_json::to_string_pretty(self).with_context(|| "Failed to serialize config")?;
134
135        fs::write(path, content)
136            .with_context(|| format!("Failed to write config to: {}", path.display()))?;
137
138        Ok(())
139    }
140
141    pub fn create_template() -> Self {
142        let mut scripts = HashMap::new();
143        scripts.insert("clean".to_string(), Value::String("...".to_string()));
144        scripts.insert(
145            "deploy staging".to_string(),
146            Value::String("echo 'ruby deploy tool --staging'".to_string()),
147        );
148        scripts.insert(
149            "deploy production".to_string(),
150            Value::String("...".to_string()),
151        );
152        scripts.insert("release beta".to_string(), Value::String("...".to_string()));
153        scripts.insert(
154            "release alpha".to_string(),
155            Value::String("...".to_string()),
156        );
157        scripts.insert("release dev".to_string(), Value::String("...".to_string()));
158
159        Self {
160            schema: Some(SCHEMA_URL.to_string()),
161            include: Vec::new(),
162            scripts,
163        }
164    }
165
166    /// Renames a task from `from` to `to`, preserving its definition. Errors if
167    /// `from` does not exist or `to` is already taken, so no task is silently
168    /// overwritten.
169    pub fn rename_script(&mut self, from: &str, to: &str) -> Result<()> {
170        if self.scripts.contains_key(to) {
171            return Err(anyhow::anyhow!("A command named '{}' already exists", to));
172        }
173        let value = self
174            .scripts
175            .remove(from)
176            .ok_or_else(|| anyhow::anyhow!("Unknown command: {}", from))?;
177        self.scripts.insert(to.to_string(), value);
178        Ok(())
179    }
180
181    /// Rewrites every script into the object form `{ "cmd": ..., "desc": "" }`,
182    /// leaving an empty `desc` ready to be filled in. Entries already in object
183    /// form are kept as-is. This is what `robin migrate` applies so users can
184    /// start attaching descriptions to existing tasks.
185    pub fn migrated(&self) -> Self {
186        let scripts = self
187            .scripts
188            .iter()
189            .map(|(name, entry)| {
190                let migrated = match entry {
191                    Value::Object(_) => entry.clone(),
192                    other => serde_json::json!({ "cmd": other, "desc": "" }),
193                };
194                (name.clone(), migrated)
195            })
196            .collect();
197
198        Self {
199            // Ensure the migrated file points at the schema for editor tooling,
200            // keeping any pointer the user already set.
201            schema: self
202                .schema
203                .clone()
204                .or_else(|| Some(SCHEMA_URL.to_string())),
205            include: self.include.clone(),
206            scripts,
207        }
208    }
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214    use serde_json::json;
215
216    #[test]
217    fn script_command_reads_bare_string_and_array() {
218        assert_eq!(script_command(&json!("cargo build")), Some(&json!("cargo build")));
219        let arr = json!(["a", "b"]);
220        assert_eq!(script_command(&arr), Some(&arr));
221    }
222
223    #[test]
224    fn script_command_reads_cmd_field_from_object() {
225        let entry = json!({ "cmd": "cargo build", "desc": "Build it" });
226        assert_eq!(script_command(&entry), Some(&json!("cargo build")));
227
228        let entry_arr = json!({ "cmd": ["a", "b"], "desc": "seq" });
229        assert_eq!(script_command(&entry_arr), Some(&json!(["a", "b"])));
230    }
231
232    #[test]
233    fn script_command_is_none_for_unsupported_shapes() {
234        assert_eq!(script_command(&json!(42)), None);
235        assert_eq!(script_command(&json!({ "desc": "no cmd" })), None);
236    }
237
238    #[test]
239    fn script_description_reads_only_non_empty_desc() {
240        assert_eq!(
241            script_description(&json!({ "cmd": "x", "desc": "hello" })),
242            Some("hello")
243        );
244        assert_eq!(script_description(&json!({ "cmd": "x", "desc": "" })), None);
245        assert_eq!(script_description(&json!("cargo build")), None);
246    }
247
248    #[test]
249    fn rename_script_moves_definition_to_new_key() {
250        let mut scripts = HashMap::new();
251        scripts.insert("old".to_string(), json!("cargo build"));
252        let mut config = RobinConfig {
253            schema: None,
254            include: vec![],
255            scripts,
256        };
257
258        config.rename_script("old", "new").unwrap();
259
260        assert!(!config.scripts.contains_key("old"));
261        assert_eq!(config.scripts["new"], json!("cargo build"));
262    }
263
264    #[test]
265    fn rename_script_errors_on_unknown_source() {
266        let mut config = RobinConfig {
267            schema: None,
268            include: vec![],
269            scripts: HashMap::new(),
270        };
271        let err = config.rename_script("missing", "new").unwrap_err();
272        assert!(err.to_string().contains("Unknown command"), "{err}");
273    }
274
275    #[test]
276    fn rename_script_refuses_to_overwrite_existing_target() {
277        let mut scripts = HashMap::new();
278        scripts.insert("a".to_string(), json!("1"));
279        scripts.insert("b".to_string(), json!("2"));
280        let mut config = RobinConfig {
281            schema: None,
282            include: vec![],
283            scripts,
284        };
285
286        let err = config.rename_script("a", "b").unwrap_err();
287        assert!(err.to_string().contains("already exists"), "{err}");
288        // Both tasks must remain untouched after a refused rename.
289        assert_eq!(config.scripts["a"], json!("1"));
290        assert_eq!(config.scripts["b"], json!("2"));
291    }
292
293    #[test]
294    fn migrated_wraps_strings_and_arrays_but_keeps_objects() {
295        let mut scripts = HashMap::new();
296        scripts.insert("s".to_string(), json!("cargo build"));
297        scripts.insert("a".to_string(), json!(["x", "y"]));
298        scripts.insert(
299            "o".to_string(),
300            json!({ "cmd": "already", "desc": "kept" }),
301        );
302        let config = RobinConfig {
303            schema: None,
304            include: vec!["base.json".to_string()],
305            scripts,
306        };
307
308        let migrated = config.migrated();
309
310        assert_eq!(migrated.scripts["s"], json!({ "cmd": "cargo build", "desc": "" }));
311        assert_eq!(migrated.scripts["a"], json!({ "cmd": ["x", "y"], "desc": "" }));
312        assert_eq!(migrated.scripts["o"], json!({ "cmd": "already", "desc": "kept" }));
313        // `include` is preserved untouched.
314        assert_eq!(migrated.include, vec!["base.json".to_string()]);
315    }
316}