Skip to main content

toasty_cli/
config.rs

1use crate::migrate::MigrationConfig;
2use anyhow::{Context, Result};
3use serde::{Deserialize, Serialize};
4use std::fs;
5use std::path::Path;
6
7/// Configuration for Toasty CLI operations.
8///
9/// Holds all settings that control how the CLI behaves. Currently this is
10/// limited to [`MigrationConfig`]. A `Config` can be built programmatically
11/// with the builder methods or loaded from a `Toasty.toml` file via
12/// [`Config::load`].
13///
14/// # Examples
15///
16/// ```
17/// use toasty_cli::{Config, MigrationConfig, MigrationPrefixStyle};
18///
19/// let config = Config::new()
20///     .migration(
21///         MigrationConfig::new()
22///             .path("db")
23///             .prefix_style(MigrationPrefixStyle::Timestamp),
24///     );
25/// assert_eq!(
26///     config.migration.get_migrations_dir(),
27///     std::path::PathBuf::from("db/migrations"),
28/// );
29/// ```
30#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
31pub struct Config {
32    /// Migration-related configuration
33    pub migration: MigrationConfig,
34}
35
36impl Config {
37    /// Create a new Config with default values
38    pub fn new() -> Self {
39        Self::default()
40    }
41
42    /// Load configuration from Toasty.toml in the project root
43    pub fn load() -> Result<Self> {
44        Self::load_from(Path::new("Toasty.toml"))
45    }
46
47    /// Load configuration from a specific path.
48    pub fn load_from(path: &Path) -> Result<Self> {
49        let contents = fs::read_to_string(path).with_context(|| {
50            format!(
51                "failed to read Toasty config file at `{}` — check that the file exists \
52                 at this path relative to the working directory (a common cause in Docker \
53                 multi-stage builds is forgetting to copy it into the final image)",
54                path.display()
55            )
56        })?;
57        let config: Config = toml::from_str(&contents).with_context(|| {
58            format!("failed to parse Toasty config file at `{}`", path.display())
59        })?;
60        Ok(config)
61    }
62
63    /// Load configuration from `<project_root>/Toasty.toml`, or the defaults
64    /// when the file does not exist. Never creates the file: read-only
65    /// commands must work against a read-only checkout.
66    pub fn load_or_default(project_root: &Path) -> Result<Self> {
67        let path = project_root.join("Toasty.toml");
68        if path.exists() {
69            Self::load_from(&path)
70        } else {
71            Ok(Self::default())
72        }
73    }
74
75    /// Writes a default `Toasty.toml` into `project_root` if none is there.
76    pub fn create_if_missing(project_root: &Path) -> Result<()> {
77        let path = project_root.join("Toasty.toml");
78
79        if path.exists() {
80            return Ok(());
81        }
82
83        let toml = toml::to_string_pretty(&Self::default())?;
84        fs::write(&path, toml).with_context(|| format!("failed to write `{}`", path.display()))?;
85
86        Ok(())
87    }
88
89    /// Set the migration configuration
90    pub fn migration(mut self, migration: MigrationConfig) -> Self {
91        self.migration = migration;
92        self
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99    use tempfile::tempdir;
100
101    #[test]
102    fn load_or_default_does_not_write_toasty_toml() {
103        let dir = tempdir().unwrap();
104        let path = dir.path().join("Toasty.toml");
105
106        let config = Config::load_or_default(dir.path()).unwrap();
107
108        assert_eq!(config, Config::default());
109        assert!(
110            !path.exists(),
111            "loading the config must not write to the source tree"
112        );
113    }
114
115    #[test]
116    fn create_if_missing_writes_defaults_then_leaves_them_alone() {
117        let dir = tempdir().unwrap();
118        let path = dir.path().join("Toasty.toml");
119
120        Config::create_if_missing(dir.path()).unwrap();
121
122        assert!(path.exists(), "Toasty.toml should be created when absent");
123        let reparsed: Config = toml::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
124        assert_eq!(reparsed, Config::default());
125
126        // An existing file is left untouched, including settings that differ
127        // from the defaults.
128        fs::write(
129            &path,
130            "[migration]\npath = \"db\"\nprefix_style = \"Timestamp\"\n",
131        )
132        .unwrap();
133        Config::create_if_missing(dir.path()).unwrap();
134
135        let config = Config::load_or_default(dir.path()).unwrap();
136        assert_eq!(config.migration.path, std::path::PathBuf::from("db"));
137    }
138
139    #[test]
140    fn load_ignores_removed_config_keys() {
141        // Toasty.toml files written by earlier versions contain keys that no
142        // longer exist; they must still parse.
143        let config: Config = toml::from_str(
144            "[migration]\npath = \"toasty\"\nprefix_style = \"Sequential\"\n\
145             checksums = false\nstatement_breakpoints = true\n",
146        )
147        .unwrap();
148        assert_eq!(config, Config::default());
149    }
150
151    #[test]
152    fn load_from_missing_file_reports_path() {
153        let dir = tempdir().unwrap();
154        let path = dir.path().join("Toasty.toml");
155
156        let err = Config::load_from(&path).unwrap_err();
157
158        let message = format!("{err:#}");
159        assert!(
160            message.contains(&path.display().to_string()),
161            "error message should mention the missing path: {message}"
162        );
163    }
164}