laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
use std::process::ExitCode;

use laravel::console::{Choice, Console, clap};
use laravel::container::Inject;
use laravel::{Application, config::Env};

struct Greetings;

impl Greetings {
    fn greet(&self, name: &str) -> String {
        format!("Hello, {name}!")
    }
}

/// Greet someone by name.
#[derive(clap::Parser)]
#[command(name = "greet")]
struct Greet {
    /// The person to greet.
    name: String,

    /// Print the greeting in uppercase.
    #[arg(long)]
    upper: bool,
}

#[laravel::console::command]
impl Greet {
    async fn handle(self, console: &mut Console, greetings: Inject<Greetings>) -> laravel::Result<()> {
        console.verbose("Resolving the greeting...");
        console.very_verbose("Applying the requested greeting style...");
        console.debug(format!("Uppercase: {}", self.upper));
        let message = greetings.greet(&self.name);
        console.info(if self.upper { message.to_uppercase() } else { message });
        Ok(())
    }
}

/// Show inline console markup, or render a supplied markup string.
#[derive(clap::Parser)]
#[command(name = "console:markup")]
struct Markup {
    text: Option<String>,
}

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

        console.line("Laravel for Rust / inline console markup");
        console.new_line();
        console.markup("<fg=sky-400>Hello, Taylor.</> <fg=emerald-400;options=bold>Ready to ship.</>");
        console.markup("<fg=amber-400>amber-400</>  <fg=rose-400>rose-400</>  <fg=violet-400>violet-400</>");
        console.markup("<fg=mauve-400>mauve-400</>  <fg=olive-400>olive-400</>  <fg=mist-400>mist-400</>");
        console.markup(
            "<fg=sky-400>Outer sky <options=bold>bold <fg=rose-400>inner rose</> sky bold</> sky restored</> plain",
        );
        console.markup("<fg=black;bg=cyan> ANSI background </>  <fg=slate-950;bg=emerald-400;options=bold> Tailwind background </>");
        console.markup("<fg=#ff8800>Hex #ff8800</>  <options=underscore>underline</>");
        console.markup(format!(
            "Literal: {}",
            laravel::console::escape_markup("<fg=red>not a tag</>")
        ));
        console.line("line stays literal: <fg=red>not parsed</>");
        console.new_line();
        console.line("No style leaks into the next line.");
    }
}

/// Build a greeting interactively.
#[derive(clap::Parser)]
#[command(name = "greet:interactive")]
struct InteractiveGreet;

#[laravel::console::command]
impl InteractiveGreet {
    async fn handle(self, console: &mut Console, greetings: Inject<Greetings>) -> laravel::Result<()> {
        let name = console.ask("What is your name?").default("Taylor").await?;
        let style = console
            .choice("Which style?", ["Normal", "Uppercase"])
            .default("Normal")
            .await?;
        if console.confirm("Display the greeting?").default(true).await? {
            let message = greetings.greet(&name);
            console.info(if style == "Uppercase" {
                message.to_uppercase()
            } else {
                message
            });
        }
        Ok(())
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
enum Environment {
    Local,
    Production,
}

#[derive(Clone, Debug, PartialEq, Eq)]
enum Feature {
    Mail,
    Search,
}

/// Try the console's prompts, message styles and progress displays.
#[derive(clap::Parser)]
#[command(name = "console:showcase")]
struct ConsoleShowcase;

#[laravel::console::command]
impl ConsoleShowcase {
    async fn handle(self, console: &mut Console) -> laravel::Result<()> {
        let description = console
            .ask("Describe your project")
            .multiline()
            .default("A Laravel for Rust application.")
            .await?;
        let environment = console
            .choice(
                "Environment?",
                [
                    Choice::new(Environment::Local, "Local").hint("Your development machine"),
                    Choice::new(Environment::Production, "Production").hint("Live customer traffic"),
                ],
            )
            .default(Environment::Local)
            .await?;
        let features = console
            .multiselect(
                "Features?",
                [
                    Choice::new(Feature::Mail, "Email").hint("Send notifications"),
                    Choice::new(Feature::Search, "Search").hint("Find records"),
                ],
            )
            .default([Feature::Mail])
            .await?;
        console.note("Configuration", format!("{description}\n{environment:?}: {features:?}"));
        console.step("Preparing application...");
        let group = console.progress_group("Preparation")?;
        let mut assets = group.spinner("Building assets...")?;
        assets.hint("Compiling browser assets");
        let mut records = group.progress(3, "Importing records...")?;
        for _ in 0..3 {
            tokio::time::sleep(std::time::Duration::from_millis(300)).await;
            records
                .message("Importing records...")
                .hint("Writing to the application database");
            records.advance(1);
        }
        records.finish("Records imported.")?;
        assets.finish("Assets built.")?;
        group.finish("Preparation complete.")?;
        let prepared = console
            .progress_each("Preparing features", features, |feature, mut progress| async move {
                progress
                    .message(format!("Preparing {feature:?}"))
                    .hint("Checking feature configuration");
                tokio::time::sleep(std::time::Duration::from_millis(500)).await;
                Ok(feature)
            })
            .await?;
        console.success(format!("Prepared {} features.", prepared.len()));
        let version = console
            .spin("Checking installation...", || async {
                tokio::time::sleep(std::time::Duration::from_millis(500)).await;
                Ok("1.0")
            })
            .await?;
        console.success(format!("Application {version} is ready."));
        Ok(())
    }
}

fn main() -> ExitCode {
    Application::configure()
        .replace_env(Env::default())
        .with_services(|services| {
            services.instance(Greetings);
        })
        .with_commands(|commands, _| {
            commands.add::<Greet>();
            commands.add::<Markup>();
            commands.add::<InteractiveGreet>();
            commands.add::<ConsoleShowcase>();
        })
        .run()
}