ampelos 0.1.0

Dev-loop trellis: one config for Docker Compose, scripts, hooks, and agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! Loading configuration from disk.
//!
//! Encapsulates the TOML format choice. Callers (CLI, runtime, tui) work in
//! terms of [`Config`] and never speak TOML directly.

use crate::config::error::ConfigError;
use crate::config::install::discover_install_steps;
use crate::config::model::Config;
use crate::config::scripts::ScriptCommand;
use std::collections::BTreeMap;
use std::path::Path;

/// Parse a [`Config`] from a TOML source string.
pub fn parse_str(source: &str) -> Result<Config, ConfigError> {
    let config: Config = toml::from_str(source).map_err(|source| ConfigError::Parse {
        path: Path::new("<inline>").to_path_buf(),
        source,
    })?;
    config.validate().map_err(ConfigError::Invalid)?;
    Ok(config)
}

/// Read a `ampelos.toml` (or other TOML file) from disk and parse it.
pub fn load_from_path(path: &Path) -> Result<Config, ConfigError> {
    let raw = std::fs::read_to_string(path).map_err(|source| ConfigError::Io {
        path: path.to_path_buf(),
        source,
    })?;
    let config: Config = toml::from_str(&raw).map_err(|source| ConfigError::Parse {
        path: path.to_path_buf(),
        source,
    })?;
    config.validate().map_err(ConfigError::Invalid)?;
    Ok(config)
}

/// Load the full project configuration without applying a worktree
/// overlay. Equivalent to `load_project_with_slug(root, None)`.
pub fn load_project(project_root: &Path) -> Result<Config, ConfigError> {
    load_project_with_slug(project_root, None)
}

/// Load the full project configuration with an optional per-worktree
/// overlay.
///
/// Layered on top of each other (later wins):
///
/// 1. `ampelos.toml` at the project root.
/// 2. `.ampelos/local.toml` (per-developer overrides; gitignored).
/// 3. `.ampelos/worktrees/<slug>.toml` when `slug` is `Some` and the
///    file exists (per-worktree overrides; gitignored).
///
/// Missing `ampelos.toml` is fine — a default config is used as the
/// base. Plus: scripts under `.ampelos/commands/` are discovered after
/// merging.
///
/// Merging is done at the `toml::Value` level so any TOML structure
/// works: tables merge recursively, scalars and arrays replace.
pub fn load_project_with_slug(
    project_root: &Path,
    slug: Option<&str>,
) -> Result<Config, ConfigError> {
    let toml_path = project_root.join("ampelos.toml");
    let local_path = project_root.join(".ampelos").join("local.toml");

    let mut value = if toml_path.exists() {
        read_toml_value(&toml_path)?
    } else {
        toml::Value::Table(Default::default())
    };

    if local_path.exists() {
        let local = read_toml_value(&local_path)?;
        deep_merge(&mut value, local);
    }

    if let Some(slug) = slug.filter(|s| !s.is_empty()) {
        let overlay_path = project_root
            .join(".ampelos")
            .join("worktrees")
            .join(format!("{slug}.toml"));
        if overlay_path.exists() {
            let overlay = read_toml_value(&overlay_path)?;
            deep_merge(&mut value, overlay);
        }
    }

    let mut config: Config =
        value
            .try_into()
            .map_err(|source: toml::de::Error| ConfigError::Parse {
                path: toml_path.clone(),
                source,
            })?;

    let scripts_dir = project_root.join(".ampelos").join("commands");
    if scripts_dir.is_dir() {
        config.scripts = discover_scripts(&scripts_dir)?;
    }
    let install_dir = project_root.join(".ampelos").join("install");
    if install_dir.is_dir() {
        let (discovered, order) = discover_install_steps(&install_dir)?;
        config.install.discovered = discovered;
        config.install.discovered_order = order;
    }
    config.validate().map_err(ConfigError::Invalid)?;
    Ok(config)
}

fn read_toml_value(path: &Path) -> Result<toml::Value, ConfigError> {
    let raw = std::fs::read_to_string(path).map_err(|source| ConfigError::Io {
        path: path.to_path_buf(),
        source,
    })?;
    toml::from_str(&raw).map_err(|source| ConfigError::Parse {
        path: path.to_path_buf(),
        source,
    })
}

/// Recursive merge: overlay tables onto base tables key-by-key; replace
/// for everything else (scalars, arrays). Public for tests; the loader
/// is the only intended caller.
pub(crate) fn deep_merge(base: &mut toml::Value, overlay: toml::Value) {
    match (base, overlay) {
        (toml::Value::Table(b), toml::Value::Table(o)) => {
            for (k, v) in o {
                match b.get_mut(&k) {
                    Some(existing) => deep_merge(existing, v),
                    None => {
                        b.insert(k, v);
                    }
                }
            }
        }
        (slot, overlay) => *slot = overlay,
    }
}

/// Scan a directory for script files and parse their frontmatter.
///
/// Hidden files (`.foo`), files starting with `_`, and entries that aren't
/// regular files are skipped. Anything else is parsed; a parse error
/// fails the whole scan rather than silently dropping the script.
pub fn discover_scripts(dir: &Path) -> Result<BTreeMap<String, ScriptCommand>, ConfigError> {
    let mut out = BTreeMap::new();
    let entries = std::fs::read_dir(dir).map_err(|source| ConfigError::Io {
        path: dir.to_path_buf(),
        source,
    })?;
    for entry in entries {
        let entry = entry.map_err(|source| ConfigError::Io {
            path: dir.to_path_buf(),
            source,
        })?;
        let file_type = entry.file_type().map_err(|source| ConfigError::Io {
            path: entry.path(),
            source,
        })?;
        if !file_type.is_file() {
            continue;
        }
        let name = entry.file_name();
        let name_str = name.to_string_lossy();
        if name_str.starts_with('.') || name_str.starts_with('_') {
            continue;
        }
        let path = entry.path();
        let cmd = ScriptCommand::from_path(&path)?;
        out.insert(cmd.name.clone(), cmd);
    }
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn parse_str_roundtrips_minimal() {
        let cfg = parse_str(
            r#"
                [project]
                name = "x"
            "#,
        )
        .unwrap();
        assert_eq!(cfg.project.name.as_deref(), Some("x"));
    }

    #[test]
    fn load_from_path_reads_file() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("ampelos.toml");
        std::fs::write(
            &path,
            r#"
                [project]
                name = "from-disk"
            "#,
        )
        .unwrap();
        let cfg = load_from_path(&path).unwrap();
        assert_eq!(cfg.project.name.as_deref(), Some("from-disk"));
    }

    #[test]
    fn load_from_path_reports_path_in_error() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("ampelos.toml");
        std::fs::write(&path, "[project\nname = bad").unwrap();
        let err = load_from_path(&path).unwrap_err();
        match err {
            ConfigError::Parse { path: p, .. } => assert_eq!(p, path),
            other => panic!("expected Parse error, got {other:?}"),
        }
    }

    #[test]
    fn load_project_discovers_scripts() {
        let root = TempDir::new().unwrap();
        std::fs::write(
            root.path().join("ampelos.toml"),
            r#"
                [project]
                name = "x"
            "#,
        )
        .unwrap();
        let cmds = root.path().join(".ampelos").join("commands");
        std::fs::create_dir_all(&cmds).unwrap();
        std::fs::write(cmds.join("seed"), "#!/bin/sh\n# @desc: Seed\necho hi\n").unwrap();
        std::fs::write(cmds.join("migrate.sh"), "#!/bin/sh\necho m\n").unwrap();

        let cfg = load_project(root.path()).unwrap();
        assert!(cfg.scripts.contains_key("seed"));
        assert!(cfg.scripts.contains_key("migrate"));
        assert_eq!(cfg.scripts["seed"].desc.as_deref(), Some("Seed"));
    }

    #[test]
    fn load_project_works_without_toml() {
        let root = TempDir::new().unwrap();
        let cmds = root.path().join(".ampelos").join("commands");
        std::fs::create_dir_all(&cmds).unwrap();
        std::fs::write(cmds.join("seed"), "echo hi\n").unwrap();

        let cfg = load_project(root.path()).unwrap();
        assert!(cfg.scripts.contains_key("seed"));
    }

    #[test]
    fn load_project_merges_local_overlay() {
        let root = TempDir::new().unwrap();
        std::fs::write(
            root.path().join("ampelos.toml"),
            r#"
                [project]
                name = "base"

                [command.test]
                run = "composer test"

                [env]
                APP_PORT = { default = "80" }
            "#,
        )
        .unwrap();
        std::fs::create_dir_all(root.path().join(".ampelos")).unwrap();
        std::fs::write(
            root.path().join(".ampelos").join("local.toml"),
            r#"
                [project]
                name = "overridden"

                [command.test]
                forward_args = true

                [command.local-only]
                run = "echo from-local"

                [env]
                APP_PORT = { default = "8080" }
                LOCAL_VAR = { value = "yes" }
            "#,
        )
        .unwrap();

        let cfg = load_project(root.path()).unwrap();
        assert_eq!(cfg.project.name.as_deref(), Some("overridden"));
        // Existing recipe got an additional field; original `run` survives.
        let test_recipe = &cfg.commands["test"];
        assert!(test_recipe.forward_args);
        // New recipe added.
        assert!(cfg.commands.contains_key("local-only"));
        // Env: existing key updated, new key appended.
        assert_eq!(
            cfg.env.get("APP_PORT").unwrap().default.as_deref(),
            Some("8080")
        );
        assert_eq!(
            cfg.env.get("LOCAL_VAR").unwrap().value.as_deref(),
            Some("yes")
        );
    }

    #[test]
    fn load_project_works_with_only_local() {
        let root = TempDir::new().unwrap();
        std::fs::create_dir_all(root.path().join(".ampelos")).unwrap();
        std::fs::write(
            root.path().join(".ampelos").join("local.toml"),
            r#"
                [command.greet]
                run = "echo hi"
            "#,
        )
        .unwrap();
        let cfg = load_project(root.path()).unwrap();
        assert!(cfg.commands.contains_key("greet"));
    }

    #[test]
    fn load_project_with_slug_applies_overlay() {
        let root = TempDir::new().unwrap();
        std::fs::write(
            root.path().join("ampelos.toml"),
            r#"
                [project]
                name = "base"

                [command.test]
                run = "composer test"
            "#,
        )
        .unwrap();
        std::fs::create_dir_all(root.path().join(".ampelos").join("worktrees")).unwrap();
        std::fs::write(
            root.path()
                .join(".ampelos")
                .join("worktrees")
                .join("feature-x.toml"),
            r#"
                [command.test]
                forward_args = true

                [command.feature-only]
                run = "echo from-feature"
            "#,
        )
        .unwrap();

        let cfg = load_project_with_slug(root.path(), Some("feature-x")).unwrap();
        assert!(cfg.commands["test"].forward_args);
        assert!(cfg.commands.contains_key("feature-only"));

        // Without the slug, the overlay is invisible.
        let cfg_main = load_project_with_slug(root.path(), Some("main")).unwrap();
        assert!(!cfg_main.commands["test"].forward_args);
        assert!(!cfg_main.commands.contains_key("feature-only"));
    }

    #[test]
    fn load_project_with_slug_layers_after_local() {
        let root = TempDir::new().unwrap();
        std::fs::write(
            root.path().join("ampelos.toml"),
            r#"
                [project]
                name = "base"
            "#,
        )
        .unwrap();
        std::fs::create_dir_all(root.path().join(".ampelos").join("worktrees")).unwrap();
        std::fs::write(
            root.path().join(".ampelos").join("local.toml"),
            r#"
                [project]
                name = "from-local"
            "#,
        )
        .unwrap();
        std::fs::write(
            root.path()
                .join(".ampelos")
                .join("worktrees")
                .join("x.toml"),
            r#"
                [project]
                name = "from-worktree"
            "#,
        )
        .unwrap();
        let cfg = load_project_with_slug(root.path(), Some("x")).unwrap();
        // Worktree overlay is applied last, so its name wins.
        assert_eq!(cfg.project.name.as_deref(), Some("from-worktree"));
    }

    #[test]
    fn load_project_with_slug_falls_back_when_overlay_absent() {
        let root = TempDir::new().unwrap();
        std::fs::write(
            root.path().join("ampelos.toml"),
            r#"
                [project]
                name = "stable"
            "#,
        )
        .unwrap();
        // No overlay file present.
        let cfg = load_project_with_slug(root.path(), Some("missing-slug")).unwrap();
        assert_eq!(cfg.project.name.as_deref(), Some("stable"));
    }

    #[test]
    fn load_project_with_slug_none_matches_load_project() {
        let root = TempDir::new().unwrap();
        std::fs::write(
            root.path().join("ampelos.toml"),
            r#"
                [project]
                name = "x"
            "#,
        )
        .unwrap();
        let a = load_project(root.path()).unwrap();
        let b = load_project_with_slug(root.path(), None).unwrap();
        assert_eq!(a, b);
    }

    #[test]
    fn load_project_skips_hidden_and_underscored() {
        let root = TempDir::new().unwrap();
        let cmds = root.path().join(".ampelos").join("commands");
        std::fs::create_dir_all(&cmds).unwrap();
        std::fs::write(cmds.join(".secret"), "echo nope\n").unwrap();
        std::fs::write(cmds.join("_helper.sh"), "echo nope\n").unwrap();
        std::fs::write(cmds.join("real"), "echo yes\n").unwrap();

        let cfg = load_project(root.path()).unwrap();
        assert_eq!(cfg.scripts.len(), 1);
        assert!(cfg.scripts.contains_key("real"));
    }
}