cargo-rustango 0.61.6

`cargo rustango new <name>` — project scaffolder for the rustango 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
//! Interactive `cargo rustango new` — numbered menus instead of flags.
//!
//! The wizard decides nothing on its own: every answer sets a field the
//! flags already set, and it prints the equivalent one-line command before
//! creating anything. So there is one code path deciding what a project
//! contains, and using the wizard once teaches the flags for next time.

use std::io::{self, IsTerminal, Write};

use crate::{Backend, NewArgs, NewFlags, Template, OPTIONAL_FEATURES};

const TEMPLATES: &[(&str, Template, &str)] = &[
    (
        "fullstack",
        Template::Fullstack,
        "ORM + auto-admin + forms — the usual starting point",
    ),
    (
        "api",
        Template::Api,
        "bare ORM + axum, no admin UI — for JSON-only services",
    ),
    (
        "tenant",
        Template::Tenant,
        "multi-tenancy: tenant registry + operator console",
    ),
];

const BACKENDS: &[(&str, Backend, &str)] = &[
    (
        "postgres",
        Backend::Postgres,
        "every feature, including schema-mode tenancy",
    ),
    (
        "sqlite",
        Backend::Sqlite,
        "a file beside the project — no server to run",
    ),
    ("mysql", Backend::Mysql, "MySQL 8.0+ / MariaDB"),
];

/// Ask for anything the flags did not already answer, then confirm.
///
/// `given` carries what was parsed from the command line; the wizard only
/// asks about the rest, so `new myapp -i` skips straight to the menus.
pub fn run(given: NewFlags, name_was_given: bool) -> Result<NewArgs, String> {
    if !io::stdin().is_terminal() {
        return Err(
            "--interactive needs a terminal — pass --template / --backend / --features instead"
                .to_owned(),
        );
    }

    println!();
    println!("  rustango — new project");
    println!("  (enter accepts the default; ctrl-c aborts)");
    ask(given, name_was_given, &mut prompt)
}

/// The wizard proper; `prompt` reads one answer, so a test can script it.
fn ask(given: NewFlags, name_was_given: bool, prompt: &mut Prompt<'_>) -> Result<NewArgs, String> {
    let name = if name_was_given {
        given.name
    } else {
        ask_name(prompt)?
    };

    // A flag already answered the question (#2286).
    let template = match given.template {
        Some(t) => t,
        None => {
            let default = TEMPLATES
                .iter()
                .position(|(_, t, _)| *t == Template::DEFAULT)
                .unwrap_or(0);
            let menu = TEMPLATES.iter().map(|(n, _, a)| (*n, *a));
            TEMPLATES[choose("Template", menu, default, prompt)?].1
        }
    };

    let backend = match given.backend {
        Some(b) => b,
        None => {
            let default = BACKENDS
                .iter()
                .position(|(_, b, _)| *b == Backend::DEFAULT)
                .unwrap_or(0);
            let menu = BACKENDS.iter().map(|(n, _, a)| (*n, *a));
            BACKENDS[choose("Database", menu, default, prompt)?].1
        }
    };

    let features = ask_features(template, &given.features, prompt)?;

    let args = NewArgs {
        name,
        template,
        backend,
        features,
        rustango_path: given.rustango_path,
    };

    println!();
    println!("  Same thing without the wizard:");
    println!("    {}", equivalent_command(&args));
    println!();
    if !confirm("Create it?", prompt)? {
        return Err("cancelled".to_owned());
    }
    Ok(args)
}

/// Prints a label and returns the line typed after it.
type Prompt<'a> = dyn FnMut(&str) -> Result<String, String> + 'a;

/// The non-interactive command line that produces `args`.
fn equivalent_command(args: &NewArgs) -> String {
    let mut cmd = format!(
        "cargo rustango new {} --template {} --backend {}",
        args.name,
        args.template.name(),
        args.backend.feature()
    );
    if !args.features.is_empty() {
        cmd.push_str(&format!(" --features {}", args.features.join(",")));
    }
    if let Some(path) = &args.rustango_path {
        cmd.push_str(&format!(" --rustango-path {}", shell_quote(path)));
    }
    cmd
}

/// `s` as one POSIX shell word; plain paths stay unquoted.
fn shell_quote(s: &str) -> String {
    let plain = !s.is_empty()
        && s.chars()
            .all(|c| c.is_ascii_alphanumeric() || "-_./:=@,+".contains(c));
    if plain {
        s.to_owned()
    } else {
        format!("'{}'", s.replace('\'', r"'\''"))
    }
}

fn ask_name(prompt: &mut Prompt<'_>) -> Result<String, String> {
    loop {
        let raw = prompt("\n  Project name: ")?;
        let name = raw.trim();
        if name.is_empty() {
            println!("  a name is required");
            continue;
        }
        match crate::validate_name(name) {
            Ok(()) => return Ok(name.to_owned()),
            Err(e) => println!("  {e}"),
        }
    }
}

/// One-of-N. Returns the index into `options`.
fn choose<'a>(
    title: &str,
    options: impl Iterator<Item = (&'a str, &'a str)>,
    default_ix: usize,
    prompt: &mut Prompt<'_>,
) -> Result<usize, String> {
    let options: Vec<(&str, &str)> = options.collect();
    let width = options.iter().map(|(n, _)| n.len()).max().unwrap_or(0);
    let iw = options.len().to_string().len();
    println!();
    println!("  {title}");
    for (i, (name, about)) in options.iter().enumerate() {
        let marker = if i == default_ix { "  (default)" } else { "" };
        println!("    {:>iw$}) {name:<width$}  {about}{marker}", i + 1);
    }
    loop {
        let raw = prompt("  > ")?;
        let raw = raw.trim();
        if raw.is_empty() {
            return Ok(default_ix);
        }
        match raw.parse::<usize>() {
            Ok(n) if n >= 1 && n <= options.len() => return Ok(n - 1),
            // Typing the name works too — it is right there on screen.
            _ => match options.iter().position(|(n, _)| *n == raw) {
                Some(ix) => return Ok(ix),
                None => println!("  pick 1-{}", options.len()),
            },
        }
    }
}

/// Any-of-N, by number. Features the template already turns on are left out.
fn ask_features(
    template: Template,
    preselected: &[String],
    prompt: &mut Prompt<'_>,
) -> Result<Vec<String>, String> {
    let base = template.base_features();
    let menu: Vec<(&str, &str)> = OPTIONAL_FEATURES
        .iter()
        .filter(|(n, _)| !base.contains(n))
        .map(|(n, a)| (*n, *a))
        .collect();
    if menu.is_empty() {
        return Ok(preselected.to_vec());
    }

    let width = menu.iter().map(|(n, _)| n.len()).max().unwrap_or(0);
    let iw = menu.len().to_string().len();
    println!();
    println!("  Extra features  (numbers, e.g. `1 3 4` — enter for none)");
    for (i, (name, about)) in menu.iter().enumerate() {
        let on = if preselected.iter().any(|p| p == name) {
            "*"
        } else {
            " "
        };
        println!("  {on} {:>iw$}) {name:<width$}  {about}", i + 1);
    }
    if !preselected.is_empty() {
        println!("    (* already set by --features; numbers add to them)");
    }

    loop {
        let raw = prompt("  > ")?;
        let raw = raw.trim();
        if raw.is_empty() {
            return Ok(preselected.to_vec());
        }
        // Given `--features` stay; the menu only adds (#2286).
        let mut picked = preselected.to_vec();
        let mut bad = None;
        for tok in raw.split([',', ' ']).filter(|t| !t.is_empty()) {
            match tok.parse::<usize>() {
                Ok(n) if n >= 1 && n <= menu.len() => {
                    let name = menu[n - 1].0.to_owned();
                    if !picked.contains(&name) {
                        picked.push(name);
                    }
                }
                _ => {
                    bad = Some(tok.to_owned());
                    break;
                }
            }
        }
        match bad {
            Some(t) => println!("  `{t}` is not one of 1-{}", menu.len()),
            None => return Ok(picked),
        }
    }
}

fn confirm(question: &str, prompt: &mut Prompt<'_>) -> Result<bool, String> {
    loop {
        let raw = prompt(&format!("  {question} [Y/n] "))?;
        return Ok(match raw.trim().to_ascii_lowercase().as_str() {
            "" | "y" | "yes" => true,
            "n" | "no" => false,
            _ => continue,
        });
    }
}

/// Print without a newline, then read one line. EOF (ctrl-d) aborts rather
/// than looping forever on an empty read.
fn prompt(label: &str) -> Result<String, String> {
    print!("{label}");
    io::stdout().flush().map_err(|e| e.to_string())?;
    let mut buf = String::new();
    match io::stdin().read_line(&mut buf) {
        Ok(0) => Err("cancelled".to_owned()),
        Ok(_) => Ok(buf),
        Err(e) => Err(e.to_string()),
    }
}

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

    /// The line the wizard prints must re-create the same project.
    ///
    /// This is what keeps the wizard a front-end over the flags rather than a
    /// second code path: if it could produce a selection the flags cannot
    /// express, the two would drift.
    #[test]
    fn the_echoed_command_round_trips() {
        let cases = [
            (Template::Tenant, Backend::Sqlite, vec!["sso", "cache-page"]),
            (Template::Api, Backend::Mysql, vec![]),
            (Template::Fullstack, Backend::Postgres, vec!["tenancy"]),
        ];
        for (template, backend, features) in cases {
            let features: Vec<String> = features.iter().map(|s| (*s).to_owned()).collect();
            let args = NewArgs {
                name: "probe".to_owned(),
                template,
                backend,
                features: features.clone(),
                rustango_path: None,
            };
            let cmd = equivalent_command(&args);
            // Re-parse it exactly as a user retyping the line would.
            let argv: Vec<String> = cmd
                .split_whitespace()
                .skip(3) // `cargo rustango new`
                .map(str::to_owned)
                .collect();
            let back = crate::parse_new_args(&argv, false)
                .unwrap_or_else(|e| panic!("`{cmd}` does not parse: {e}"));
            assert_eq!(back.name, "probe", "{cmd}");
            assert_eq!(back.template, template, "{cmd}");
            assert_eq!(back.backend, backend, "{cmd}");
            assert_eq!(back.features, features, "{cmd}");
        }
    }

    /// Enter on every question keeps `--template` / `--backend`: they are
    /// not asked at all, so a menu default cannot override them (#2286).
    #[test]
    fn given_template_and_backend_are_not_asked() {
        let argv: Vec<String> = ["shop", "-i", "--template", "tenant", "--backend", "sqlite"]
            .iter()
            .map(|s| (*s).to_owned())
            .collect();
        let flags = crate::parse_new_flags(&argv, true).expect("parse");
        let mut asked = Vec::new();
        let mut enter = |label: &str| {
            asked.push(label.to_owned());
            Ok("\n".to_owned())
        };
        let args = ask(flags, true, &mut enter).expect("wizard");
        assert_eq!(args.template, Template::Tenant);
        assert_eq!(args.backend, Backend::Sqlite);
        // Extra features, then the confirm — no template or backend menu.
        assert_eq!(asked.len(), 2, "{asked:?}");
    }

    /// Absent flags are still asked, and Enter takes the documented default.
    #[test]
    fn missing_template_and_backend_are_asked_with_defaults() {
        let flags = crate::parse_new_flags(&["shop".to_owned()], true).expect("parse");
        let mut asked = 0;
        let mut enter = |_: &str| {
            asked += 1;
            Ok("\n".to_owned())
        };
        let args = ask(flags, true, &mut enter).expect("wizard");
        assert_eq!(args.template, Template::DEFAULT);
        assert_eq!(args.backend, Backend::DEFAULT);
        assert_eq!(asked, 4);
    }

    /// Picking from the menu adds to `--features`, it does not replace them.
    #[test]
    fn menu_picks_add_to_given_features() {
        let argv: Vec<String> = [
            "shop",
            "-i",
            "-t",
            "api",
            "-b",
            "sqlite",
            "--features",
            "csrf",
        ]
        .iter()
        .map(|s| (*s).to_owned())
        .collect();
        let flags = crate::parse_new_flags(&argv, true).expect("parse");
        let sso = OPTIONAL_FEATURES
            .iter()
            .filter(|(n, _)| !Template::Api.base_features().contains(n))
            .position(|(n, _)| *n == "sso")
            .expect("sso on the api menu")
            + 1;
        let mut answers = vec![format!("{sso}\n"), "\n".to_owned()].into_iter();
        let mut next = |_: &str| Ok(answers.next().expect("asked too often"));
        let args = ask(flags, true, &mut next).expect("wizard");
        assert_eq!(args.features, vec!["csrf", "sso"]);
    }

    /// A local checkout picked with `--rustango-path` is echoed too, quoted
    /// when the shell would split it.
    #[test]
    fn the_echoed_command_keeps_rustango_path() {
        let mut args = NewArgs {
            name: "probe".to_owned(),
            template: Template::Api,
            backend: Backend::Sqlite,
            features: vec![],
            rustango_path: Some("../rustango/crates/rustango".to_owned()),
        };
        let cmd = equivalent_command(&args);
        let argv: Vec<String> = cmd.split_whitespace().skip(3).map(str::to_owned).collect();
        let back = crate::parse_new_args(&argv, false).expect("parses");
        assert_eq!(back.rustango_path, args.rustango_path, "{cmd}");

        args.rustango_path = Some("my dir/it's".to_owned());
        assert!(
            equivalent_command(&args).ends_with(r"--rustango-path 'my dir/it'\''s'"),
            "{}",
            equivalent_command(&args)
        );
    }

    /// Every menu entry must map onto a value the flags accept, so a wizard
    /// answer is never something `--template` / `--backend` cannot say.
    #[test]
    fn every_menu_label_is_a_valid_flag_value() {
        for (label, template, _) in TEMPLATES {
            assert_eq!(&Template::parse(label).expect(label), template);
        }
        for (label, backend, _) in BACKENDS {
            assert_eq!(&Backend::parse(label).expect(label), backend);
        }
    }
}