autumn-cli 0.10.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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
//! `autumn seed` -- run the project's seed binary to populate the database.
//!
//! Delegates to `cargo run --bin <seed-bin>` after:
//!   1. Verifying `src/bin/seed.rs` exists.
//!   2. Resolving the seed binary's *target name* from `cargo metadata` (the
//!      target may be renamed, e.g. `todo-app-seed`; autumn #2639).
//!   3. Blocking a `--count`/`--model` fake-seed request against a
//!      `prod`/`production` profile unless `--yes-i-mean-prod` is given.
//!   4. 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;

use crate::migrate::is_production_profile_name;

/// 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,

    #[error(
        "`--count` and `--model` must be used together: pass both to generate \
         faked rows (e.g. `autumn seed --count 200 --model Post`), or neither \
         to run the project seed binary"
    )]
    IncompleteFakeFlags,

    #[error(
        "production profile detected; generating faked rows in production requires \
         explicit confirmation\n  Re-run with --yes-i-mean-prod to proceed."
    )]
    ProductionFakeSeedBlocked,
}

/// Resolve the `--count`/`--model` pair into the fake-seed request, if any.
///
/// - Both absent → `Ok(None)`: preserve today's behavior (run the seed binary).
/// - Both present → `Ok(Some((count, model)))`: forward to the seed binary so
///   it generates faked rows for that model.
/// - Exactly one present → [`SeedError::IncompleteFakeFlags`].
fn resolve_fake_request(
    count: Option<usize>,
    model: Option<&str>,
) -> Result<Option<(usize, String)>, SeedError> {
    match (count, model) {
        (None, None) => Ok(None),
        (Some(count), Some(model)) => Ok(Some((count, model.to_owned()))),
        _ => Err(SeedError::IncompleteFakeFlags),
    }
}

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

/// Resolve the seed binary's cargo target name for a project.
///
/// The convention is that the seed binary's source lives at
/// `<project_dir>/src/bin/seed.rs`, but its *target name* may differ from
/// `seed` (e.g. `todo-app-seed` after autumn #2639 renamed colliding example
/// targets). This finds the bin target whose `src_path` is the seed source
/// and returns its name, so `cargo run --bin` invokes the right target.
/// Returns `None` when cargo metadata cannot be read or no such target exists;
/// callers fall back to the conventional `seed` name.
fn resolve_seed_bin_name(project_dir: &Path, package: Option<&str>) -> Option<String> {
    let output = Command::new("cargo")
        .args(["metadata", "--format-version=1", "--no-deps"])
        .current_dir(project_dir)
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let metadata: serde_json::Value = serde_json::from_slice(&output.stdout).ok()?;
    seed_bin_name_from_metadata(&metadata, project_dir, package)
}

/// Pure core of [`resolve_seed_bin_name`]: given parsed `cargo metadata --no-deps`
/// output, find the bin target whose source is `<project_dir>/src/bin/seed.rs`.
fn seed_bin_name_from_metadata(
    metadata: &serde_json::Value,
    project_dir: &Path,
    package: Option<&str>,
) -> Option<String> {
    let seed_src = project_dir.join("src/bin/seed.rs");
    let packages = metadata["packages"].as_array()?;
    let pkg = match package {
        Some(name) => packages.iter().find(|p| p["name"].as_str() == Some(name))?,
        None => packages.iter().find(|p| {
            p["manifest_path"]
                .as_str()
                .and_then(|manifest| Path::new(manifest).parent())
                .is_some_and(|dir| dir == project_dir)
        })?,
    };
    pkg["targets"].as_array()?.iter().find_map(|t| {
        let is_bin = t["kind"]
            .as_array()
            .is_some_and(|kinds| kinds.iter().any(|k| k == "bin"));
        let src_matches = t["src_path"]
            .as_str()
            .is_some_and(|src| Path::new(src) == seed_src);
        if is_bin && src_matches {
            t["name"].as_str().map(str::to_owned)
        } else {
            None
        }
    })
}

/// Guard against accidentally mass-inserting faked rows into a production
/// database. Only fires for an actual fake-seed request (`--count`/`--model`
/// both given) targeting a `prod`/`production` profile without
/// `--yes-i-mean-prod` — a plain `autumn seed` (running the project's own
/// seed binary) is unaffected, matching `autumn migrate`'s existing
/// production guard scope (see `is_production_profile_name`).
fn check_production_guard(
    profile: &str,
    fake_request: Option<&(usize, String)>,
    yes_i_mean_prod: bool,
) -> Result<(), SeedError> {
    if fake_request.is_some() && is_production_profile_name(profile) && !yes_i_mean_prod {
        return Err(SeedError::ProductionFakeSeedBlocked);
    }
    Ok(())
}

/// 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.
///
/// Shared with `autumn console` (see `crate::console`) so both `--package`
/// flags resolve a workspace member the same way.
pub 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`.
///
/// When both `count` and `model` are supplied, the seed binary is asked (via the
/// `AUTUMN_SEED_COUNT`/`AUTUMN_SEED_MODEL` environment variables) to generate
/// that many faked rows for the named model instead of running its hand-written
/// seed body. Supplying only one of the two is an error; supplying neither
/// preserves the original behavior (run the project seed binary).
///
/// A fake-seed request (`--count`/`--model`) targeting a `prod`/`production`
/// profile is blocked unless `yes_i_mean_prod` is set, mirroring `autumn
/// migrate`'s production guard — generating hundreds of faked rows in
/// production by accident (e.g. a copy-pasted `--profile prod`) should require
/// explicit confirmation, not a typo-away default.
pub fn run(
    profile: &str,
    package: Option<&str>,
    count: Option<usize>,
    model: Option<&str>,
    yes_i_mean_prod: bool,
) {
    eprintln!("\u{1F342} autumn seed\n");
    eprintln!("  Profile: {profile}");

    let fake_request = match resolve_fake_request(count, model) {
        Ok(req) => req,
        Err(e) => {
            eprintln!("\u{2717} {e}");
            std::process::exit(1);
        }
    };
    if let Err(e) = check_production_guard(profile, fake_request.as_ref(), yes_i_mean_prod) {
        eprintln!("\u{2717} {e}");
        std::process::exit(1);
    }
    if let Some((count, model)) = &fake_request {
        // Do not claim the rows were created: this command only *delegates* the
        // request to the project's seed binary (via AUTUMN_SEED_COUNT/MODEL).
        // Only a seed binary from a current scaffold — one that calls
        // `autumn_web::seed::maybe_fake_seed` — actually performs the fake seed
        // and reports the real inserted count itself.
        eprintln!(
            "  Requesting fake seed: {count} row(s) of model `{model}` \
             (delegated to the seed binary; requires a seed binary from a \
             current `autumn new` scaffold)"
        );
    }

    // 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");

    // The seed binary's *target* name need not be `seed`: projects may rename
    // the target (autumn #2639 renamed colliding example `seed` targets to
    // `<crate>-seed`) while keeping the conventional `src/bin/seed.rs` path.
    // Resolve the real target name from cargo metadata; fall back to `seed`
    // when metadata is unreadable.
    let seed_bin =
        resolve_seed_bin_name(&project_dir, package).unwrap_or_else(|| "seed".to_owned());
    let mut cmd = Command::new("cargo");
    cmd.args(["run", "--bin", &seed_bin]);
    if let Some(pkg) = package {
        cmd.args(["--package", pkg]);
    }
    cmd.env("AUTUMN_ENV", profile);
    cmd.env("AUTUMN_PROFILE", profile);
    // Forward the fake-seed request (if any) to the seed binary, which
    // dispatches on these vars via `autumn_web::seed::maybe_fake_seed`. When no
    // request was made, explicitly *remove* these vars from the child's
    // environment so a stray ambient `AUTUMN_SEED_MODEL`/`AUTUMN_SEED_COUNT`
    // inherited by this process can't silently trigger a fake seed the user did
    // not ask for.
    if let Some((count, model)) = &fake_request {
        cmd.env("AUTUMN_SEED_COUNT", count.to_string());
        cmd.env("AUTUMN_SEED_MODEL", model);
    } else {
        cmd.env_remove("AUTUMN_SEED_COUNT");
        cmd.env_remove("AUTUMN_SEED_MODEL");
    }
    // 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}"
        );
    }

    // ── check_production_guard (production-fake-seed confirmation) ──────────

    #[test]
    fn production_guard_blocks_fake_seed_without_confirmation() {
        let req = Some((200, "Post".to_string()));
        assert_eq!(
            check_production_guard("prod", req.as_ref(), false),
            Err(SeedError::ProductionFakeSeedBlocked)
        );
    }

    #[test]
    fn production_guard_accepts_production_spelling() {
        let req = Some((200, "Post".to_string()));
        assert_eq!(
            check_production_guard("production", req.as_ref(), false),
            Err(SeedError::ProductionFakeSeedBlocked)
        );
    }

    #[test]
    fn production_guard_is_case_insensitive() {
        let req = Some((200, "Post".to_string()));
        assert_eq!(
            check_production_guard("PROD", req.as_ref(), false),
            Err(SeedError::ProductionFakeSeedBlocked)
        );
    }

    #[test]
    fn production_guard_allows_fake_seed_with_confirmation() {
        let req = Some((200, "Post".to_string()));
        assert_eq!(check_production_guard("prod", req.as_ref(), true), Ok(()));
    }

    #[test]
    fn production_guard_allows_non_production_profiles() {
        let req = Some((200, "Post".to_string()));
        assert_eq!(check_production_guard("dev", req.as_ref(), false), Ok(()));
        assert_eq!(check_production_guard("demo", req.as_ref(), false), Ok(()));
    }

    #[test]
    fn production_guard_ignores_plain_seed_without_fake_request() {
        // No --count/--model: running the project's own seed binary against
        // prod is unaffected by this guard (existing, unrelated behavior).
        assert_eq!(check_production_guard("prod", None, false), Ok(()));
    }

    #[test]
    fn production_fake_seed_blocked_error_mentions_flag() {
        let msg = SeedError::ProductionFakeSeedBlocked.to_string();
        assert!(
            msg.contains("--yes-i-mean-prod"),
            "error should mention --yes-i-mean-prod, got: {msg}"
        );
    }

    // ── resolve_fake_request (--count / --model, #1343 AC4) ─────────────────

    #[test]
    fn resolve_fake_request_none_when_both_absent() {
        assert_eq!(resolve_fake_request(None, None), Ok(None));
    }

    #[test]
    fn resolve_fake_request_some_when_both_present() {
        assert_eq!(
            resolve_fake_request(Some(200), Some("Post")),
            Ok(Some((200, "Post".to_string())))
        );
    }

    #[test]
    fn resolve_fake_request_errors_on_count_without_model() {
        assert_eq!(
            resolve_fake_request(Some(200), None),
            Err(SeedError::IncompleteFakeFlags)
        );
    }

    #[test]
    fn resolve_fake_request_errors_on_model_without_count() {
        assert_eq!(
            resolve_fake_request(None, Some("Post")),
            Err(SeedError::IncompleteFakeFlags)
        );
    }

    #[test]
    fn incomplete_fake_flags_error_is_actionable() {
        let msg = SeedError::IncompleteFakeFlags.to_string();
        assert!(
            msg.contains("--count") && msg.contains("--model"),
            "error should mention both flags, 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));
    }

    // ── seed_bin_name_from_metadata ───────────────────────────────────────

    fn seed_metadata() -> serde_json::Value {
        serde_json::json!({
            "packages": [
                {
                    "name": "todo-app",
                    "manifest_path": "/projects/todo-app/Cargo.toml",
                    "targets": [
                        { "name": "todo-app-seed", "kind": ["bin"], "src_path": "/projects/todo-app/src/bin/seed.rs" },
                        { "name": "todo-app", "kind": ["bin"], "src_path": "/projects/todo-app/src/main.rs" }
                    ]
                },
                {
                    "name": "other",
                    "manifest_path": "/projects/other/Cargo.toml",
                    "targets": [
                        { "name": "seed", "kind": ["bin"], "src_path": "/projects/other/src/bin/seed.rs" }
                    ]
                }
            ]
        })
    }

    #[test]
    fn seed_bin_name_resolves_renamed_target_by_src_path() {
        // Regression for autumn #2639: the target name may differ from `seed`.
        let name =
            seed_bin_name_from_metadata(&seed_metadata(), Path::new("/projects/todo-app"), None);
        assert_eq!(name.as_deref(), Some("todo-app-seed"));
    }

    #[test]
    fn seed_bin_name_resolves_conventional_seed_target() {
        let name =
            seed_bin_name_from_metadata(&seed_metadata(), Path::new("/projects/other"), None);
        assert_eq!(name.as_deref(), Some("seed"));
    }

    #[test]
    fn seed_bin_name_package_filter_selects_the_package() {
        // With --package, run() resolves project_dir to the package's own
        // directory via find_package_dir, so pass that directory here.
        let name = seed_bin_name_from_metadata(
            &seed_metadata(),
            Path::new("/projects/todo-app"),
            Some("todo-app"),
        );
        assert_eq!(name.as_deref(), Some("todo-app-seed"));
    }

    #[test]
    fn seed_bin_name_returns_none_when_project_has_no_seed_target() {
        let name =
            seed_bin_name_from_metadata(&seed_metadata(), Path::new("/projects/missing"), None);
        assert_eq!(name, None);
    }

    #[test]
    fn seed_bin_name_ignores_non_bin_seed_target() {
        let metadata = serde_json::json!({
            "packages": [{
                "name": "lib-only",
                "manifest_path": "/projects/lib-only/Cargo.toml",
                "targets": [
                    { "name": "seed", "kind": ["lib"], "src_path": "/projects/lib-only/src/bin/seed.rs" }
                ]
            }]
        });
        let name = seed_bin_name_from_metadata(&metadata, Path::new("/projects/lib-only"), None);
        assert_eq!(name, None);
    }

    // ── 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");
    }
}