laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
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
use std::future::IntoFuture;
use std::panic::AssertUnwindSafe;
use std::time::Duration;

use futures_util::FutureExt;
use laravel::Application;
use laravel::config::Env;
use laravel::console::{Console, clap};
use laravel::testing::MakesConsoleRequests;

#[derive(clap::Parser)]
#[command(name = "profile")]
struct Profile;

#[laravel::console::command]
impl Profile {
    async fn handle(self, console: &mut Console) -> laravel::Result<()> {
        let name = console
            .ask("Name?")
            .placeholder("Taylor")
            .required(true)
            .autocomplete(["Taylor", "Jess"])
            .default("Taylor")
            .validate(|name: &String| {
                if name.len() < 3 {
                    Err("Use at least three characters.")
                } else {
                    Ok(())
                }
            })
            .await?;
        let password = console
            .password("Password?")
            .required(true)
            .default("default-secret")
            .validate(|password: &String| {
                if password.len() < 8 {
                    Err("Use at least eight characters.")
                } else {
                    Ok(())
                }
            })
            .await?;
        assert!(password.len() >= 8);
        let queue = console
            .choice("Queue?", ["default", "high"])
            .searchable()
            .default("default")
            .await?;
        let roles = console
            .multiselect("Roles?", ["admin", "editor", "viewer"])
            .searchable()
            .default(["editor"])
            .validate(|roles: &[String]| {
                if roles.len() > 2 {
                    Err("Select at most two roles.")
                } else {
                    Ok(())
                }
            })
            .await?;
        let mood = console
            .ask("Mood?")
            .autocomplete(|query: &str| {
                ["Curious", "Focused"]
                    .into_iter()
                    .filter(|mood| mood.to_lowercase().contains(&query.to_lowercase()))
                    .map(str::to_owned)
                    .collect()
            })
            .default("Curious")
            .await?;
        console.note("Profile", format!("{name}: {queue}, {}, {mood}", roles.join(",")));
        console.line("Saved.");
        Ok(())
    }
}

#[derive(clap::Parser)]
#[command(name = "input")]
struct Input {
    kind: String,
    #[arg(long)]
    default: Option<String>,
    #[arg(long)]
    required: bool,
    #[arg(long)]
    invalid_configuration: bool,
}

#[laravel::console::command]
impl Input {
    async fn handle(self, console: &mut Console) -> laravel::Result<()> {
        let reject_invalid = |value: &String| {
            if value == "invalid" {
                Err("Value was rejected.")
            } else {
                Ok(())
            }
        };
        match self.kind.as_str() {
            "text" => {
                let mut prompt = console.ask("Value?").required(self.required).validate(reject_invalid);
                if let Some(default) = self.default {
                    prompt = prompt.default(default);
                }
                if self.invalid_configuration {
                    prompt = prompt.multiline().autocomplete(["valid"]);
                }
                let value = prompt.await?;
                console.line(format!("Accepted {} characters.", value.len()));
            }
            "password" => {
                let mut prompt = console
                    .password("Value?")
                    .required(self.required)
                    .validate(reject_invalid);
                if let Some(default) = self.default {
                    prompt = prompt.default(default);
                }
                let value = prompt.await?;
                console.line(format!("Accepted {} characters.", value.len()));
            }
            "confirm" => {
                let mut prompt = console.confirm("Accept?").required(self.required);
                if let Some(default) = self.default {
                    prompt = prompt.default(default == "yes");
                }
                let accepted = prompt.await?;
                console.line(format!("Accepted: {accepted}"));
            }
            "multiple" => {
                let mut prompt = console.multiselect("Values?", ["one", "two"]).required(self.required);
                if let Some(default) = self.default {
                    prompt = prompt.default(if default.is_empty() {
                        vec![]
                    } else {
                        default.split(',').collect()
                    });
                }
                let values = prompt.await?;
                console.line(values.join(","));
            }
            _ => unreachable!(),
        }
        Ok(())
    }
}

#[derive(clap::Parser)]
#[command(name = "activity")]
struct Activity {
    #[arg(default_value = "finish")]
    outcome: String,
    #[arg(long)]
    spinner: bool,
}

#[laravel::console::command]
impl Activity {
    async fn handle(self, console: &mut Console) -> laravel::Result<()> {
        let shutdown = console.shutdown();
        assert!(tokio::time::timeout(Duration::from_millis(1), shutdown).await.is_err());
        let mut progress = if self.spinner {
            console.spinner("Starting...")?
        } else {
            console.progress(3, "Starting...")?
        };
        progress.advance(1);
        progress.advance(u64::MAX);
        let position = progress.position();
        assert_eq!(progress.length(), if self.spinner { None } else { Some(3) });
        progress.message("Working...").hint("A temporary hint").hint("");
        match self.outcome.as_str() {
            "finish" => progress.finish("Done.")?,
            "cancel" => progress.cancel("Cancelled explicitly.")?,
            "fail" => progress.fail("Failed explicitly.")?,
            "error" => return Err(std::io::Error::other("Work failed.").into()),
            "panic" => panic!("Work panicked."),
            "drop" => drop(progress),
            "cancel-future" => {
                let (started, ready) = tokio::sync::oneshot::channel();
                let work = async move {
                    let _progress = progress;
                    started.send(()).unwrap();
                    std::future::pending::<()>().await;
                };
                tokio::select! {
                    () = work => unreachable!(),
                    _ = ready => {},
                }
            }
            _ => unreachable!(),
        }
        console.line(format!("Completed count: {position}"));
        Ok(())
    }
}

fn app() -> Application {
    Application::configure()
        .replace_env(Env::default())
        .with_commands(|commands, _| {
            commands.add::<Profile>().add::<Input>().add::<Activity>();
        })
        .create()
}

#[tokio::test]
async fn extended_prompts_use_scripted_answers_and_keep_secrets_out_of_output() {
    let command = app()
        .command("profile")
        .expects_question("Name?", "Jess")
        .expects_password("Password?", "scripted-secret")
        .expects_choice("Queue?", "high")
        .expects_multiselect("Roles?", ["admin", "viewer"])
        .expects_question("Mood?", "Focused");
    assert!(!format!("{command:?}").contains("scripted-secret"));
    let result = command.await;
    result.assert_successful().assert_output_contains("Saved.");
    assert_eq!(result.error_output(), "Profile\nJess: high, admin,viewer, Focused\n");
    assert!(!result.error_output().contains("secret"));
    assert_eq!(result.questions(), ["Name?", "Password?", "Queue?", "Roles?", "Mood?"]);
}

#[tokio::test]
async fn all_extended_prompts_have_consistent_noninteractive_defaults() {
    for command in ["profile", "profile -n"] {
        let result = app().command(command).await;
        result.assert_successful();
        assert_eq!(result.error_output(), "Profile\nTaylor: default, editor, Curious\n");
        assert!(!format!("{result:?}").contains("default-secret"));
    }
    for kind in ["text", "password", "multiple"] {
        app()
            .command(&format!("input {kind} -n"))
            .await
            .assert_failed()
            .assert_error_output_contains("supply a default");
    }
}

#[tokio::test]
async fn empty_input_and_selections_can_be_allowed_or_required() {
    for kind in ["text", "password", "multiple"] {
        app()
            .command(&format!("input {kind} --default='' -n"))
            .await
            .assert_successful();
        app()
            .command(&format!("input {kind} --default='' --required -n"))
            .await
            .assert_failed()
            .assert_error_output_contains("input required");
    }
    app()
        .command("input text --default='   ' --required -n")
        .await
        .assert_failed()
        .assert_error_output_contains("input required");
    app()
        .command("input multiple")
        .expects_multiselect("Values?", Vec::<String>::new())
        .await
        .assert_successful();
}

#[tokio::test]
async fn empty_scripted_text_answers_use_the_default_as_enter_does() {
    app()
        .command("input text --default=fallback --required")
        .expects_question("Value?", "")
        .await
        .assert_successful()
        .assert_output_contains("Accepted 8 characters.");
    app()
        .command("input password --default=fallback --required")
        .expects_password("Value?", "")
        .await
        .assert_successful()
        .assert_output_contains("Accepted 8 characters.");
    app()
        .command("input text")
        .expects_question("Value?", "")
        .await
        .assert_successful()
        .assert_output_contains("Accepted 0 characters.");
}

#[tokio::test]
async fn required_confirmations_must_be_accepted() {
    app()
        .command("input confirm --default=no -n")
        .await
        .assert_successful()
        .assert_output_contains("Accepted: false");
    app()
        .command("input confirm --default=no --required -n")
        .await
        .assert_failed()
        .assert_error_output_contains("input required");
    app()
        .command("input confirm --required")
        .expects_confirmation("Accept?", true)
        .await
        .assert_successful()
        .assert_output_contains("Accepted: true");
    let declined = app()
        .command("input confirm --required")
        .expects_confirmation("Accept?", false);
    assert!(AssertUnwindSafe(declined.into_future()).catch_unwind().await.is_err());
}

#[tokio::test]
async fn defaults_must_pass_validation_and_match_menu_values() {
    for kind in ["text", "password"] {
        app()
            .command(&format!("input {kind} --default=invalid -n"))
            .await
            .assert_failed()
            .assert_error_output_contains("Value was rejected");
    }
    app()
        .command("input multiple --default=missing -n")
        .await
        .assert_failed()
        .assert_error_output_contains("isn't an option");
    app()
        .command("input multiple --default=one,one -n")
        .await
        .assert_failed()
        .assert_error_output_contains("more than once");
    app()
        .command("input text --default=valid --invalid-configuration -n")
        .await
        .assert_failed()
        .assert_error_output_contains("multiline input can't use autocomplete");
}

#[tokio::test]
async fn multiselect_defaults_and_scripted_answers_follow_menu_order() {
    let application = app();
    let defaults = application.command("input multiple --default=two,one -n").await;
    let scripted = application
        .command("input multiple")
        .expects_multiselect("Values?", ["two", "one"])
        .await;
    defaults.assert_successful();
    scripted.assert_successful();
    assert_eq!(defaults.output(), "one,two\n");
    assert_eq!(scripted.output(), defaults.output());
}

#[tokio::test]
async fn rejected_scripted_answers_fail_even_if_the_command_error_is_expected() {
    for command in [
        app().command("input text").expects_question("Value?", "invalid"),
        app().command("input password").expects_password("Value?", "invalid"),
        app()
            .command("input multiple")
            .expects_multiselect("Values?", ["missing"]),
        app()
            .command("input multiple")
            .expects_multiselect("Values?", ["one", "one"]),
        app()
            .command("input multiple --required")
            .expects_multiselect("Values?", Vec::<String>::new()),
    ] {
        assert!(AssertUnwindSafe(command.into_future()).catch_unwind().await.is_err());
    }
}

#[tokio::test]
async fn unused_password_expectations_are_redacted_from_failure_diagnostics() {
    let panic = AssertUnwindSafe(
        app()
            .command("list")
            .expects_password("Password?", "never-print-this")
            .into_future(),
    )
    .catch_unwind()
    .await
    .unwrap_err();
    let message = panic.downcast_ref::<String>().unwrap();
    assert!(message.contains("didn't ask"));
    assert!(!message.contains("never-print-this"));
}

#[tokio::test]
async fn password_prompt_defaults_are_redacted_from_debug_output() {
    #[derive(clap::Parser)]
    #[command(name = "debug-password")]
    struct DebugPassword;
    #[laravel::console::command]
    impl DebugPassword {
        async fn handle(self, console: &mut Console) -> laravel::Result<()> {
            let prompt = console.password("Password?").default("never-print-this");
            assert!(!format!("{prompt:?}").contains("never-print-this"));
            prompt.await?;
            Ok(())
        }
    }
    Application::configure()
        .replace_env(Env::default())
        .with_commands(|commands, _| {
            commands.add::<DebugPassword>();
        })
        .create()
        .command("debug-password")
        .await
        .assert_successful();
}

#[tokio::test]
async fn captured_progress_only_writes_start_and_finish_to_stderr() {
    for suffix in ["", " --spinner", " -n"] {
        let result = app().command(&format!("activity{suffix}")).await;
        result.assert_successful();
        assert_eq!(result.error_output(), "Starting...\nDone.\n");
        assert_eq!(
            result.output(),
            if suffix.contains("spinner") {
                "Completed count: 0\n"
            } else {
                "Completed count: 3\n"
            }
        );
    }
    for (outcome, message) in [("cancel", "Cancelled explicitly."), ("fail", "Failed explicitly.")] {
        let result = app().command(&format!("activity {outcome}")).await;
        result.assert_successful();
        assert_eq!(result.error_output(), format!("Starting...\n{message}\n"));
    }
}

#[tokio::test]
async fn progress_is_cleaned_up_on_errors_panics_and_dropped_work() {
    for outcome in ["drop", "cancel-future", "error", "panic"] {
        let result = app().command(&format!("activity {outcome}")).await;
        result.assert_exit_code(if matches!(outcome, "error" | "panic") { 1 } else { 0 });
        assert!(
            result
                .error_output()
                .starts_with("Starting...\nCancelled: Working...\n")
        );
        assert!(!result.error_output().contains('\x1b'));
    }
}