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
use std::future::IntoFuture;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

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

#[derive(clap::Parser)]
#[command(name = "markup")]
struct Markup {
    text: String,
}

#[laravel::console::command]
impl Markup {
    async fn handle(self, console: &mut Console) {
        console.markup(&self.text);
    }
}

#[tokio::test]
async fn markup_capture_removes_valid_styles_and_preserves_literal_and_invalid_tags() {
    let application = Application::configure()
        .replace_env(Env::default())
        .with_commands(|commands, _| {
            commands.add::<Markup>();
        })
        .create();
    for (input, expected) in [
        (
            "<fg=red>red <bg=cyan;options=bold,underscore>nested</> restored</> plain",
            "red nested restored plain",
        ),
        (
            "<fg=sky-400>Sky</> <fg=emerald-400;options=bold>Ready</> <bg=#abc;fg=#123456>Hex</>",
            "Sky Ready Hex",
        ),
        (
            "<fg=red>outer <fg=unknown>literal</> restored</>",
            "outer <fg=unknown>literal</> restored",
        ),
        (
            "<fg=red;fg=blue>duplicate</> <options=oops>bad</>",
            "<fg=red;fg=blue>duplicate</> <options=oops>bad</>",
        ),
        ("</> <fg=red>unclosed", "</> unclosed"),
        ("<fg=red", "<fg=red"),
        (r"\<fg=red>literal\</> \\ path\name", r"<fg=red>literal</> \ path\name"),
        ("<fg=red>雪 🦀\n\tline</>\x1b[31m raw\x1b[0m\x07", "雪 🦀\n\tline raw"),
    ] {
        let result = application.command_args(["markup", input]).await;
        result.assert_successful();
        assert_eq!(result.output(), format!("{expected}\n"), "{input}");
        assert_eq!(result.error_output(), "");
    }

    let untrusted = "Taylor\\</><options=conceal>hidden</>\x1b[2J\x07";
    let result = application
        .command_args([
            "markup",
            &format!("<fg=red>{}</>", laravel::console::escape_markup(untrusted)),
        ])
        .await;
    assert_eq!(result.output(), "Taylor\\</><options=conceal>hidden</>\n");
}

#[derive(clap::Parser)]
#[command(name = "describe")]
struct Describe {
    #[arg(long)]
    label_default: bool,
}

#[laravel::console::command]
impl Describe {
    async fn handle(self, console: &mut Console) -> laravel::Result<()> {
        let description = console
            .ask("Description?")
            .multiline()
            .placeholder("Tell us about the project")
            .required(true)
            .default("First line\nSecond line")
            .validate(|value: &String| {
                if value.lines().count() >= 2 {
                    Ok(())
                } else {
                    Err("Use at least two lines.")
                }
            })
            .await?;
        let environment = console
            .choice(
                "Environment?",
                [
                    Choice::new("production".to_owned(), "Production").hint("Live traffic"),
                    Choice::new("staging".to_owned(), "Staging").hint("Test traffic"),
                ],
            )
            .searchable()
            .default(if self.label_default { "Staging" } else { "staging" })
            .validate(|value: &String| {
                assert!(matches!(value.as_str(), "staging" | "production"));
                Ok::<_, String>(())
            })
            .await?;
        let targets = console
            .multiselect(
                "Targets?",
                [
                    Choice::new("a", "Same label").hint("First"),
                    Choice::new("b", "Same label").hint("Second"),
                ],
            )
            .searchable()
            .default(["b", "a"])
            .await?;
        console.line(format!("{description}\n{environment}: {}", targets.join(",")));
        console.step("Saving configuration...");
        console.success("Configuration saved.");
        Ok(())
    }
}

#[derive(clap::Parser)]
#[command(name = "present")]
struct Present {
    #[arg(default_value = "success")]
    outcome: String,
    #[arg(long)]
    grouped: bool,
}

#[laravel::console::command]
impl Present {
    async fn handle(self, console: &mut Console) -> laravel::Result<()> {
        if self.grouped {
            let group = console.progress_group("Preparing...")?;
            let assets = group.spinner("Assets...")?;
            let mut records = group.progress(2, "Records...")?;
            let (assets, records) = tokio::join!(
                async move {
                    tokio::task::yield_now().await;
                    assert!(!laravel::config().app.name.is_empty());
                    assets
                },
                async move {
                    records.advance(u64::MAX);
                    assert_eq!(records.position(), 2);
                    assert_eq!(records.length(), Some(2));
                    records.message("Importing...").hint("Saving {records}");
                    tokio::task::yield_now().await;
                    records
                }
            );
            records.finish("Records imported.")?;
            match self.outcome.as_str() {
                "success" => {
                    assets.finish("Assets built.")?;
                    group.finish("Ready.")?;
                }
                "cancel" => {
                    assets.cancel("Assets cancelled.")?;
                    group.cancel("Preparation cancelled.")?;
                }
                "fail" => {
                    assets.fail("Assets failed.")?;
                    group.fail("Preparation failed.")?;
                }
                "error" => return Err(std::io::Error::other("Build failed.").into()),
                "panic" => panic!("Build panicked."),
                "drop" => drop(assets),
                "cancel-future" => {
                    let (started, ready) = tokio::sync::oneshot::channel();
                    let work = async move {
                        let _assets = assets;
                        started.send(()).unwrap();
                        std::future::pending::<()>().await;
                    };
                    tokio::select! {
                        () = work => unreachable!(),
                        _ = ready => {},
                    }
                }
                _ => unreachable!(),
            }
        } else {
            let calls = Arc::new(AtomicUsize::new(0));
            let invoked = Arc::clone(&calls);
            let cancel_future = self.outcome == "cancel-future";
            let work = || async move {
                invoked.fetch_add(1, Ordering::Relaxed);
                assert!(!laravel::config().app.name.is_empty());
                tokio::task::yield_now().await;
                match self.outcome.as_str() {
                    "success" => Ok(42),
                    "error" => Err(std::io::Error::other("Build failed.").into()),
                    "cancel" => Err(PromptError::Cancelled.into()),
                    "panic" => panic!("Build panicked."),
                    "cancel-future" => std::future::pending().await,
                    _ => unreachable!(),
                }
            };
            if cancel_future {
                let mut spin = Box::pin(console.spin("Preparing...", work));
                assert!(spin.as_mut().now_or_never().is_none());
                drop(spin);
            } else {
                let value = console.spin("Preparing...", work).await?;
                console.line(format!("Value: {value}"));
            }
            assert_eq!(calls.load(Ordering::Relaxed), 1);
        }
        Ok(())
    }
}

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

#[tokio::test]
async fn multiline_and_menu_values_work_with_defaults_and_scripted_answers() {
    let application = app();
    let defaults = application.command("describe -n").await;
    let scripted = application
        .command("describe")
        .expects_question("Description?", "First line\nSecond line")
        .expects_choice("Environment?", "staging")
        .expects_multiselect("Targets?", ["b", "a"])
        .await;
    for result in [&defaults, &scripted] {
        result.assert_successful();
        assert_eq!(result.output(), "First line\nSecond line\nstaging: a,b\n");
        assert_eq!(result.error_output(), "Saving configuration...\nConfiguration saved.\n");
    }
}

#[tokio::test]
async fn menu_defaults_use_values_not_labels() {
    app()
        .command("describe -n --label-default")
        .await
        .assert_failed()
        .assert_error_output_contains("isn't an option");
}

#[tokio::test]
async fn multiline_scripted_answers_are_validated() {
    let command = app()
        .command("describe")
        .expects_question("Description?", "Just one line");
    assert!(
        std::panic::AssertUnwindSafe(command.into_future())
            .catch_unwind()
            .await
            .is_err()
    );
}

#[tokio::test]
async fn groups_capture_concurrent_work_and_explicit_outcomes_without_animation() {
    for (outcome, message) in [
        ("success", "Ready."),
        ("cancel", "Preparation cancelled."),
        ("fail", "Preparation failed."),
    ] {
        let result = app().command(&format!("present {outcome} --grouped -n")).await;
        result.assert_successful();
        assert!(
            result
                .error_output()
                .starts_with("Preparing...\nAssets...\nRecords...\nRecords imported.\n")
        );
        assert!(result.error_output().ends_with(&format!("{message}\n")));
        assert!(!result.error_output().contains('\x1b'));
    }
}

#[tokio::test]
async fn groups_clean_up_children_and_heading_on_error_panic_or_cancellation() {
    for outcome in ["error", "panic", "drop", "cancel-future"] {
        let result = app().command(&format!("present {outcome} --grouped")).await;
        result.assert_exit_code(if matches!(outcome, "error" | "panic") { 1 } else { 0 });
        result.assert_error_output_contains("Cancelled: Assets...\nCancelled: Preparing...\n");
    }
}

#[tokio::test]
async fn spin_returns_the_value_and_original_error_and_cleans_up_other_exits() {
    let success = app().command("present -n").await;
    success.assert_successful().assert_output_contains("Value: 42");
    assert_eq!(success.error_output(), "Preparing...\nPreparing...\n");
    let failed = app().command("present error").await;
    failed
        .assert_exit_code(1)
        .assert_error_output_contains("Failed: Preparing...\n");
    failed.assert_error_output_contains("Build failed.");
    let cancelled = app().command("present cancel").await;
    cancelled.assert_exit_code(130);
    assert_eq!(cancelled.error_output(), "Preparing...\nCancelled: Preparing...\n");
    for outcome in ["panic", "cancel-future"] {
        let result = app().command(&format!("present {outcome}")).await;
        result.assert_exit_code(if outcome == "panic" { 1 } else { 0 });
        result.assert_error_output_contains("Preparing...\nCancelled: Preparing...\n");
    }
}

#[derive(clap::Parser)]
#[command(name = "process-items")]
struct ProcessItems {
    #[arg(default_value = "success")]
    outcome: String,
    #[arg(long)]
    empty: bool,
}

#[laravel::console::command]
impl ProcessItems {
    async fn handle(self, console: &mut Console) -> laravel::Result<()> {
        use std::sync::Mutex;
        let seen = Arc::new(Mutex::new(Vec::new()));
        let failed_update = Arc::new(Mutex::new(None::<laravel::console::ProgressUpdate>));
        let total = if self.empty { 0usize } else { 3 };
        let work = console.progress_each("Updating users", 0..total, |item, mut progress| {
            let seen = Arc::clone(&seen);
            let failed_update = Arc::clone(&failed_update);
            let outcome = &self.outcome;
            async move {
                assert!(!laravel::config().app.name.is_empty());
                assert_eq!(progress.length(), Some(total as u64));
                assert_eq!(progress.position(), item as u64);
                seen.lock().unwrap().push(item);
                progress
                    .message(format!("Updating user {item}"))
                    .hint("Saving {profile}");
                tokio::task::yield_now().await;
                match (outcome.as_str(), item) {
                    ("error", 1) => {
                        *failed_update.lock().unwrap() = Some(progress);
                        return Err(std::io::Error::other("User update failed.").into());
                    }
                    ("cancel", 1) => {
                        *failed_update.lock().unwrap() = Some(progress);
                        return Err(PromptError::Cancelled.into());
                    }
                    ("panic", 1) => panic!("User update panicked."),
                    ("cancel-future", _) => std::future::pending::<()>().await,
                    _ => {}
                }
                Ok((item * 10, progress))
            }
        });
        if self.outcome == "cancel-future" {
            let mut work = Box::pin(work);
            assert!(work.as_mut().now_or_never().is_none());
            drop(work);
            assert_eq!(*seen.lock().unwrap(), [0]);
            return Ok(());
        }
        let result = work.await;
        match result {
            Ok(results) => {
                assert_eq!(*seen.lock().unwrap(), (0..total).collect::<Vec<_>>());
                let values = results
                    .into_iter()
                    .map(|(value, mut progress)| {
                        assert_eq!(progress.position(), total as u64);
                        let before = format!("{progress:?}");
                        progress.message("Late update").hint("Should not appear");
                        assert_eq!(format!("{progress:?}"), before);
                        value.to_string()
                    })
                    .collect::<Vec<_>>();
                console.line(values.join(","));
                Ok(())
            }
            Err(error) => {
                assert_eq!(*seen.lock().unwrap(), [0, 1]);
                let progress = failed_update.lock().unwrap().take().unwrap();
                assert_eq!(progress.position(), 1);
                if self.outcome == "error" {
                    assert!(error.is::<std::io::Error>());
                } else {
                    assert!(error.is::<PromptError>());
                }
                Err(error)
            }
        }
    }
}

#[tokio::test]
async fn progress_each_maps_in_order_and_advances_only_after_success() {
    let result = app().command("process-items -n").await;
    result.assert_successful();
    assert_eq!(result.output(), "0,10,20\n");
    assert_eq!(result.error_output(), "Updating users\nUpdating users\n");
    let empty = app().command("process-items --empty").await;
    empty.assert_successful();
    assert_eq!(empty.output(), "\n");
    assert_eq!(empty.error_output(), "Updating users\nUpdating users\n");
}

#[tokio::test]
async fn progress_each_stops_on_error_or_cancellation_and_returns_the_original_error() {
    for (outcome, status, message) in [
        ("error", 1, "Failed: Updating user 1"),
        ("cancel", 130, "Cancelled: Updating user 1"),
    ] {
        app()
            .command(&format!("process-items {outcome}"))
            .await
            .assert_exit_code(status)
            .assert_error_output_contains(message);
    }
}

#[tokio::test]
async fn progress_each_cleans_up_after_a_panic_or_dropped_future() {
    for (outcome, status, item) in [("panic", 1, 1), ("cancel-future", 0, 0)] {
        app()
            .command(&format!("process-items {outcome}"))
            .await
            .assert_exit_code(status)
            .assert_error_output_contains(&format!("Cancelled: Updating user {item}"));
    }
}