laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use laravel::Application;
use laravel::config::{Env, Section};
use laravel::console::{Commands, Console, Signal, clap, command};
use laravel::container::Inject;
use laravel::foundation::ApplicationBuilder;
use laravel::testing::MakesConsoleRequests;

#[derive(Default)]
struct Mailer;

impl Mailer {
    fn describe(&self, user: u64, queue: &str) -> String {
        format!("user {user} on {queue}")
    }
}

struct MailConfig {
    from: String,
}

#[derive(Clone, Debug, clap::ValueEnum)]
enum Format {
    Text,
    Html,
}

/// Send marketing emails to a user.
///
/// Emails are queued, so they may arrive a little later.
#[command("newsletter:send", visible_alias = "newsletter")]
async fn send_emails(
    /// The user to send to.
    user: u64,
    /// The queue to use.
    #[arg(long, default_value = "default")]
    queue: String,
    /// Send even if the user unsubscribed.
    #[arg(long)]
    force: bool,
    /// Extra recipients.
    #[arg(long = "cc")]
    cc: Vec<String>,
    /// The subject line.
    #[arg(long)]
    subject: Option<String>,
    #[arg(long, value_enum, default_value = "html")] format: Format,
    console: &mut Console,
    mailer: Inject<Mailer>,
    config: Section<MailConfig>,
) -> laravel::Result<()> {
    console.line(format!(
        "{} from {} force={force} cc={cc:?} subject={subject:?} format={format:?}",
        mailer.describe(user, &queue),
        config.from,
    ));

    Ok(())
}

/// Report whether the queue is healthy.
#[command("queue:check", hide = true)]
async fn check_queue(#[arg(long)] fail: bool) -> u8 {
    u8::from(fail) * 3
}

/// Process jobs until stopped.
#[command("jobs:work")]
async fn work(console: &mut Console) -> laravel::Result<()> {
    let stopping = Arc::new(AtomicBool::new(false));
    let stop = Arc::clone(&stopping);
    console.trap(Signal::Interrupt, move |_| stop.store(true, Ordering::Relaxed))?;

    while !stopping.load(Ordering::Relaxed) {
        tokio::task::yield_now().await;
    }
    console.info("Stopped cleanly.");

    Ok(())
}

/// Options several commands share.
#[derive(clap::Args)]
struct Output {
    /// Print JSON instead of text.
    #[arg(long)]
    json: bool,
}

/// List the queues.
#[command("queue:list")]
async fn list_queues(
    #[command(flatten)] output: Output,
    #[arg(long, conflicts_with = "database")] redis: bool,
    #[arg(long)] database: bool,
    console: &mut Console,
) -> laravel::Result<()> {
    let source = if redis {
        "redis"
    } else if database {
        "database"
    } else {
        "all"
    };
    console.line(if output.json {
        format!("{{\"source\":\"{source}\"}}")
    } else {
        source.to_owned()
    });

    Ok(())
}

/// A command in a module of its own, whose types name its parent module's items with `super::`.
mod reports {
    use laravel::console::clap;

    pub struct Report {
        pub title: &'static str,
    }

    #[derive(Clone, Debug, clap::ValueEnum)]
    pub enum Format {
        Csv,
        Pdf,
    }

    pub fn shout(title: &str) -> Result<String, String> {
        if title.is_empty() {
            return Err("the heading is empty".to_owned());
        }

        Ok(title.to_uppercase())
    }

    pub mod commands {
        use laravel::console::{Console, command};
        use laravel::container::Inject;

        #[command("reports:export")]
        pub async fn export(
            #[arg(long, value_enum)] format: Option<super::Format>,
            #[arg(long, value_parser = super::shout)] heading: Option<String>,
            report: Inject<super::Report>,
            console: &mut Console,
        ) {
            console.line(format!("{} as {format:?} under {heading:?}", report.title));
        }
    }
}

fn configure() -> ApplicationBuilder {
    Application::configure()
        .replace_env(Env::default())
        .with_config(|config, _| {
            config.set(MailConfig {
                from: "hello@example.com".to_owned(),
            });
        })
        .with_services(|services| {
            services.instance(Mailer);
            services.instance(reports::Report { title: "Sales" });
        })
        .with_commands(|commands: &mut Commands, _| {
            commands
                .add::<send_emails>()
                .add::<check_queue>()
                .add::<work>()
                .add::<list_queues>()
                .add::<reports::commands::export>();
        })
}

#[tokio::test]
async fn function_commands_receive_arguments_options_services_and_config() {
    let app = configure().create();

    app.command("newsletter:send 42 --queue=high --force --cc a@example.com --cc b@example.com --subject Hi --format text")
        .await
        .assert_successful()
        .assert_output_contains(
            r#"user 42 on high from hello@example.com force=true cc=["a@example.com", "b@example.com"] subject=Some("Hi") format=Text"#,
        );

    app.command("newsletter 7")
        .await
        .assert_successful()
        .assert_output_contains("user 7 on default from hello@example.com force=false cc=[] subject=None format=Html");
}

#[tokio::test]
async fn a_missing_service_names_the_command_function() {
    let app = Application::configure()
        .replace_env(Env::default())
        .with_commands(|commands, _| {
            commands.add::<send_emails>();
        })
        .create();

    let result = app.command("newsletter:send 42").await;

    result
        .assert_exit_code(1)
        .assert_error_output_contains("injecting `integration::console_functions::send_emails` failed");
}

#[tokio::test]
async fn documentation_becomes_the_commands_help() {
    let app = configure().create();

    let help = app.command("help newsletter:send").await;
    help.assert_successful();
    for command in ["newsletter:send --help", "newsletter:send -h"] {
        let direct = app.command(command).await;
        direct.assert_successful();
        assert_eq!(help.output(), direct.output());
    }
    let text = format!("{}{}", help.output(), help.error_output());
    for expected in [
        "Send marketing emails to a user.",
        "Emails are queued, so they may arrive a little later.",
        "<USER>",
        "The user to send to",
        "--queue <QUEUE>",
        "The queue to use",
        "[default: default]",
        "Send even if the user unsubscribed",
        "[possible values: text, html]",
    ] {
        assert!(text.contains(expected), "{expected}\n{text}");
    }

    let list = app.command("list").await;
    let listed = format!("{}{}", list.output(), list.error_output());
    assert!(listed.contains("newsletter:send"), "{listed}");
    assert!(
        listed.contains("Send marketing emails to a user [aliases: newsletter]"),
        "{listed}"
    );
    assert!(
        !listed.contains("queue:check"),
        "hidden commands aren't listed\n{listed}"
    );
}

#[tokio::test]
async fn function_commands_return_exit_statuses() {
    let app = configure().create();

    app.command("queue:check").await.assert_successful();
    app.command("queue:check --fail").await.assert_exit_code(3);
}

#[tokio::test]
async fn flattened_and_conflicting_options_work() {
    let app = configure().create();

    app.command("queue:list --json --redis")
        .await
        .assert_successful()
        .assert_output_contains(r#"{"source":"redis"}"#);
    app.command("queue:list")
        .await
        .assert_successful()
        .assert_output_contains("all");
}

#[tokio::test]
async fn function_commands_trap_signals_through_the_console() {
    let app = configure().create();

    app.command("jobs:work")
        .sends_signal(Signal::Interrupt)
        .await
        .assert_successful()
        .assert_error_output_contains("Stopped cleanly.");
}

#[tokio::test]
async fn function_commands_take_types_named_relative_to_their_module() {
    let app = configure().create();

    app.command("reports:export --format pdf --heading q3")
        .await
        .assert_successful()
        .assert_output_contains(r#"Sales as Some(Pdf) under Some("Q3")"#);
}

#[tokio::test]
async fn function_commands_stay_callable() {
    assert_eq!(check_queue(true).await, 3);
}

/// Display an inspiring quote.
#[command("inspire:test")]
async fn inspire(console: &mut Console, inspiring: Inject<laravel::foundation::Inspiring>) -> laravel::Result<()> {
    console.line(inspiring.quote());

    Ok(())
}

#[tokio::test]
async fn every_application_has_inspiring_quotes_which_it_may_replace() {
    use laravel::foundation::Inspiring;

    let app = configure()
        .with_commands(|commands, _| {
            commands.add::<inspire>();
        })
        .create();
    let quote = app.command("inspire:test").await;
    quote.assert_successful();
    let quotes = app.resolve::<Inspiring>().await;
    assert!(
        quotes.quotes().iter().any(|known| *known == quote.output().trim_end()),
        "{}",
        quote.output()
    );

    let replaced = configure()
        .with_services(|services| {
            services.instance(Inspiring::new(["Ship it. - Taylor Otwell".to_owned()]));
        })
        .with_commands(|commands, _| {
            commands.add::<inspire>();
        })
        .create();
    replaced
        .command("inspire:test")
        .await
        .assert_successful()
        .assert_output_contains("Ship it. - Taylor Otwell");
}

/// Greet someone.
#[command("greet")]
async fn greet(greet: String, console: &mut Console) -> laravel::Result<()> {
    console.line(format!("Hello, {greet}!"));

    Ok(())
}

#[tokio::test]
async fn arguments_may_share_the_function_name() {
    let app = configure()
        .with_commands(|commands, _| {
            commands.add::<greet>();
        })
        .create();

    app.command("greet Taylor")
        .await
        .assert_successful()
        .assert_output_contains("Hello, Taylor!");
}