cratefield-cli 0.6.3

The fz CLI for Cratefield ventures: migrations collect/apply, doctor, modules, push
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
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
//! `fz import supabase inspect` (issue #658, ADR 0026): connects read-only
//! to a Supabase project and writes the migration report.
//!
//! `--dispositions <FILE>` decides the report's needs-work and blocker items
//! from a TOML file (ADR 0026, Decision 5);
//! `fz import supabase dispositions init` writes a skeleton of that file.
//!
//! The engine is `cratefield-import-supabase`, which reads Postgres through
//! sqlx and so is native-only. It is behind the `import-supabase` feature
//! for the reason `postgres` and `push-send` are: a venture links this
//! crate beside a wasm build, and that graph must never see sqlx or tokio.
//! Without the feature the command exists and says what to install — loud
//! absence, not a silently smaller `fz`.
//!
//! **Credentials.** The database URL comes from `--db-url` or
//! `SUPABASE_DB_URL`, the Management API token from `--management-token`
//! or `SUPABASE_ACCESS_TOKEN`, and `--classify` reads `TYPESAFE_API_KEY`
//! through the `TypeSafe` adapter's own `from_env`. `fz` never prompts (ADR
//! 0026, Decision 6), so a missing URL is a refusal naming the variable.
//! The values are held cleared-on-drop, never printed, and the report names
//! the database by host and database alone.

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

use crate::EnvVars;
use cratefield_core::Config;

/// The environment variable the database URL is read from.
pub const DB_URL_VAR: &str = "SUPABASE_DB_URL";
/// The environment variable the Management API token is read from.
pub const ACCESS_TOKEN_VAR: &str = "SUPABASE_ACCESS_TOKEN";
/// The environment variable the target Postgres URL is read from by
/// default: the harness's own app-database variable, the one a venture's
/// native runtime reads (`crates/runtime-native/README.md`).
pub const DEFAULT_TARGET_ENV: &str = "DATABASE_URL";

/// The report format.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Format {
    /// Markdown, for a person.
    Markdown,
    /// JSON, for the later steps and the dashboard.
    Json,
}

/// Everything `fz import supabase inspect` was given.
#[derive(Debug, Clone)]
pub struct InspectArgs {
    /// The project ref.
    pub project: String,
    /// `--db-url`, if given.
    pub db_url: Option<String>,
    /// `--management-token`, if given.
    pub management_token: Option<String>,
    /// The format.
    pub format: Format,
    /// `--out`, if given.
    pub out: Option<PathBuf>,
    /// `--transfer-mbps`.
    pub transfer_mbps: u32,
    /// `--classify`.
    pub classify: bool,
    /// `--classify-threshold`.
    pub classify_threshold: f32,
    /// `--dispositions`, if given: the file applied to the report.
    pub dispositions: Option<PathBuf>,
}

/// Everything `fz import supabase dispositions init` was given.
#[derive(Debug, Clone)]
pub struct DispositionsInitArgs {
    /// The project ref.
    pub project: String,
    /// `--db-url`, if given.
    pub db_url: Option<String>,
    /// `--management-token`, if given.
    pub management_token: Option<String>,
    /// `--out`: where the skeleton goes.
    pub out: PathBuf,
    /// `--force`: overwrite an existing file.
    pub force: bool,
    /// `--dispositions`: skip items this file already decides.
    pub dispositions: Option<PathBuf>,
}

impl DispositionsInitArgs {
    /// The inspect args that reach the same project, for the shared
    /// credential and report code. Only the engine build inspects.
    #[cfg(feature = "import-supabase")]
    fn as_inspect(&self) -> InspectArgs {
        InspectArgs {
            project: self.project.clone(),
            db_url: self.db_url.clone(),
            management_token: self.management_token.clone(),
            format: Format::Markdown,
            out: None,
            transfer_mbps: 100,
            classify: false,
            classify_threshold: 0.8,
            dispositions: None,
        }
    }
}

/// Where each credential came from — the flag or the environment — with
/// the value itself never leaving this struct.
#[derive(Debug)]
pub struct Credentials {
    /// The database URL.
    pub db_url: Secret,
    /// The Management API token, if any.
    pub management_token: Option<Secret>,
    /// Notes for stderr: a credential given as a flag is in the shell
    /// history and the process list.
    pub notes: Vec<String>,
}

/// A string that prints as `[redacted]`. The engine has its own; this one
/// exists so the argument handling compiles without the feature.
#[derive(Clone)]
pub struct Secret(zeroize::Zeroizing<String>);

impl Secret {
    /// The value. Named `expose` so a reader has to notice.
    #[must_use]
    pub fn expose(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Debug for Secret {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("[redacted]")
    }
}

/// Resolves the credentials from the flags, then `config` (the
/// environment). Never prompts.
///
/// # Errors
///
/// A refusal naming `SUPABASE_DB_URL` when no URL was given either way.
pub fn credentials(args: &InspectArgs, config: &dyn Config) -> Result<Credentials, String> {
    resolve(
        args.db_url.as_deref(),
        args.management_token.as_deref(),
        config,
    )
}

/// [`credentials`] without an [`InspectArgs`], so the plan run reuses it.
fn resolve(
    db_url: Option<&str>,
    management_token: Option<&str>,
    config: &dyn Config,
) -> Result<Credentials, String> {
    let (db_url, note) = source_db_url(db_url, config)?;
    let mut notes = note.into_iter().collect::<Vec<_>>();
    let management_token = match management_token {
        Some(token) => {
            notes.push(format!(
                "note: --management-token puts the token in your shell history and the process \
                 list; prefer {ACCESS_TOKEN_VAR}"
            ));
            Some(token.to_owned())
        }
        None => config.get(ACCESS_TOKEN_VAR),
    };
    Ok(Credentials {
        db_url,
        management_token: management_token.map(|token| Secret(zeroize::Zeroizing::new(token))),
        notes,
    })
}

/// Resolves the source database URL from `--db-url`, then [`DB_URL_VAR`] in
/// `config`. Never prompts. Shared by `inspect` and `fz import supabase
/// users` (#659), which read the same source through the same variable.
///
/// Returns the note a flag earns, if any: a flag is in the shell history
/// and the process list.
///
/// # Errors
///
/// A refusal naming [`DB_URL_VAR`] when no URL was given either way.
pub fn source_db_url(
    db_url: Option<&str>,
    config: &dyn Config,
) -> Result<(Secret, Option<String>), String> {
    match db_url {
        Some(url) => Ok((
            Secret(zeroize::Zeroizing::new(url.to_owned())),
            Some(format!(
                "note: --db-url puts the password in your shell history and the process list; \
                 prefer {DB_URL_VAR}"
            )),
        )),
        None => config.get(DB_URL_VAR).map_or_else(
            || {
                Err(format!(
                    "no database URL: set {DB_URL_VAR} to the read-only role's connection string \
                     (docs/import/supabase.md), or pass --db-url. fz never prompts"
                ))
            },
            |url| Ok((Secret(zeroize::Zeroizing::new(url)), None)),
        ),
    }
}

/// Runs the command: inspects, then writes the report to `--out` or
/// stdout.
///
/// # Errors
///
/// A refusal or an access error (connection, permission, a refused token):
/// the exit code is non-zero for those alone. Blockers are in the report
/// and the exit code is zero.
pub fn inspect(args: &InspectArgs) -> Result<(), String> {
    let credentials = credentials(args, &EnvVars)?;
    for note in &credentials.notes {
        eprintln!("{note}");
    }
    let rendered = run(args, &credentials)?;
    if let Some(path) = &args.out {
        write_report(path, &rendered.text)?;
        eprintln!("wrote {}: {}", path.display(), rendered.summary);
    } else {
        print!("{}", rendered.text);
    }
    Ok(())
}

fn write_report(path: &Path, text: &str) -> Result<(), String> {
    std::fs::write(path, text).map_err(|err| format!("cannot write {}: {err}", path.display()))
}

/// The rendered report and its one-line summary.
pub struct Rendered {
    /// The report in the requested format.
    pub text: String,
    /// `N automatic, N needs work, N blockers, N undecided`.
    pub summary: String,
}

/// The refusal every command prints when `fz` was built without the engine.
#[cfg(not(feature = "import-supabase"))]
const WITHOUT_FEATURE: &str = "this `fz` was built without the `import-supabase` feature, so it \
     cannot reach Postgres. Install one that has it — `cargo install cratefield-cli --features \
     import-supabase` — and run that binary (it needs no compiled-in harness).";

/// Runs `dispositions init`: inspects, then writes the skeleton file.
///
/// # Errors
///
/// A refusal — an existing file without `--force`, a bad dispositions file, a
/// connection or permission error.
pub fn dispositions_init(args: &DispositionsInitArgs) -> Result<(), String> {
    // Without the engine there is nothing to inspect, so refuse before the
    // overwrite and credential checks (which would otherwise be reached).
    #[cfg(not(feature = "import-supabase"))]
    {
        let _ = args;
        Err(WITHOUT_FEATURE.to_owned())
    }

    #[cfg(feature = "import-supabase")]
    {
        if args.out.exists() && !args.force {
            return Err(format!(
                "{} exists; pass --force to overwrite it",
                args.out.display()
            ));
        }
        let inspect_args = args.as_inspect();
        let credentials = credentials(&inspect_args, &EnvVars)?;
        for note in &credentials.notes {
            eprintln!("{note}");
        }
        write_skeleton(&inspect_args, &credentials, args)
    }
}

#[cfg(feature = "import-supabase")]
fn write_skeleton(
    inspect_args: &InspectArgs,
    credentials: &Credentials,
    args: &DispositionsInitArgs,
) -> Result<(), String> {
    use cratefield_import_supabase as engine;

    let mut report = inspect_report(inspect_args, credentials)?;
    if let Some(path) = &args.dispositions {
        let file = engine::DispositionsFile::load(path).map_err(|error| error.to_string())?;
        engine::apply_dispositions(&mut report, &file);
    }
    let text = engine::skeleton(&report);
    if let Some(parent) = args
        .out
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
    {
        std::fs::create_dir_all(parent)
            .map_err(|error| format!("cannot create {}: {error}", parent.display()))?;
    }
    std::fs::write(&args.out, &text)
        .map_err(|error| format!("cannot write {}: {error}", args.out.display()))?;
    println!(
        "{} undecided item(s) written to {}",
        report.summary.undecided,
        args.out.display()
    );
    Ok(())
}

#[cfg(feature = "import-supabase")]
fn engine_options(
    project: &str,
    credentials: &Credentials,
    transfer_mbps: u32,
    classify: bool,
    classify_threshold: f32,
) -> Result<cratefield_import_supabase::InspectOptions, String> {
    use cratefield_import_supabase as engine;
    use std::sync::Arc;

    let clock: Arc<dyn cratefield_core::Clock> = Arc::new(cratefield_runtime_native::TokioClock);
    let http: Arc<dyn cratefield_core::HttpClient> =
        Arc::new(cratefield_core::BoundedHttpClient::new(
            Arc::new(cratefield_runtime_native::ReqwestClient::new()),
            Arc::clone(&clock),
        ));
    let mut options = engine::InspectOptions::new(
        project.to_owned(),
        engine::Secret::new(credentials.db_url.expose()),
    );
    options.transfer_mbps = transfer_mbps;
    options.classify_threshold = classify_threshold;
    options.management = credentials.management_token.as_ref().map(|token| {
        engine::ManagementApi::new(
            Arc::clone(&http),
            engine::DEFAULT_API_BASE,
            engine::Secret::new(token.expose()),
        )
    });
    if classify {
        // TypeSafe (its judge, Jev) through the adapter's own reader, so
        // the key's name is the adapter's, not ours.
        let classifier =
            cratefield_adapter_typesafe::TypeSafe::from_env(Arc::clone(&http), Arc::clone(&clock))
                .ok_or_else(|| {
                    "--classify needs TYPESAFE_API_KEY (the TypeSafe adapter reads it); without \
                     it, drop --classify and unplaced policies stay needs_review"
                        .to_owned()
                })?;
        options.classifier = Some(Arc::new(classifier));
    }
    Ok(options)
}

#[cfg(feature = "import-supabase")]
fn inspect_report(
    args: &InspectArgs,
    credentials: &Credentials,
) -> Result<cratefield_import_supabase::Report, String> {
    use cratefield_import_supabase as engine;

    let options = engine_options(
        &args.project,
        credentials,
        args.transfer_mbps,
        args.classify,
        args.classify_threshold,
    )?;
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|err| format!("cannot start the async runtime inspect needs: {err}"))?;
    let mut report = runtime
        .block_on(engine::inspect(&options))
        .map_err(|error| error.to_string())?;
    if let Some(path) = &args.dispositions {
        let file = engine::DispositionsFile::load(path).map_err(|error| error.to_string())?;
        engine::apply_dispositions(&mut report, &file);
    }
    Ok(report)
}

#[cfg(feature = "import-supabase")]
fn run(args: &InspectArgs, credentials: &Credentials) -> Result<Rendered, String> {
    let report = inspect_report(args, credentials)?;
    let s = &report.summary;
    let summary = format!(
        "{} automatic, {} needs work, {} blocker(s), {} undecided{}",
        s.automatic,
        s.needs_work,
        s.blockers,
        s.undecided,
        if s.ready { "" } else { " — not ready" }
    );
    Ok(Rendered {
        text: match args.format {
            Format::Json => report.to_json(),
            Format::Markdown => report.to_markdown(),
        },
        summary,
    })
}

#[cfg(not(feature = "import-supabase"))]
fn run(_args: &InspectArgs, _credentials: &Credentials) -> Result<Rendered, String> {
    // As with `push-send`: an installed binary, never a feature on the
    // venture's dependency, whose wasm build must not see sqlx.
    Err(WITHOUT_FEATURE.to_owned())
}

/// Everything the bare `fz import supabase` and `fz import supabase plan`
/// were given (issue #728).
#[derive(Debug, Clone)]
pub struct PlanArgs {
    /// The project ref.
    pub project: String,
    /// `--db-url`, if given.
    pub db_url: Option<String>,
    /// `--management-token`, if given.
    pub management_token: Option<String>,
    /// `--target-env`: the variable the target Postgres URL is read from.
    pub target_env: String,
    /// `--dir`: where `report.json`, `report.md` and `plan.json` go.
    pub dir: PathBuf,
    /// `--transfer-mbps`.
    pub transfer_mbps: u32,
    /// `--classify`.
    pub classify: bool,
    /// `--classify-threshold`.
    pub classify_threshold: f32,
    /// `--apply`: apply an approved plan instead of writing one.
    pub apply: bool,
    /// `--plan`: the plan file to apply.
    pub plan: Option<PathBuf>,
}

/// Runs the command: inspects the source read-only, reads the target
/// read-only, and either writes `report.json`, `report.md` and `plan.json`
/// to `--dir`, or re-checks an approved plan with `--apply --plan`.
///
/// # Errors
///
/// A refusal or an access error. Blockers are in the plan and the exit code
/// is zero; `--apply` fails (non-zero) on an unknown plan version, a
/// project mismatch, drift or a remaining blocker.
pub fn plan(args: &PlanArgs) -> Result<(), String> {
    let credentials = resolve(
        args.db_url.as_deref(),
        args.management_token.as_deref(),
        &EnvVars,
    )?;
    for note in &credentials.notes {
        eprintln!("{note}");
    }
    run_plan(args, &credentials)
}

#[cfg(feature = "import-supabase")]
fn run_plan(args: &PlanArgs, credentials: &Credentials) -> Result<(), String> {
    use cratefield_import_supabase as engine;

    let options = engine_options(
        &args.project,
        credentials,
        args.transfer_mbps,
        args.classify,
        args.classify_threshold,
    )?;
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|err| format!("cannot start the async runtime the plan needs: {err}"))?;
    runtime.block_on(async {
        if args.apply {
            let path = args
                .plan
                .as_ref()
                .ok_or_else(|| "--apply needs --plan <FILE>".to_owned())?;
            return apply_plan(args, path, &options).await;
        }
        let report = engine::inspect(&options)
            .await
            .map_err(|error| error.to_string())?;
        let target = match EnvVars.get(&args.target_env) {
            Some(url) => Some(
                engine::read_target(&engine::Secret::new(url))
                    .await
                    .map_err(|error| format!("could not read the target database: {error}"))?,
            ),
            None => None,
        };
        let plan = engine::build_plan(&report, target.as_ref());
        std::fs::create_dir_all(&args.dir)
            .map_err(|err| format!("cannot create {}: {err}", args.dir.display()))?;
        write_report(&args.dir.join("report.json"), &report.to_json())?;
        write_report(&args.dir.join("report.md"), &report.to_markdown())?;
        write_report(&args.dir.join("plan.json"), &plan.to_json())?;
        eprintln!(
            "wrote {}/report.json, report.md and plan.json: {} blocker(s) in the plan",
            args.dir.display(),
            plan.blockers.len()
        );
        for blocker in &plan.blockers {
            eprintln!("  blocker {}: {}", blocker.code, blocker.message);
        }
        Ok(())
    })
}

/// `--apply --plan FILE`: re-inspects and refuses unless the plan still
/// matches. It writes nothing: the auth-users and data phases land with
/// #659/#660.
#[cfg(feature = "import-supabase")]
async fn apply_plan(
    args: &PlanArgs,
    path: &Path,
    options: &cratefield_import_supabase::InspectOptions,
) -> Result<(), String> {
    use cratefield_import_supabase as engine;

    let text = std::fs::read_to_string(path)
        .map_err(|err| format!("cannot read {}: {err}", path.display()))?;
    let plan: engine::Plan = serde_json::from_str(&text)
        .map_err(|err| format!("{} is not a plan file: {err}", path.display()))?;
    if plan.plan_version != engine::PLAN_VERSION {
        return Err(format!(
            "{} is a version {} plan, and this fz applies version {}; re-plan with `fz import \
             supabase plan`",
            path.display(),
            plan.plan_version,
            engine::PLAN_VERSION
        ));
    }
    if plan.project.project_ref != args.project {
        return Err(format!(
            "{} is a plan for project {}, not {}; re-plan with `fz import supabase plan --project \
             {}`",
            path.display(),
            plan.project.project_ref,
            args.project,
            args.project
        ));
    }
    let report = engine::inspect(options)
        .await
        .map_err(|error| error.to_string())?;
    engine::check_drift(&plan, &report).map_err(|drift| drift.to_string())?;
    if !plan.blockers.is_empty() {
        let codes: Vec<&str> = plan.blockers.iter().map(|b| b.code.as_str()).collect();
        return Err(format!(
            "the plan still has {} blocker(s) ({}); resolve them and re-plan",
            plan.blockers.len(),
            codes.join(", ")
        ));
    }
    eprintln!(
        "the plan matches the source ({}); the auth-users and data phases land with #659/#660 — \
         nothing was written to the target",
        plan.inspection_hash
    );
    Ok(())
}

#[cfg(not(feature = "import-supabase"))]
fn run_plan(_args: &PlanArgs, _credentials: &Credentials) -> Result<(), String> {
    Err(
        // The same refusal `inspect` gives without the engine.
        "this `fz` was built without the `import-supabase` feature, so it cannot reach Postgres. \
         Install one that has it — `cargo install cratefield-cli --features import-supabase` — \
         and run that binary (it needs no compiled-in harness)."
            .to_owned(),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::BTreeMap;

    struct Vars(BTreeMap<&'static str, &'static str>);

    impl Config for Vars {
        fn get(&self, key: &str) -> Option<String> {
            self.0.get(key).map(|value| (*value).to_owned())
        }
    }

    fn args() -> InspectArgs {
        InspectArgs {
            project: "abcdefghijklmnopqrst".to_owned(),
            db_url: None,
            management_token: None,
            format: Format::Markdown,
            out: None,
            transfer_mbps: 100,
            classify: false,
            classify_threshold: 0.8,
            dispositions: None,
        }
    }

    #[test]
    fn a_missing_url_is_a_refusal_not_a_prompt() {
        let error = credentials(&args(), &Vars(BTreeMap::new())).unwrap_err();
        assert!(error.contains(DB_URL_VAR), "{error}");
        assert!(error.contains("never prompts"), "{error}");
    }

    #[test]
    fn the_environment_is_read_and_never_printed() {
        let vars = Vars(BTreeMap::from([
            (DB_URL_VAR, "postgres://ro:hunter2@db.example.test/postgres"),
            (ACCESS_TOKEN_VAR, "sbp_secret_token"),
        ]));
        let credentials = credentials(&args(), &vars).expect("resolved");
        assert!(credentials.notes.is_empty());
        assert!(credentials.management_token.is_some());
        let debug = format!("{credentials:?}");
        assert!(
            !debug.contains("hunter2") && !debug.contains("sbp_"),
            "{debug}"
        );
    }

    #[test]
    fn a_flag_wins_and_earns_a_note() {
        let mut given = args();
        given.db_url = Some("postgres://ro:hunter2@db.example.test/postgres".to_owned());
        let vars = Vars(BTreeMap::from([(DB_URL_VAR, "postgres://other")]));
        let credentials = credentials(&given, &vars).expect("resolved");
        assert_eq!(
            credentials.db_url.expose(),
            "postgres://ro:hunter2@db.example.test/postgres"
        );
        assert_eq!(credentials.notes.len(), 1);
        assert!(!credentials.notes[0].contains("hunter2"));
    }

    #[test]
    #[cfg(not(feature = "import-supabase"))]
    fn without_the_feature_the_refusal_names_the_install() {
        let mut given = args();
        given.db_url = Some("postgres://ro:hunter2@db.example.test/postgres".to_owned());
        let error = inspect(&given).unwrap_err();
        assert!(
            error.contains("cargo install cratefield-cli --features import-supabase"),
            "{error}"
        );
        assert!(!error.contains("hunter2"));
    }

    #[test]
    #[cfg(feature = "import-supabase")]
    fn dispositions_init_refuses_to_overwrite_without_force() {
        let dir = std::env::temp_dir().join(format!("fz-dispositions-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("a temp dir");
        let out = dir.join("supabase-dispositions.toml");
        std::fs::write(&out, "# mine\n").expect("write");
        let given = DispositionsInitArgs {
            project: "abcdefghijklmnopqrst".to_owned(),
            db_url: None,
            management_token: None,
            out: out.clone(),
            force: false,
            dispositions: None,
        };
        let error = dispositions_init(&given).unwrap_err();
        assert!(error.contains("--force"), "{error}");
        assert!(error.contains(&out.display().to_string()), "{error}");
        // It left the file alone.
        assert_eq!(std::fs::read_to_string(&out).expect("read"), "# mine\n");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    #[cfg(feature = "import-supabase")]
    fn an_unreachable_database_is_an_error_that_quotes_no_secret() {
        let mut given = args();
        given.db_url = Some("postgres://ro:hunter2@127.0.0.1:1/postgres".to_owned());
        let error = inspect(&given).unwrap_err();
        assert!(error.contains("could not connect"), "{error}");
        assert!(!error.contains("hunter2"), "{error}");
    }
}