autumn-cli 0.4.0

CLI tool for the Autumn web framework
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
//! `autumn seed` -- run the project's seed binary to populate the database.
//!
//! Delegates to `cargo run --bin seed` after:
//!   1. Verifying `src/bin/seed.rs` exists.
//!   2. Checking for pending migrations via the diesel CLI.
//!
//! The seed binary receives the active profile through the `AUTUMN_ENV`
//! environment variable, matching how the rest of the framework resolves
//! configuration profiles.

use std::path::{Path, PathBuf};
use std::process::Command;

/// Errors surfaced by the seed runner.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum SeedError {
    #[error(
        "no seed binary found; create `src/bin/seed.rs`\n\
         See: https://autumn.rs/guide/seeding"
    )]
    MissingSeedBinary,

    #[error("pending migrations detected; run `autumn migrate` before `autumn seed`")]
    PendingMigrations,
}

/// Returns `true` if the seed binary source file exists at `path`.
fn seed_binary_exists_at(path: &Path) -> bool {
    path.is_file()
}

/// Locate the directory of a Cargo package by name using `cargo metadata`.
///
/// Returns the directory containing the package's `Cargo.toml`, or `None` if
/// the package cannot be found or `cargo metadata` fails.
fn find_package_dir(package: &str) -> Option<PathBuf> {
    let output = Command::new("cargo")
        .args(["metadata", "--no-deps", "--format-version", "1"])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let metadata: serde_json::Value = serde_json::from_slice(&output.stdout).ok()?;
    let manifest_path = metadata["packages"]
        .as_array()?
        .iter()
        .find(|p| p["name"].as_str() == Some(package))?["manifest_path"]
        .as_str()?
        .to_owned();
    Path::new(&manifest_path).parent().map(Path::to_path_buf)
}

/// Resolve the database URL from environment variables and `autumn.toml`.
///
/// Reads `autumn.toml` from `base_dir` (the project root) rather than from
/// the process working directory so that workspace invocations are correct.
///
/// Precedence (highest to lowest):
/// 1. `AUTUMN_DATABASE__PRIMARY_URL` env var
/// 2. `AUTUMN_DATABASE__URL` env var
/// 3. `DATABASE_URL` env var
/// 4. `[profile.<profile>.database.primary_url]` in `<base_dir>/autumn.toml`
/// 5. `[profile.<profile>.database.url]` in `<base_dir>/autumn.toml`
/// 6. `[database.primary_url]` in `<base_dir>/autumn.toml`
/// 7. `[database.url]` in `<base_dir>/autumn.toml`
fn resolve_database_url_with_env<F>(
    env_var: F,
    base_dir: &Path,
    profile: &str,
) -> Result<String, SeedError>
where
    F: Fn(&str) -> Result<String, std::env::VarError>,
{
    for var in [
        "AUTUMN_DATABASE__PRIMARY_URL",
        "AUTUMN_DATABASE__URL",
        "DATABASE_URL",
    ] {
        if let Ok(url) = env_var(var)
            && !url.is_empty()
        {
            return Ok(url);
        }
    }

    let config_path = base_dir.join("autumn.toml");
    if config_path.exists()
        && let Ok(contents) = std::fs::read_to_string(&config_path)
        && let Ok(table) = toml::from_str::<toml::Table>(&contents)
    {
        let value = toml::Value::Table(table);

        // Profile-specific override: [profile.<name>.database]
        let profile_database = value
            .get("profile")
            .and_then(|p| p.get(profile))
            .and_then(|p| p.get("database"))
            .and_then(toml::Value::as_table);
        if let Some(url) = first_database_url(profile_database) {
            return Ok(url);
        }

        // Top-level fallback: [database]
        let database = value.get("database").and_then(toml::Value::as_table);
        if let Some(url) = first_database_url(database) {
            return Ok(url);
        }
    }

    Err(SeedError::MissingSeedBinary)
}

fn first_database_url(database: Option<&toml::Table>) -> Option<String> {
    let database = database?;
    for key in ["primary_url", "url"] {
        if let Some(url) = database
            .get(key)
            .and_then(toml::Value::as_str)
            .filter(|url| !url.is_empty())
        {
            return Some(url.to_owned());
        }
    }

    None
}

/// Resolve the database URL using the real environment, a given base dir, and profile.
fn resolve_database_url(base_dir: &Path, profile: &str) -> Result<String, SeedError> {
    resolve_database_url_with_env(|key| std::env::var(key), base_dir, profile)
}

/// Check whether there are pending (unapplied) migrations.
///
/// Runs `diesel migration list` and scans for `[ ]` markers that indicate
/// unapplied migrations. Returns `Ok(())` if all migrations are applied or
/// if diesel CLI is unavailable (in which case a warning is printed).
fn check_pending_migrations(database_url: &str, migrations_dir: &str) -> Result<(), SeedError> {
    let output = Command::new("diesel")
        .args(["migration", "list", "--migration-dir", migrations_dir])
        .env("DATABASE_URL", database_url)
        .output();

    if let Ok(out) = output {
        let stdout = String::from_utf8_lossy(&out.stdout);
        let stderr = String::from_utf8_lossy(&out.stderr);
        let combined = format!("{stdout}{stderr}");
        if combined.lines().any(|line| line.contains("[ ]")) {
            return Err(SeedError::PendingMigrations);
        }
    } else {
        eprintln!(
            "  \u{26a0} diesel CLI not found; skipping pending-migration check.\n  \
             Install with: cargo install diesel_cli --no-default-features --features postgres"
        );
    }
    Ok(())
}

/// Entry point for `autumn seed`.
pub fn run(profile: &str, package: Option<&str>) {
    eprintln!("\u{1F342} autumn seed\n");
    eprintln!("  Profile: {profile}");

    // Determine the project directory: either the workspace member's root (when
    // --package is given) or the current working directory.
    let project_dir: PathBuf = package
        .and_then(find_package_dir)
        .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));

    let seed_path = project_dir.join("src/bin/seed.rs");
    if !seed_binary_exists_at(&seed_path) {
        eprintln!("\u{2717} {}", SeedError::MissingSeedBinary);
        std::process::exit(1);
    }

    // Best-effort pending migration check when diesel CLI and migrations dir are available.
    let migrations_dir = project_dir.join("migrations");
    if let Ok(db_url) = resolve_database_url(&project_dir, profile)
        && migrations_dir.is_dir()
        && let Err(e) = check_pending_migrations(&db_url, &migrations_dir.to_string_lossy())
    {
        eprintln!("\u{2717} {e}");
        std::process::exit(1);
    }

    eprintln!("  Running seed binary...\n");

    let mut cmd = Command::new("cargo");
    cmd.args(["run", "--bin", "seed"]);
    if let Some(pkg) = package {
        cmd.args(["--package", pkg]);
    }
    cmd.env("AUTUMN_ENV", profile);
    cmd.env("AUTUMN_PROFILE", profile);
    // Run from the project directory so the seed binary's SeedContext reads
    // autumn.toml from the correct location (the package root, not the
    // workspace root).
    cmd.current_dir(&project_dir);

    let status = cmd.status();
    match status {
        Ok(s) if s.success() => {
            eprintln!("\n\u{2713} Seed completed successfully.");
        }
        Ok(_) => {
            eprintln!("\n\u{2717} Seed binary exited with a non-zero status.");
            std::process::exit(1);
        }
        Err(e) => {
            eprintln!("\u{2717} Failed to run cargo: {e}");
            std::process::exit(1);
        }
    }
}

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

    // ── SeedError messages ─────────────────────────────────────────────────

    #[test]
    fn missing_seed_binary_error_mentions_src_bin_seed() {
        let msg = SeedError::MissingSeedBinary.to_string();
        assert!(
            msg.contains("src/bin/seed.rs"),
            "error should mention src/bin/seed.rs, got: {msg}"
        );
    }

    #[test]
    fn missing_seed_binary_error_mentions_seeding_guide_url() {
        let msg = SeedError::MissingSeedBinary.to_string();
        assert!(
            msg.contains("autumn.rs/guide/seeding"),
            "error should link to the seeding guide, got: {msg}"
        );
    }

    #[test]
    fn pending_migrations_error_mentions_autumn_migrate() {
        let msg = SeedError::PendingMigrations.to_string();
        assert!(
            msg.contains("autumn migrate"),
            "error should mention `autumn migrate`, got: {msg}"
        );
    }

    #[test]
    fn pending_migrations_error_mentions_pending() {
        let msg = SeedError::PendingMigrations.to_string();
        assert!(
            msg.contains("pending"),
            "error should mention pending migrations, got: {msg}"
        );
    }

    // ── seed_binary_exists_at ──────────────────────────────────────────────

    #[test]
    fn seed_binary_exists_at_returns_false_for_missing_path() {
        assert!(!seed_binary_exists_at(Path::new(
            "/nonexistent/src/bin/seed.rs"
        )));
    }

    #[test]
    fn seed_binary_exists_at_returns_true_when_file_present() {
        let tmp = TempDir::new().unwrap();
        let seed_path = tmp.path().join("src/bin/seed.rs");
        std::fs::create_dir_all(seed_path.parent().unwrap()).unwrap();
        std::fs::write(&seed_path, "fn main() {}").unwrap();
        assert!(seed_binary_exists_at(&seed_path));
    }

    #[test]
    fn seed_binary_exists_at_returns_false_for_directory() {
        let tmp = TempDir::new().unwrap();
        let seed_dir = tmp.path().join("src/bin/seed.rs");
        std::fs::create_dir_all(&seed_dir).unwrap();
        // seed_dir is a directory, not a file
        assert!(!seed_binary_exists_at(&seed_dir));
    }

    // ── resolve_database_url_with_env ──────────────────────────────────────

    #[test]
    fn resolve_db_url_prefers_autumn_database_url() {
        let env = |key: &str| match key {
            "AUTUMN_DATABASE__URL" => Ok("postgres://autumn:5432/db".to_string()),
            "DATABASE_URL" => Ok("postgres://plain:5432/db".to_string()),
            _ => Err(std::env::VarError::NotPresent),
        };
        let url = resolve_database_url_with_env(env, Path::new("."), "dev").unwrap();
        assert_eq!(url, "postgres://autumn:5432/db");
    }

    #[test]
    fn resolve_db_url_prefers_primary_database_url_env() {
        let env = |key: &str| match key {
            "AUTUMN_DATABASE__PRIMARY_URL" => Ok("postgres://primary:5432/db".to_string()),
            "AUTUMN_DATABASE__URL" => Ok("postgres://legacy:5432/db".to_string()),
            "DATABASE_URL" => Ok("postgres://plain:5432/db".to_string()),
            _ => Err(std::env::VarError::NotPresent),
        };
        let url = resolve_database_url_with_env(env, Path::new("."), "dev").unwrap();
        assert_eq!(url, "postgres://primary:5432/db");
    }

    #[test]
    fn resolve_db_url_falls_back_to_database_url() {
        let env = |key: &str| match key {
            "DATABASE_URL" => Ok("postgres://fallback:5432/db".to_string()),
            _ => Err(std::env::VarError::NotPresent),
        };
        let url = resolve_database_url_with_env(env, Path::new("."), "dev").unwrap();
        assert_eq!(url, "postgres://fallback:5432/db");
    }

    #[test]
    fn resolve_db_url_returns_err_when_no_env_no_toml() {
        let tmp = TempDir::new().unwrap();
        let env =
            |_: &str| -> Result<String, std::env::VarError> { Err(std::env::VarError::NotPresent) };
        assert!(resolve_database_url_with_env(env, tmp.path(), "dev").is_err());
    }

    #[test]
    fn resolve_db_url_ignores_empty_env_var() {
        let env = |key: &str| match key {
            "AUTUMN_DATABASE__URL" => Ok(String::new()),
            "DATABASE_URL" => Ok("postgres://real:5432/db".to_string()),
            _ => Err(std::env::VarError::NotPresent),
        };
        let url = resolve_database_url_with_env(env, Path::new("."), "dev").unwrap();
        assert_eq!(url, "postgres://real:5432/db");
    }

    #[test]
    fn resolve_db_url_reads_database_url_from_base_dir_toml() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("autumn.toml"),
            "[database]\nurl = \"postgres://toml:5432/db\"\n",
        )
        .unwrap();
        let env =
            |_: &str| -> Result<String, std::env::VarError> { Err(std::env::VarError::NotPresent) };
        let url = resolve_database_url_with_env(env, tmp.path(), "dev").unwrap();
        assert_eq!(url, "postgres://toml:5432/db");
    }

    #[test]
    fn resolve_db_url_reads_primary_url_from_base_dir_toml() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("autumn.toml"),
            "[database]\nprimary_url = \"postgres://primary-toml:5432/db\"\n\
             url = \"postgres://legacy-toml:5432/db\"\n",
        )
        .unwrap();
        let env =
            |_: &str| -> Result<String, std::env::VarError> { Err(std::env::VarError::NotPresent) };
        let url = resolve_database_url_with_env(env, tmp.path(), "dev").unwrap();
        assert_eq!(url, "postgres://primary-toml:5432/db");
    }

    #[test]
    fn resolve_db_url_ignores_toml_in_wrong_base_dir() {
        // autumn.toml exists only in a different directory; base_dir has none.
        let tmp_with_toml = TempDir::new().unwrap();
        std::fs::write(
            tmp_with_toml.path().join("autumn.toml"),
            "[database]\nurl = \"postgres://wrong:5432/db\"\n",
        )
        .unwrap();
        let tmp_empty = TempDir::new().unwrap();
        let env =
            |_: &str| -> Result<String, std::env::VarError> { Err(std::env::VarError::NotPresent) };
        // Using tmp_empty as base_dir — no autumn.toml there, so must fail.
        assert!(resolve_database_url_with_env(env, tmp_empty.path(), "dev").is_err());
    }

    #[test]
    fn resolve_db_url_uses_profile_specific_section_from_toml() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("autumn.toml"),
            "[database]\nurl = \"postgres://default:5432/db\"\n\
             [profile.demo.database]\nurl = \"postgres://demo:5432/demo_db\"\n",
        )
        .unwrap();
        let env =
            |_: &str| -> Result<String, std::env::VarError> { Err(std::env::VarError::NotPresent) };
        let url = resolve_database_url_with_env(env, tmp.path(), "demo").unwrap();
        assert_eq!(url, "postgres://demo:5432/demo_db");
    }

    #[test]
    fn resolve_db_url_uses_profile_specific_primary_url_from_toml() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("autumn.toml"),
            "[database]\nprimary_url = \"postgres://default:5432/db\"\n\
             [profile.demo.database]\nprimary_url = \"postgres://demo:5432/demo_db\"\n",
        )
        .unwrap();
        let env =
            |_: &str| -> Result<String, std::env::VarError> { Err(std::env::VarError::NotPresent) };
        let url = resolve_database_url_with_env(env, tmp.path(), "demo").unwrap();
        assert_eq!(url, "postgres://demo:5432/demo_db");
    }

    #[test]
    fn resolve_db_url_falls_back_to_top_level_when_profile_section_absent() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("autumn.toml"),
            "[database]\nurl = \"postgres://default:5432/db\"\n",
        )
        .unwrap();
        let env =
            |_: &str| -> Result<String, std::env::VarError> { Err(std::env::VarError::NotPresent) };
        let url = resolve_database_url_with_env(env, tmp.path(), "demo").unwrap();
        assert_eq!(url, "postgres://default:5432/db");
    }
}