use crate::config::error::ConfigError;
use crate::config::scripts::ScriptCommand;
use serde::Deserialize;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct InstallConfig {
#[serde(default)]
pub steps: Vec<InstallStepRef>,
#[serde(default = "true_default")]
pub install_git_hooks: bool,
#[serde(default = "default_gitignore")]
pub gitignore: String,
#[serde(skip)]
pub discovered: BTreeMap<String, InstallStepScript>,
#[serde(skip)]
pub discovered_order: Vec<String>,
}
impl Default for InstallConfig {
fn default() -> Self {
Self {
steps: Vec::new(),
install_git_hooks: true,
gitignore: default_gitignore(),
discovered: BTreeMap::new(),
discovered_order: Vec::new(),
}
}
}
const fn true_default() -> bool {
true
}
fn default_gitignore() -> String {
".ampelos/.gitignore".to_string()
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(untagged)]
pub enum InstallStepRef {
Name(String),
Inline(InlineStep),
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct InlineStep {
pub name: String,
pub run: String,
#[serde(default)]
pub desc: Option<String>,
#[serde(default, rename = "in")]
pub service: Option<String>,
#[serde(default)]
pub tty: bool,
#[serde(default)]
pub env: BTreeMap<String, String>,
#[serde(default)]
pub cwd: Option<String>,
#[serde(default)]
pub optional: bool,
#[serde(default)]
pub interactive: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstallStepScript {
pub name: String,
pub path: PathBuf,
pub desc: Option<String>,
pub service: Option<String>,
pub tty: bool,
pub env: BTreeMap<String, String>,
pub cwd: Option<String>,
pub optional: bool,
pub interactive: bool,
}
impl From<ScriptCommand> for InstallStepScript {
fn from(cmd: ScriptCommand) -> Self {
Self {
name: cmd.name,
path: cmd.path,
desc: cmd.desc,
service: cmd.service,
tty: cmd.tty,
env: cmd.env,
cwd: cmd.cwd,
optional: cmd.optional,
interactive: cmd.interactive,
}
}
}
pub fn discover_install_steps(
dir: &Path,
) -> Result<(BTreeMap<String, InstallStepScript>, Vec<String>), ConfigError> {
let mut out = BTreeMap::new();
let mut order = Vec::new();
let entries = std::fs::read_dir(dir).map_err(|source| ConfigError::Io {
path: dir.to_path_buf(),
source,
})?;
let mut candidates: Vec<PathBuf> = Vec::new();
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;
}
candidates.push(entry.path());
}
candidates.sort();
for path in candidates {
let cmd = ScriptCommand::from_path(&path)?;
order.push(cmd.name.clone());
out.insert(cmd.name.clone(), cmd.into());
}
Ok((out, order))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::Config;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
#[test]
fn install_section_defaults_when_absent() {
let cfg: Config = toml::from_str("").unwrap();
assert!(cfg.install.steps.is_empty());
assert!(cfg.install.install_git_hooks);
assert_eq!(cfg.install.gitignore, ".ampelos/.gitignore");
assert!(cfg.install.discovered.is_empty());
}
#[test]
fn parses_named_steps() {
let cfg: Config = toml::from_str(
r#"
[install]
steps = ["copy-env", "composer-install", "migrate-fresh"]
"#,
)
.unwrap();
assert_eq!(cfg.install.steps.len(), 3);
match &cfg.install.steps[0] {
InstallStepRef::Name(n) => assert_eq!(n, "copy-env"),
other => panic!("expected Name, got {other:?}"),
}
}
#[test]
fn parses_inline_step() {
let cfg: Config = toml::from_str(
r#"
[[install.steps]]
name = "copy-env"
run = "test -f .env || cp .env.example .env"
desc = "Seed .env from example"
"#,
)
.unwrap();
match &cfg.install.steps[0] {
InstallStepRef::Inline(step) => {
assert_eq!(step.name, "copy-env");
assert_eq!(step.run, "test -f .env || cp .env.example .env");
assert_eq!(step.desc.as_deref(), Some("Seed .env from example"));
assert!(!step.optional);
assert!(!step.interactive);
}
other => panic!("expected Inline, got {other:?}"),
}
}
#[test]
fn parses_mixed_named_and_inline_steps() {
let cfg: Config = toml::from_str(
r#"
[install]
install_git_hooks = false
[[install.steps]]
name = "first"
run = "echo first"
[[install.steps]]
name = "second"
run = "echo second"
optional = true
interactive = true
"#,
)
.unwrap();
assert!(!cfg.install.install_git_hooks);
assert_eq!(cfg.install.steps.len(), 2);
match &cfg.install.steps[1] {
InstallStepRef::Inline(step) => {
assert!(step.optional);
assert!(step.interactive);
}
other => panic!("expected Inline, got {other:?}"),
}
}
#[test]
fn discover_install_steps_sorts_alphabetically() {
let dir = TempDir::new().unwrap();
std::fs::write(
dir.path().join("02-composer"),
"#!/bin/sh\n# @desc: Install dependencies\ncomposer install\n",
)
.unwrap();
std::fs::write(
dir.path().join("01-copy-env"),
"#!/bin/sh\n# @optional: yes\ncp .env.example .env\n",
)
.unwrap();
std::fs::write(
dir.path().join("03-migrate"),
"#!/bin/sh\n# @interactive: true\necho hi\n",
)
.unwrap();
let (map, order) = discover_install_steps(dir.path()).unwrap();
assert_eq!(order, vec!["01-copy-env", "02-composer", "03-migrate"]);
assert!(map["01-copy-env"].optional);
assert!(map["03-migrate"].interactive);
assert_eq!(
map["02-composer"].desc.as_deref(),
Some("Install dependencies")
);
}
#[test]
fn discover_install_steps_skips_hidden_and_underscored() {
let dir = TempDir::new().unwrap();
std::fs::write(dir.path().join(".hidden"), "echo nope\n").unwrap();
std::fs::write(dir.path().join("_helper"), "echo nope\n").unwrap();
std::fs::write(dir.path().join("real"), "echo yes\n").unwrap();
let (map, order) = discover_install_steps(dir.path()).unwrap();
assert_eq!(order, vec!["real"]);
assert_eq!(map.len(), 1);
}
}