rustango 0.60.0

Batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
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
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
//! `manage menu` — numbered choices over the tenancy verbs.
//!
//! There are 42 verbs. Reading `--help` tells you they exist; it does not
//! help you run one you have never run before. The menu lists them by group,
//! asks only for what the verb will not ask for itself, echoes the command it
//! is about to run, and comes back for the next action.
//!
//! ## Why the catalog is small
//!
//! Most verbs already prompt for their own required values on a terminal —
//! `create-tenant` asks for a slug, `create-operator` asks for a username and
//! reads the password without echoing it (`manage_interactive`). Re-asking
//! here would duplicate that and, for passwords, do it worse. So [`Action`]
//! carries only the options a verb will *not* prompt for: `--days`,
//! `--mode`, `--generate`. Everything else is left to the verb.
//!
//! Each pick re-enters [`super::dispatch`], so the menu cannot drift from
//! what the flags do — same code path, different front end.

use std::io::Write;

use crate::manage_interactive::LineSource;
use std::path::Path;

use crate::tenancy::error::TenancyError;
use crate::tenancy::pools::TenantPools;

use super::wizard::{prompt_value, prompt_yes_no};
use super::InitTenancyFn;

/// An option the menu asks about, appended to the argv when answered.
enum Ask {
    /// `--name <value>`; skipped when the answer is empty.
    Value {
        flag: &'static str,
        label: &'static str,
        default: Option<&'static str>,
    },
    /// `--name`; appended only when the answer is yes.
    Toggle {
        flag: &'static str,
        question: &'static str,
    },
    /// One of two flags, always appended — for a verb that refuses to guess
    /// a direction, where "no answer" is not a valid argv.
    Either {
        question: &'static str,
        yes: &'static str,
        no: &'static str,
    },
}

struct Action {
    verb: &'static str,
    about: &'static str,
    asks: &'static [Ask],
}

struct Group {
    title: &'static str,
    actions: &'static [Action],
}

const GROUPS: &[Group] = &[
    Group {
        title: "TENANTS",
        actions: &[
            Action {
                verb: "list-tenants",
                about: "every tenant in the registry",
                asks: &[],
            },
            Action {
                verb: "create-tenant",
                about: "provision a new tenant",
                asks: &[
                    Ask::Value {
                        flag: "--mode",
                        label: "storage mode (schema|database)",
                        default: Some("schema"),
                    },
                    Ask::Value {
                        flag: "--display-name",
                        label: "display name (blank to skip)",
                        default: None,
                    },
                    Ask::Value {
                        flag: "--host-pattern",
                        label: "host pattern (blank to skip)",
                        default: None,
                    },
                ],
            },
            Action {
                verb: "edit-tenant",
                about: "change routing and display config",
                asks: &[
                    Ask::Value {
                        flag: "--display-name",
                        label: "display name (blank to leave alone)",
                        default: None,
                    },
                    Ask::Value {
                        flag: "--host-pattern",
                        label: "host pattern (blank to leave alone)",
                        default: None,
                    },
                ],
            },
            Action {
                verb: "drop-tenant",
                about: "soft-delete a tenant; data preserved",
                asks: &[],
            },
            Action {
                verb: "purge-tenant",
                about: "HARD-delete a tenant and its schema",
                asks: &[Ask::Toggle {
                    flag: "--purge-database",
                    question: "also drop the tenant's database?",
                }],
            },
            Action {
                verb: "test-tenant-connection",
                about: "check a database URL before using it",
                asks: &[],
            },
        ],
    },
    Group {
        title: "INSPECTION",
        actions: &[
            Action {
                verb: "list-runs",
                about: "recent provisioning and migration runs",
                asks: &[Ask::Value {
                    flag: "--kind",
                    label: "kind (provision|migrate, blank for both)",
                    default: None,
                }],
            },
            Action {
                verb: "show-run",
                about: "one run's steps, from the recorded events",
                asks: &[],
            },
            Action {
                verb: "audit-log",
                about: "who changed what in the registry, and when",
                asks: &[Ask::Value {
                    flag: "--table",
                    label: "table (blank for all)",
                    default: None,
                }],
            },
        ],
    },
    Group {
        title: "HOSTNAMES",
        actions: &[
            Action {
                verb: "list-hosts",
                about: "every hostname a tenant answers on",
                asks: &[],
            },
            Action {
                verb: "add-host",
                about: "bind an extra hostname to a tenant",
                asks: &[],
            },
            Action {
                verb: "remove-host",
                about: "unbind one",
                asks: &[],
            },
            Action {
                verb: "set-host-enabled",
                about: "park or serve a bound hostname",
                asks: &[Ask::Either {
                    question: "serve it? (no parks it)",
                    yes: "--on",
                    no: "--off",
                }],
            },
        ],
    },
    Group {
        title: "OPERATORS AND USERS",
        actions: &[
            Action {
                verb: "list-operators",
                about: "every operator and whether they are active",
                asks: &[],
            },
            Action {
                verb: "create-operator",
                about: "an apex-level account for the operator console",
                asks: &[Ask::Toggle {
                    flag: "--generate",
                    question: "generate a password instead of choosing one?",
                }],
            },
            Action {
                verb: "set-operator-active",
                about: "turn an operator's access off or back on",
                asks: &[Ask::Either {
                    question: "activate them? (no deactivates)",
                    yes: "--on",
                    no: "--off",
                }],
            },
            Action {
                verb: "reset-operator-password",
                about: "reset an operator's password",
                asks: &[Ask::Toggle {
                    flag: "--generate",
                    question: "generate the new password?",
                }],
            },
            Action {
                verb: "create-user",
                about: "a tenant-scoped user",
                asks: &[
                    Ask::Toggle {
                        flag: "--superuser",
                        question: "make them a superuser?",
                    },
                    Ask::Toggle {
                        flag: "--generate",
                        question: "generate a password instead of choosing one?",
                    },
                ],
            },
            Action {
                verb: "set-superuser",
                about: "promote or demote a tenant user",
                asks: &[Ask::Toggle {
                    flag: "--off",
                    question: "demote instead of promote?",
                }],
            },
            Action {
                verb: "reset-password",
                about: "reset a tenant user's password",
                asks: &[Ask::Toggle {
                    flag: "--generate",
                    question: "generate the new password?",
                }],
            },
        ],
    },
    Group {
        title: "ROLES AND PERMISSIONS",
        actions: &[
            Action {
                verb: "list-roles",
                about: "roles defined for a tenant",
                asks: &[],
            },
            Action {
                verb: "create-role",
                about: "define a new role",
                asks: &[],
            },
            Action {
                verb: "assign-role",
                about: "give a user a role",
                asks: &[],
            },
            Action {
                verb: "revoke-role",
                about: "take a role away",
                asks: &[],
            },
            Action {
                verb: "seed-permissions",
                about: "create the built-in permission rows",
                asks: &[],
            },
        ],
    },
    Group {
        title: "MIGRATIONS AND MAINTENANCE",
        actions: &[
            Action {
                verb: "migrate",
                about: "apply migrations: registry first, then every tenant",
                asks: &[],
            },
            Action {
                verb: "migrate-registry",
                about: "the registry database only",
                asks: &[],
            },
            Action {
                verb: "migrate-tenants",
                about: "every active tenant",
                asks: &[],
            },
            Action {
                verb: "audit-cleanup",
                about: "trim old audit-log entries",
                asks: &[Ask::Value {
                    flag: "--days",
                    label: "delete entries older than (days)",
                    default: Some("90"),
                }],
            },
            Action {
                verb: "prewarm-pools",
                about: "open a connection per tenant up front",
                asks: &[],
            },
            Action {
                verb: "wizard",
                about: "guided first-time setup",
                asks: &[],
            },
        ],
    },
];

/// Loop: show the menu, run one verb, come back. Ends on `q` or EOF.
pub(super) async fn menu_cmd<R: LineSource + ?Sized, W: Write + Send, DB: sqlx::Database>(
    pools: &TenantPools<DB>,
    registry_url: &str,
    dir: &Path,
    init_fn: InitTenancyFn,
    reader: &mut R,
    writer: &mut W,
) -> Result<(), TenancyError>
where
    crate::sql::Pool: From<sqlx::Pool<DB>>,
{
    let flat = flatten();
    loop {
        write_menu(writer, &flat)?;
        let Some(action) = pick(reader, writer, &flat)? else {
            writeln!(writer)?;
            return Ok(());
        };

        let argv = build_argv(action, reader, writer)?;
        writeln!(writer)?;
        writeln!(writer, "  Same thing without the menu:")?;
        writeln!(writer, "    cargo run -- {}", argv.join(" "))?;
        writeln!(writer)?;

        // Same match the flags go through — boxed because this is the one
        // place dispatch is re-entered from inside itself.
        let outcome = Box::pin(super::dispatch(
            pools,
            registry_url,
            dir,
            argv,
            writer,
            init_fn,
        ))
        .await;

        // A failed verb ends that action, not the session: the operator is
        // sitting right there and the usual answer is to pick again.
        if let Err(e) = outcome {
            writeln!(writer, "  {} failed: {e}", action.verb)?;
        }

        if !prompt_yes_no(reader, writer, "\n  Another action?", true)? {
            return Ok(());
        }
    }
}

/// Every action in menu order, so a typed number maps to one entry.
fn flatten() -> Vec<&'static Action> {
    GROUPS.iter().flat_map(|g| g.actions.iter()).collect()
}

fn write_menu<W: Write>(w: &mut W, flat: &[&Action]) -> Result<(), TenancyError> {
    let width = flat.iter().map(|a| a.verb.len()).max().unwrap_or(0);
    let iw = flat.len().to_string().len();
    writeln!(w)?;
    writeln!(w, "  rustango manage — pick an action")?;
    let mut n = 0;
    for group in GROUPS {
        writeln!(w)?;
        writeln!(w, "  {}", group.title)?;
        for action in group.actions {
            n += 1;
            writeln!(w, "    {n:>iw$}) {:<width$}  {}", action.verb, action.about)?;
        }
    }
    writeln!(w)?;
    writeln!(w, "    {:>iw$}  quit", "q")?;
    writeln!(w, "    {:>iw$}  every other verb: cargo run -- --help", "?")?;
    Ok(())
}

/// Read a choice. `None` means quit (typed `q`, or EOF).
fn pick<'a, R: LineSource + ?Sized, W: Write>(
    reader: &mut R,
    writer: &mut W,
    flat: &[&'a Action],
) -> Result<Option<&'a Action>, TenancyError> {
    loop {
        write!(writer, "\n  > ")?;
        writer.flush()?;
        let mut buf = String::new();
        if reader.read_line_from(&mut buf)? == 0 {
            return Ok(None); // EOF — piped input ran out.
        }
        let raw = buf.trim();
        match raw {
            "q" | "quit" | "exit" => return Ok(None),
            "?" | "help" => {
                super::write_help(writer)?;
                continue;
            }
            "" => continue,
            _ => {}
        }
        if let Ok(n) = raw.parse::<usize>() {
            if n >= 1 && n <= flat.len() {
                return Ok(Some(flat[n - 1]));
            }
        }
        // Typing the verb works too — it is on screen right above.
        if let Some(a) = flat.iter().find(|a| a.verb == raw) {
            return Ok(Some(a));
        }
        writeln!(writer, "  pick 1-{}, or q to quit", flat.len())?;
    }
}

/// The argv for `action`, asking only what the verb will not ask itself.
fn build_argv<R: LineSource + ?Sized, W: Write>(
    action: &Action,
    reader: &mut R,
    writer: &mut W,
) -> Result<Vec<String>, TenancyError> {
    let mut argv = vec![action.verb.to_owned()];
    if !action.asks.is_empty() {
        writeln!(writer)?;
    }
    for ask in action.asks {
        match ask {
            Ask::Value {
                flag,
                label,
                default,
            } => {
                let v = prompt_value(reader, writer, &format!("  {label}"), *default)?;
                if !v.is_empty() {
                    argv.push((*flag).to_owned());
                    argv.push(v);
                }
            }
            Ask::Toggle { flag, question } => {
                if prompt_yes_no(reader, writer, &format!("  {question}"), false)? {
                    argv.push((*flag).to_owned());
                }
            }
            Ask::Either { question, yes, no } => {
                let pick = prompt_yes_no(reader, writer, &format!("  {question}"), true)?;
                argv.push((*if pick { yes } else { no }).to_owned());
            }
        }
    }
    Ok(argv)
}

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

    /// Every menu entry must be a verb the dispatcher handles.
    ///
    /// The catalog is a second list of verb names, so it can rot: rename a
    /// verb and the menu keeps offering the old spelling, which falls
    /// through to the single-tenant runner and fails with something
    /// unrelated. Reading the match arms is crude but it is the only way to
    /// compare against the real table without running a database.
    #[test]
    fn every_menu_verb_is_dispatchable() {
        let src = include_str!("mod.rs");
        for action in flatten() {
            let arm = format!("\"{}\"", action.verb);
            assert!(
                src.contains(&arm),
                "the menu offers `{}`, which no arm of `dispatch` matches — \
                 it would fall through to the single-tenant runner (#1345)",
                action.verb
            );
        }
    }

    /// A verb listed twice would make one of the two numbers unreachable.
    #[test]
    fn no_verb_appears_twice() {
        let mut seen: Vec<&str> = Vec::new();
        for action in flatten() {
            assert!(
                !seen.contains(&action.verb),
                "`{}` is in the menu twice",
                action.verb
            );
            seen.push(action.verb);
        }
    }

    /// Numbering is positional, so the flat order must match what is printed.
    #[test]
    fn numbering_matches_the_printed_order() {
        let flat = flatten();
        let mut out = Vec::new();
        write_menu(&mut out, &flat).expect("render");
        let text = String::from_utf8(out).expect("utf8");
        for (i, action) in flat.iter().enumerate() {
            assert!(
                text.contains(&format!("{}) {}", i + 1, action.verb)),
                "entry {} should be `{}`:\n{text}",
                i + 1,
                action.verb
            );
        }
    }

    #[test]
    fn a_number_and_the_verb_itself_pick_the_same_action() {
        let flat = flatten();
        for (i, action) in flat.iter().enumerate() {
            let by_number = format!("{}\n", i + 1);
            let mut sink = Vec::new();
            let picked = pick(&mut Cursor::new(by_number), &mut sink, &flat)
                .expect("pick")
                .expect("some");
            assert_eq!(picked.verb, action.verb);

            let mut sink = Vec::new();
            let by_name = pick(
                &mut Cursor::new(format!("{}\n", action.verb)),
                &mut sink,
                &flat,
            )
            .expect("pick")
            .expect("some");
            assert_eq!(by_name.verb, action.verb);
        }
    }

    #[test]
    fn quit_and_eof_both_end_the_menu() {
        let flat = flatten();
        for input in ["q\n", "quit\n", ""] {
            let mut sink = Vec::new();
            let got = pick(&mut Cursor::new(input), &mut sink, &flat).expect("pick");
            assert!(got.is_none(), "`{input:?}` should end the menu");
        }
    }

    /// An out-of-range number re-asks rather than running something else.
    #[test]
    fn a_bad_choice_reprompts() {
        let flat = flatten();
        let input = format!("{}\n2\n", flat.len() + 1);
        let mut sink = Vec::new();
        let picked = pick(&mut Cursor::new(input), &mut sink, &flat)
            .expect("pick")
            .expect("some");
        assert_eq!(picked.verb, flat[1].verb);
        let text = String::from_utf8(sink).expect("utf8");
        assert!(text.contains("pick 1-"), "should have complained: {text}");
    }

    /// A pick must actually reach the verb — the whole point of re-entering
    /// `dispatch` rather than describing what the verb would have done.
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn picking_an_action_runs_it() {
        use crate::sql::sqlx;

        let tmp = tempfile::tempdir().expect("tempdir");
        let url = format!("sqlite://{}?mode=rwc", tmp.path().join("reg.db").display());
        let pool = sqlx::SqlitePool::connect(&url).await.expect("connect");
        let pools = TenantPools::<sqlx::Sqlite>::new(pool);
        let migrations = tempfile::tempdir().expect("migrations");

        let mut buf: Vec<u8> = Vec::new();
        super::super::run_with_writer(
            &pools,
            &url,
            migrations.path(),
            vec!["migrate-registry".to_owned()],
            &mut buf,
        )
        .await
        .expect("migrate-registry");

        // Pick `list-tenants` by name, then decline another action.
        let mut out: Vec<u8> = Vec::new();
        menu_cmd(
            &pools,
            &url,
            migrations.path(),
            crate::tenancy::bootstrap::init_tenancy,
            &mut Cursor::new("list-tenants\nn\n"),
            &mut out,
        )
        .await
        .expect("menu");

        let text = String::from_utf8(out).expect("utf8");
        assert!(
            text.contains("cargo run -- list-tenants"),
            "the menu should echo the command it runs:\n{text}"
        );
        // `list-tenants` on an empty registry still prints its own header, so
        // reaching the verb is observable without seeding anything.
        assert!(
            !text.contains("list-tenants failed"),
            "the verb should have run cleanly:\n{text}"
        );
    }

    /// Control must come back from a verb that reached for stdin itself —
    /// the menu used to deadlock there (#1360).
    ///
    /// A `Cursor` cannot drive the verb's *own* prompt: `manage_interactive`
    /// reads the process's stdin, which under `cargo test` is not a
    /// terminal, so the verb gets `None` and errors. That is still the
    /// assertion worth making here — the verb ran, reached for input,
    /// returned, and the loop moved on to the next question. Under the old
    /// held-`StdinLock` design that hung, and nothing after the first
    /// prompt was ever written.
    ///
    /// The full nested-prompt path needs a real terminal; see the pty
    /// check in the issue.
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn a_verb_that_prompts_for_itself_completes() {
        use crate::sql::sqlx;

        let tmp = tempfile::tempdir().expect("tempdir");
        let url = format!("sqlite://{}?mode=rwc", tmp.path().join("reg.db").display());
        let pool = sqlx::SqlitePool::connect(&url).await.expect("connect");
        let pools = TenantPools::<sqlx::Sqlite>::new(pool);
        let migrations = tempfile::tempdir().expect("migrations");

        let mut buf: Vec<u8> = Vec::new();
        super::super::run_with_writer(
            &pools,
            &url,
            migrations.path(),
            vec!["migrate-registry".to_owned()],
            &mut buf,
        )
        .await
        .expect("migrate-registry");

        // Pick drop-tenant — which prompts for a slug — then decline
        // another action. The `n` must still be consumed by the menu,
        // proving the loop got control back.
        let mut out: Vec<u8> = Vec::new();
        menu_cmd(
            &pools,
            &url,
            migrations.path(),
            crate::tenancy::bootstrap::init_tenancy,
            &mut Cursor::new("drop-tenant\nn\n"),
            &mut out,
        )
        .await
        .expect("menu");

        let text = String::from_utf8(out).expect("utf8");
        assert!(
            text.contains("drop-tenant failed"),
            "the verb should have run and reported:\n{text}"
        );
        assert!(
            text.contains("Another action?"),
            "the loop must reach the next question rather than hang:\n{text}"
        );
    }

    /// Declining "another action?" ends the loop rather than re-showing the
    /// menu forever — a menu that cannot be left is worse than no menu.
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn the_loop_ends_when_asked() {
        use crate::sql::sqlx;

        let tmp = tempfile::tempdir().expect("tempdir");
        let url = format!("sqlite://{}?mode=rwc", tmp.path().join("reg.db").display());
        let pool = sqlx::SqlitePool::connect(&url).await.expect("connect");
        let pools = TenantPools::<sqlx::Sqlite>::new(pool);
        let migrations = tempfile::tempdir().expect("migrations");

        let mut out: Vec<u8> = Vec::new();
        // `q` at the first prompt: no verb runs at all.
        menu_cmd(
            &pools,
            &url,
            migrations.path(),
            crate::tenancy::bootstrap::init_tenancy,
            &mut Cursor::new("q\n"),
            &mut out,
        )
        .await
        .expect("menu");
        let text = String::from_utf8(out).expect("utf8");
        assert!(
            !text.contains("Same thing without the menu"),
            "quitting should not have run anything:\n{text}"
        );
    }

    /// Values become `--flag value`; an empty answer drops the flag entirely
    /// so the verb sees its own default rather than an empty string.
    #[test]
    fn answers_become_flags_and_blanks_are_dropped() {
        let action = Action {
            verb: "create-tenant",
            about: "",
            asks: &[
                Ask::Value {
                    flag: "--mode",
                    label: "mode",
                    default: Some("schema"),
                },
                Ask::Value {
                    flag: "--display-name",
                    label: "display name",
                    default: None,
                },
                Ask::Toggle {
                    flag: "--no-migrate",
                    question: "skip migrations?",
                },
            ],
        };
        // mode: enter (default) · display-name: blank · toggle: no
        let mut sink = Vec::new();
        let argv = build_argv(&action, &mut Cursor::new("\n\nn\n"), &mut sink).expect("argv");
        assert_eq!(argv, vec!["create-tenant", "--mode", "schema"]);

        // mode: database · display-name: Acme · toggle: yes
        let mut sink = Vec::new();
        let argv =
            build_argv(&action, &mut Cursor::new("database\nAcme\ny\n"), &mut sink).expect("argv");
        assert_eq!(
            argv,
            vec![
                "create-tenant",
                "--mode",
                "database",
                "--display-name",
                "Acme",
                "--no-migrate"
            ]
        );
    }
}