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
use crate::console::ConsoleInternals as _;
use std::path::Path;

use comfy_table::Cell;

use super::{Application, ServiceProvider};
use crate::config::dotenv;
use crate::console::markup::clean;
use crate::console::theme::Tone;
use crate::console::{Console, Verbosity, clap};
use crate::container::Registrar;
use crate::crypt::Encrypter;
use crate::routing::RouteInfo;

pub(super) struct ConsoleServiceProvider;

impl ServiceProvider for ConsoleServiceProvider {
    fn register(&self, app: &mut Registrar) {
        app.instance(super::Inspiring::default());

        let commands = app.commands();
        commands.add::<Serve>();
        commands.add::<RouteList>();
        commands.add::<KeyGenerate>();
        commands.add::<List>();
        commands.add::<Help>();
        crate::schedule::commands::register(commands);
        crate::queue::commands::register(commands);
        crate::workflow::commands::register(commands);
        #[cfg(feature = "reverb")]
        laravel_reverb::reverb::register(commands);
        #[cfg(feature = "database")]
        crate::db::register_commands(commands);
        #[cfg(feature = "database")]
        crate::db::register_seed_command(commands);
    }
}

/// Serve the application.
#[derive(clap::Parser)]
#[command(name = "serve")]
struct Serve {
    /// The address to listen on, instead of the server configuration's.
    #[arg(long, value_name = "ADDRESS")]
    host: Option<String>,
    /// The port to listen on, instead of the server configuration's.
    #[arg(long, value_name = "PORT")]
    port: Option<u16>,
}

#[crate::console::command(long_running)]
impl Serve {
    async fn handle(self, app: &Application, console: &mut Console) -> crate::Result<u8> {
        if console.is_captured() {
            console.error("the `serve` command requires the application's binary; use HTTP requests to test the application in-process");
            return Ok(1);
        }

        let host = self.host.unwrap_or_else(|| app.config().server.host.clone());
        let port = self.port.unwrap_or_else(|| app.config().server.port);

        use crate::ErrorContext as _;

        app.clone()
            .serve_with_output((host.as_str(), port), console)
            .await
            .with_context(|| format!("failed to serve on `{host}:{port}`"))?;

        Ok(0)
    }
}

/// List registered routes.
#[derive(clap::Parser)]
#[command(name = "route:list")]
struct RouteList {
    /// Print the routes as JSON.
    #[arg(long)]
    json: bool,
    /// Only include handlers containing this text.
    #[arg(long, value_name = "TEXT")]
    handler: Option<String>,
    /// Only include URIs containing this text.
    #[arg(long, value_name = "TEXT")]
    path: Option<String>,
}

#[crate::console::command]
impl RouteList {
    async fn handle(self, app: &Application, console: &mut Console) -> crate::Result<()> {
        let routes: Vec<&RouteInfo> = app
            .routes()
            .iter()
            .filter(|route| {
                self.handler
                    .as_ref()
                    .is_none_or(|handler| route.handler.contains(handler.as_str()))
            })
            .filter(|route| self.path.as_ref().is_none_or(|path| route.uri.contains(path.as_str())))
            .collect();

        if self.json {
            console.line(serde_json::to_string(&routes)?);
            return Ok(());
        }

        if routes.is_empty() {
            console.info("No routes found.");
            return Ok(());
        }

        let (headers, rows) = route_rows(&routes, console);
        console.listing(headers, rows);

        Ok(())
    }
}

/// Generate an application key.
#[derive(clap::Parser)]
#[command(name = "key:generate")]
struct KeyGenerate {
    /// Print the key without changing `.env`.
    #[arg(long)]
    show: bool,
    /// Replace an existing key, making previously encrypted data unreadable.
    #[arg(long)]
    force: bool,
}

#[crate::console::command]
impl KeyGenerate {
    async fn handle(self, console: &mut Console) -> crate::Result<u8> {
        let key = Encrypter::generate_key(crate::config().app.cipher);
        if self.show {
            console.line(key);
            return Ok(0);
        }

        use crate::ErrorContext as _;

        let path = Path::new(".env");
        let contents = read_env_file(path, Path::new(".env.example")).context("failed to read `.env`")?;
        let contents = match with_key(&contents, &key, self.force) {
            Ok(contents) => contents,
            Err(error) => {
                console.error(clean(&error));
                return Ok(1);
            }
        };

        std::fs::write(path, contents).context("failed to write `.env`")?;
        console.success("Application key set.");

        Ok(0)
    }
}

/// List the available commands.
#[derive(clap::Parser)]
#[command(name = "list")]
struct List;

#[crate::console::command]
impl List {
    async fn handle(self, console: &mut Console) -> crate::Result<()> {
        let mut definition = crate::console::commands();
        console.help(&definition.render_help());
        Ok(())
    }
}

/// Display help for a command.
#[derive(clap::Parser)]
#[command(name = "help")]
struct Help {
    /// The command to describe; omit it to list all commands.
    command: Option<String>,
}

#[crate::console::command]
impl Help {
    async fn handle(self, console: &mut Console) -> crate::Result<u8> {
        let mut definition = crate::console::commands();
        let Some(name) = self.command else {
            console.help(&definition.render_help());
            return Ok(0);
        };

        if let Some(command) = definition.find_subcommand_mut(&name) {
            console.help(&command.render_long_help());
            Ok(0)
        } else {
            let error = clap::Error::raw(
                clap::error::ErrorKind::InvalidSubcommand,
                format!("unknown command `{name}`"),
            )
            .format(&mut definition);
            console.argument_error(&error);
            Ok(2)
        }
    }
}

/// The `.env` file's contents, or the example file's when there's no `.env`
/// yet, so a fresh checkout starts from the example's settings.
///
/// Only missing files fall back. Other read failures must not discard the
/// real file's secrets or the example's settings.
fn read_env_file(path: &Path, example: &Path) -> std::io::Result<String> {
    match std::fs::read_to_string(path) {
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => match std::fs::read_to_string(example) {
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
            result => result,
        },
        result => result,
    }
}

fn with_key(contents: &str, key: &str, force: bool) -> Result<String, String> {
    let vars = dotenv::parse(contents).map_err(|error| format!("failed to read `.env`: {error}"))?;

    if dotenv::value(&vars, "APP_KEY").is_some_and(|current| !current.is_empty()) && !force {
        return Err(
            "an application key is already set; use `--force` to replace it, which makes existing encrypted data unreadable"
                .to_owned(),
        );
    }

    let line = format!("APP_KEY={key}");
    let contents = contents.strip_prefix('\u{feff}').unwrap_or(contents);
    let contents = if contents.lines().any(|existing| dotenv::assigns(existing, "APP_KEY")) {
        contents
            .lines()
            .map(|existing| {
                if dotenv::assigns(existing, "APP_KEY") {
                    line.as_str()
                } else {
                    existing
                }
            })
            .collect::<Vec<_>>()
            .join("\n")
            + "\n"
    } else {
        format!("{line}\n{contents}")
    };

    match dotenv::parse(&contents) {
        Ok(vars) if dotenv::value(&vars, "APP_KEY") == Some(key) => Ok(contents),
        _ => Err("failed to set the key: write `APP_KEY=` on a line of its own in `.env`, and try again".to_owned()),
    }
}

fn route_rows(routes: &[&RouteInfo], console: &Console) -> (Vec<&'static str>, Vec<Vec<Cell>>) {
    let domains = routes.iter().any(|route| route.domain.is_some());
    let full_paths = console.verbosity() >= Verbosity::VeryVerbose;
    let handlers: Vec<_> = routes.iter().map(|route| route.handler.as_str()).collect();
    let accent = Tone::Accent.table(console.stdout_colors());
    let mut headers = vec!["Method"];
    if domains {
        headers.push("Domain");
    }
    headers.extend(["URI", "Handler"]);

    let rows = routes
        .iter()
        .map(|route| {
            let mut handler = if full_paths {
                route.handler.clone()
            } else {
                handler_label(&route.handler, &handlers)
            };
            if console.is_verbose() {
                for middleware in &route.middleware {
                    handler.push_str("\n⇂ ");
                    handler.push_str(if full_paths {
                        middleware
                    } else {
                        middleware
                            .split('<')
                            .next()
                            .unwrap_or(middleware)
                            .rsplit("::")
                            .next()
                            .unwrap_or(middleware)
                    });
                }
            }
            let mut row = vec![Cell::new(route.methods.join("|")).fg(accent)];
            if domains {
                row.push(Cell::new(route.domain.as_deref().unwrap_or_default()));
            }
            row.extend([Cell::new(&route.uri), Cell::new(handler)]);
            row
        })
        .collect();

    (headers, rows)
}

fn handler_label(handler: &str, handlers: &[&str]) -> String {
    if handler.contains("{{closure}}") {
        return "Closure".to_owned();
    }

    for depth in 2..=handler.split("::").count() {
        let label = handler_suffix(handler, depth);
        if !handlers
            .iter()
            .any(|other| *other != handler && handler_suffix(other, depth) == label)
        {
            return label;
        }
    }

    handler.to_owned()
}

fn handler_suffix(handler: &str, depth: usize) -> String {
    let parts: Vec<_> = handler.split("::").collect();
    let start = parts.len().saturating_sub(depth);
    if start == 0 {
        return handler.to_owned();
    }
    let suffix = parts[start..].join("::");
    if parts[0] == "app" {
        suffix
    } else {
        format!("{}::{suffix}", parts[0])
    }
}

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

    fn directory(name: &str) -> std::path::PathBuf {
        let directory = std::env::temp_dir().join(format!("laravel-console-{name}-{}", std::process::id()));
        std::fs::create_dir_all(&directory).unwrap();
        directory
    }

    #[test]
    fn keys_are_set_where_theyre_assigned() {
        let contents = with_key("APP_NAME=Laravel\nAPP_KEY=\nAPP_ENV=local\n", "base64:new", false).unwrap();

        assert_eq!(contents, "APP_NAME=Laravel\nAPP_KEY=base64:new\nAPP_ENV=local\n");
    }

    #[test]
    fn keys_are_added_when_missing() {
        assert_eq!(
            with_key("APP_NAME=Laravel\n", "base64:new", false).unwrap(),
            "APP_KEY=base64:new\nAPP_NAME=Laravel\n"
        );
    }

    #[rstest::rstest]
    #[case::plain("APP_KEY=base64:old\n")]
    #[case::exported("export APP_KEY=base64:old\n")]
    #[case::spaced("  APP_KEY = base64:old\n")]
    #[case::quoted("APP_KEY=\"base64:old\"\n")]
    #[case::after_a_byte_order_mark("\u{feff}APP_KEY=base64:old\n")]
    #[case::after_an_empty_one("APP_KEY=base64:old\nAPP_KEY=\n")]
    fn existing_keys_are_only_replaced_by_force(#[case] contents: &str) {
        assert!(with_key(contents, "base64:new", false).is_err());

        let replaced = with_key(contents, "base64:new", true).unwrap();
        let vars = dotenv::parse(&replaced).unwrap();
        assert_eq!(dotenv::value(&vars, "APP_KEY"), Some("base64:new"));
        assert!(!replaced.contains("old"), "{replaced}");
    }

    #[test]
    fn invalid_env_files_are_left_alone() {
        assert!(with_key("APP NAME=Laravel\n", "base64:new", true).is_err());
    }

    #[test]
    fn a_missing_env_file_starts_from_the_example() {
        let directory = directory("missing");
        std::fs::write(directory.join(".env.example"), "APP_NAME=Laravel\n").unwrap();

        let contents = read_env_file(&directory.join(".env"), &directory.join(".env.example")).unwrap();

        assert_eq!(contents, "APP_NAME=Laravel\n");
        let _ = std::fs::remove_dir_all(directory);
    }

    #[test]
    fn env_and_example_files_that_cant_be_read_are_errors() {
        for (name, env, example) in [
            (
                "unreadable",
                Some(&b"DB_PASSWORD=secret\n# caf\xe9\n"[..]),
                &b"APP_KEY=\n"[..],
            ),
            ("unreadable-example", None, &b"APP_KEY=\n# caf\xe9\n"[..]),
        ] {
            let directory = directory(name);
            if let Some(env) = env {
                std::fs::write(directory.join(".env"), env).unwrap();
            }
            std::fs::write(directory.join(".env.example"), example).unwrap();

            let result = read_env_file(&directory.join(".env"), &directory.join(".env.example"));

            assert!(result.is_err(), "{name}");
            let _ = std::fs::remove_dir_all(directory);
        }
    }

    #[test]
    fn missing_env_and_example_files_start_empty() {
        let directory = directory("missing-both");

        let contents = read_env_file(&directory.join(".env"), &directory.join(".env.example")).unwrap();

        assert_eq!(contents, "");
        let _ = std::fs::remove_dir_all(directory);
    }
}