use crate::config_template;
use anyhow::{Context, Result};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
const APP_DIRS: &[&str] = &[
".vscode",
"app/Http/Controllers",
"app/Http/Middleware",
"app/Http/Requests",
"app/Models",
"app/Policies",
"app/Providers",
"app/Jobs",
"app/Events",
"app/Console/Commands",
"app/Wire",
"app/Mail",
"app/Services",
"config",
"database/migrations",
"database/factories",
"database/seeders",
"public",
"resources/views/layouts",
"resources/views/posts",
"resources/views/emails",
"resources/assets",
"resources/lang",
"routes",
"storage/app",
"tests",
];
/// Crates every generated app currently depends on, resolved as `path`
/// dependencies onto this workspace checkout (Larust isn't published yet).
const FRAMEWORK_CRATES: &[&str] = &["larust-core", "larust-http", "larust-support"];
// Dev-only: never shipped, so not subject to the "one dependency surface"
// rule above - `larust-testing` is added to `[dev-dependencies]`, not
// `[dependencies]`.
const DEV_FRAMEWORK_CRATES: &[&str] = &["larust-testing"];
const CONTROLLERS_MOD_RS: &str =
"pub mod post_controller;\n\npub use post_controller::PostController;\n";
const POST_CONTROLLER_RS: &str = r#"use larust_http::session::Session;
use larust_support::axum::response::IntoResponse;
use larust_support::view;
use larust_support::AppError;
use crate::models::{NewPost, Post};
use crate::requests::StorePostRequest;
pub struct PostController;
impl PostController {
pub async fn index(session: Session) -> Result<impl IntoResponse, AppError> {
let posts = Post::all().await?;
let flash_success = larust_http::session::take::<String>(&session, "success")
.await
.ok()
.flatten()
.unwrap_or_default();
let csrf_token = larust_http::csrf::token(&session).await;
let is_authenticated = larust_support::auth::check(&session).await?;
let nav_active = "posts";
Ok(view!("posts.index", { posts, flash_success, csrf_token, is_authenticated, nav_active }))
}
pub async fn create(session: Session) -> Result<impl IntoResponse, AppError> {
let csrf_token = larust_http::csrf::token(&session).await;
let is_authenticated = true;
let nav_active = "create";
Ok(view!("posts.create", { csrf_token, is_authenticated, nav_active }))
}
pub async fn show(post: Post) -> String {
format!("{} (id {})", post.title, post.id)
}
pub async fn store(
session: Session,
request: StorePostRequest,
) -> Result<impl IntoResponse, AppError> {
let validated = request.validated();
let post = Post::create(NewPost {
title: validated.title,
})
.await?;
Ok(larust_support::redirect()
.route("posts.index")?
.with(
&session,
"success",
format!("Post \"{}\" (id {}) created.", post.title, post.id),
)
.await)
}
}
"#;
const POST_CONTROLLER_RS_WITH_AUTH: &str = r#"use larust_http::session::Session;
use larust_support::auth::Auth;
use larust_support::axum::response::IntoResponse;
use larust_support::view;
use larust_support::AppError;
use crate::models::{Comment, NewPost, Post, User};
use crate::requests::StorePostRequest;
/// A post plus its author's display name - `view!`'s `@foreach` binds a
/// single identifier per iteration (no tuple destructuring), so the
/// author name a `belongs_to` lookup resolves is flattened onto a small
/// per-view struct rather than passing `(Post, String)` pairs.
struct PostWithAuthor {
title: String,
author_name: String,
}
/// Same flattening as `PostWithAuthor` above, for a comment's author.
struct CommentWithAuthor {
author_name: String,
body: String,
}
pub struct PostController;
impl PostController {
pub async fn index(session: Session) -> Result<impl IntoResponse, AppError> {
let posts = Post::all().await?;
// Batch-loaded (eager) rather than one `post.user()` lookup per
// post - `Post::load_user` is `#[belongs_to(...)]`'s generated
// batch loader, fetching every author in one query instead of one
// query per post.
let authors = Post::load_user(&posts).await?;
let posts_with_author: Vec<PostWithAuthor> = posts
.into_iter()
.map(|post| {
let author_name = authors
.get(&post.user_id)
.map(|user| user.name.clone())
.unwrap_or_else(|| "Unknown".to_string());
PostWithAuthor {
title: post.title,
author_name,
}
})
.collect();
let flash_success = larust_http::session::take::<String>(&session, "success")
.await
.ok()
.flatten()
.unwrap_or_default();
let csrf_token = larust_http::csrf::token(&session).await;
let is_authenticated = larust_support::auth::check(&session).await?;
let nav_active = "posts";
Ok(view!("posts.index", { posts: posts_with_author, flash_success, csrf_token, is_authenticated, nav_active }))
}
pub async fn create(session: Session) -> Result<impl IntoResponse, AppError> {
let csrf_token = larust_http::csrf::token(&session).await;
let is_authenticated = true;
let nav_active = "create";
Ok(view!("posts.create", { csrf_token, is_authenticated, nav_active }))
}
pub async fn show(session: Session, post: Post) -> Result<impl IntoResponse, AppError> {
let author_name = post
.user()
.await?
.map(|author| author.name)
.unwrap_or_else(|| "Unknown".to_string());
// Live-updated by `CommentController::store`'s
// `reverb::broadcast_event` for every *other* open tab on this
// page - this initial load is only what already existed when the
// page was requested.
let comments = post.comments().await?;
let comment_authors = Comment::load_user(&comments).await?;
let comments: Vec<CommentWithAuthor> = comments
.into_iter()
.map(|comment| {
let author_name = comment_authors
.get(&comment.user_id)
.map(|user| user.name.clone())
.unwrap_or_else(|| "Unknown".to_string());
CommentWithAuthor {
author_name,
body: comment.body,
}
})
.collect();
let csrf_token = larust_http::csrf::token(&session).await;
let is_authenticated = larust_support::auth::check(&session).await?;
let nav_active = "posts";
Ok(view!("posts.show", {
id: post.id,
title: post.title,
author_name,
comments,
csrf_token,
is_authenticated,
nav_active,
}))
}
pub async fn store(
session: Session,
Auth(user): Auth<User>,
request: StorePostRequest,
) -> Result<impl IntoResponse, AppError> {
let validated = request.validated();
let post = Post::create(NewPost {
user_id: user.id,
title: validated.title,
})
.await?;
Ok(larust_support::redirect()
.route("posts.index")?
.with(
&session,
"success",
format!("Post \"{}\" (id {}) created.", post.title, post.id),
)
.await)
}
}
"#;
const COMMENT_MODEL_RS: &str = r#"use larust_support::orm::sqlx;
use larust_support::Model;
use crate::models::User;
#[derive(Model, sqlx::FromRow)]
#[table("comments")]
#[belongs_to(User, foreign_key = "user_id")]
pub struct Comment {
#[primary_key]
pub id: i64,
pub post_id: i64,
pub user_id: i64,
pub body: String,
}
"#;
const STORE_COMMENT_REQUEST_RS: &str = r#"use larust_support::FormRequest;
#[derive(FormRequest)]
pub struct StoreCommentRequest {
#[validate(required, length(max = 2000))]
pub body: String,
}
"#;
const COMMENT_CONTROLLER_RS: &str = r#"use larust_support::auth::Auth;
use larust_support::axum::response::IntoResponse;
use larust_support::AppError;
use crate::models::{Comment, NewComment, Post, User};
use crate::requests::StoreCommentRequest;
pub struct CommentController;
impl CommentController {
/// A plain POST + redirect back to the post page, same shape as
/// `PostController::store` - the "no reload needed" half of live
/// comments isn't this handler's job at all: it's
/// `larust_support::reverb::broadcast_event` below, which pushes the
/// new comment to every *other* open tab on this post's page over
/// `posts.{post_id}.comments`. The submitting browser gets there the
/// ordinary way (this redirect); everyone else's tab gets there via
/// `LarustReverb.channel(...).listen('CommentCreated', ...)`
/// (`resources/views/posts/show.blade.xr`) appending the same data as
/// a DOM node with no page load at all.
pub async fn store(
Auth(user): Auth<User>,
post: Post,
request: StoreCommentRequest,
) -> Result<impl IntoResponse, AppError> {
let validated = request.validated();
let comment = Comment::create(NewComment {
post_id: post.id,
user_id: user.id,
body: validated.body,
})
.await?;
larust_support::reverb::broadcast_event(
&format!("posts.{}.comments", post.id),
"CommentCreated",
&larust_support::serde_json::json!({
"author": user.name,
"body": comment.body,
}),
)?;
larust_support::redirect().to(&format!("/posts/{}", post.id))
}
}
"#;
const LAYOUT_APP_BLADE_XR: &str = r##"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#f4513d">
<meta name="view-transition" content="same-origin">
<meta name="csrf-token" content="{{ csrf_token }}">
<script>(function(){try{var t=localStorage.getItem('larust-theme');document.documentElement.dataset.theme=t||(matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light')}catch(_){}})()</script>
<title>Larust - ship with confidence</title>
<style>
:root { --ink: #202124; --muted: #6b6d73; --paper: #fffdf9; --canvas: #f4f0e8; --line: #e4ddd2; --brand: #f4513d; --brand-dark: #cf3628; --mint: #b9e4d0; } [data-theme="dark"] { --ink: #f6f1e8; --muted: #b8b1a8; --paper: #272522; --canvas: #181716; --line: #45413b; --brand: #ff735f; --brand-dark: #ff8a79; }
* { box-sizing: border-box; }
body { margin: 0; color: var(--ink); background: var(--canvas); font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; line-height: 1.5; }
a { color: inherit; text-decoration: none; }
.site-header { width: min(1120px, calc(100% - 40px)); margin: 0 auto; padding: 22px 0; display: flex; justify-content: space-between; align-items: center; }
.brand { display: inline-flex; gap: 10px; align-items: center; font-size: 1.15rem; font-weight: 800; letter-spacing: -.04em; }
.brand-mark { display: grid; place-items: center; width: 30px; height: 30px; color: white; background: var(--brand); border-radius: 9px 9px 9px 2px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: .9rem; }
.nav { display: flex; gap: 18px; align-items: center; font-size: .9rem; font-weight: 650; }.nav form { margin: 0; }
.nav-link { color: var(--muted); }.nav-link:hover { color: var(--brand-dark); }.nav-link.is-active { color: var(--ink); position: relative; }.nav-link.is-active::after { content: ""; position: absolute; right: 0; bottom: -7px; left: 0; height: 2px; background: var(--brand); border-radius: 2px; }
.nav-cta, .button { display: inline-flex; align-items: center; justify-content: center; border: 0; border-radius: 10px; padding: 11px 16px; background: var(--brand); color: white; font: inherit; font-weight: 750; cursor: pointer; box-shadow: 0 6px 14px rgba(244, 81, 61, .18); transition: transform .15s ease, background .15s ease; }
.nav-cta:hover, .button:hover { background: var(--brand-dark); color: white; transform: translateY(-1px); }.nav-cta.is-active { box-shadow: inset 0 0 0 2px white, 0 6px 14px rgba(244, 81, 61, .18); }.logout-button { border: 0; padding: 0; background: transparent; color: var(--muted); font: inherit; font-weight: 650; cursor: pointer; }.logout-button:hover { color: var(--brand-dark); }.theme-toggle { display: grid; place-items: center; width: 34px; height: 34px; padding: 0; color: var(--muted); background: transparent; border: 1px solid var(--line); border-radius: 9px; cursor: pointer; }.theme-toggle:hover { color: var(--ink); background: var(--paper); }.theme-toggle svg { width: 17px; height: 17px; }.theme-toggle .moon { display: none; } [data-theme="dark"] .theme-toggle .sun { display: none; } [data-theme="dark"] .theme-toggle .moon { display: block; } [data-theme="dark"] input { background: #201e1c; border-color: var(--line); color: var(--ink); } [data-theme="dark"] .button-secondary { background: #33302c; color: var(--ink); } [data-theme="dark"] .button-secondary:hover { background: #3a3733; }
.page { width: min(1120px, calc(100% - 40px)); margin: 0 auto 52px; }.page-narrow { width: min(520px, calc(100% - 40px)); margin: 42px auto 70px; }
.display { margin: 8px 0 12px; max-width: 700px; font-size: clamp(2.35rem, 6vw, 4.5rem); line-height: .98; letter-spacing: -.07em; }.lead { max-width: 560px; color: var(--muted); font-size: 1.08rem; }
.hero { padding: 68px 0 50px; }.hero-actions { display: flex; flex-wrap: wrap; gap: 12px; margin-top: 28px; margin-bottom: 20px; }.button-secondary { background: var(--paper); color: var(--ink); box-shadow: inset 0 0 0 1px var(--line); }.button-secondary:hover { background: #fff; color: var(--ink); }
.feature-grid, .post-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; }.feature, .post-card, .form-card { background: var(--paper); border: 1px solid var(--line); border-radius: 18px; }.feature { padding: 22px; }.feature strong { display: block; margin-bottom: 8px; font-size: 1.05rem; }.feature p { margin: 0; color: var(--muted); font-size: .92rem; }
.page-heading { display: flex; align-items: end; justify-content: space-between; gap: 18px; margin: 38px 0 24px; }.page-title { margin: 4px 0 0; font-size: clamp(2rem, 4vw, 3rem); letter-spacing: -.055em; }.flash-success, .flash-error { margin: 22px 0; padding: 13px 16px; border-radius: 12px; font-weight: 650; }.flash-success { color: #155b41; background: #dff5e9; }.flash-error { color: #8c3028; background: #ffebe7; }
.post-card { min-height: 170px; padding: 22px; display: flex; flex-direction: column; justify-content: space-between; }.post-title { margin: 0 0 10px; font-size: 1.2rem; letter-spacing: -.03em; }.post-meta { margin: 0; color: var(--muted); font-size: .9rem; }.tag-line { margin-top: 16px; color: var(--brand-dark); font-size: .8rem; font-weight: 750; }.empty-state { grid-column: 1 / -1; padding: 42px 24px; border: 1px dashed #cfc5b6; border-radius: 18px; color: var(--muted); text-align: center; }
.form-card { padding: 30px; box-shadow: 0 18px 48px rgba(47, 38, 26, .07); }.form-card + .form-card { margin-top: 20px; }.form-card h1 { margin: 6px 0 8px; font-size: 2rem; letter-spacing: -.05em; }.form-card > p { margin: 0 0 25px; color: var(--muted); }.field { display: grid; gap: 7px; margin-bottom: 16px; }.field label { font-size: .86rem; font-weight: 750; } input, textarea { width: 100%; padding: 12px 13px; border: 1px solid #d7d0c5; border-radius: 10px; background: #fff; color: var(--ink); font: inherit; outline: none; } textarea { min-height: 80px; resize: vertical; } input:focus, textarea:focus { border-color: var(--brand); box-shadow: 0 0 0 4px rgba(244, 81, 61, .12); }.form-card .button { margin-bottom: 8px; }.form-footer { margin: 20px 0 0; color: var(--muted); font-size: .92rem; }.form-footer a { color: var(--brand-dark); font-weight: 750; }.comment-list { list-style: none; margin: 16px 0; padding: 0; display: grid; gap: 10px; }.comment { padding: 12px 14px; background: var(--canvas); border-radius: 10px; }.comment-body { margin: 0 0 4px; }.comment-meta { margin: 0; color: var(--muted); font-size: .82rem; }.comment-form { margin-top: 8px; }
.site-footer { width: min(1120px, calc(100% - 40px)); margin: 0 auto; padding: 24px 0 34px; color: var(--muted); font-size: .82rem; border-top: 1px solid var(--line); } @media (max-width: 680px) { .site-header { padding: 16px 0; }.nav { gap: 12px; }.nav a:first-child { display: none; }.feature-grid, .post-grid { grid-template-columns: 1fr; }.hero { padding-top: 40px; }.page-heading { align-items: start; flex-direction: column; }.page, .page-narrow { width: min(100% - 28px, 1120px); } }
</style>
</head>
<body>
<header class="site-header" id="__larust_spa_header"><a class="brand" href="/"><span class="brand-mark">>_</span><span>larust</span></a><nav class="nav"><a class="{{ if nav_active == "home" { "nav-link is-active" } else { "nav-link" } }}" href="/">Home</a><a class="{{ if nav_active == "posts" { "nav-link is-active" } else { "nav-link" } }}" href="/posts">Posts</a>@if(is_authenticated)<form method="POST" action="/logout">@csrf<button class="logout-button" type="submit">Log out</button></form> <a class="{{ if nav_active == "create" { "nav-cta is-active" } else { "nav-cta" } }}" href="/posts/create">New Post</a>@else <a class="{{ if nav_active == "login" { "nav-link is-active" } else { "nav-link" } }}" href="/login">Log in</a> <a class="nav-cta" href="/register">Start building</a>@endif <button class="theme-toggle" type="button" aria-label="Toggle color theme"><svg class="sun" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 2v2m0 16v2M4.93 4.93l1.41 1.41m11.32 11.32 1.41 1.41M2 12h2m16 0h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></svg><svg class="moon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M21 12.8A9 9 0 1 1 11.2 3 7 7 0 0 0 21 12.8Z"/></svg></button></nav></header>
@spa
@yield('content')
@endspa
<footer class="site-footer">Larust by <a href="https://wallabydesigns.com" class="wallaby" target="_blank" rel="noopener noreferrer">Wallaby Designs</a> · familiar conventions, Rust certainty.</footer>
<script>(function(){function s(){var b=document.querySelector('.theme-toggle');if(!b)return;b.setAttribute('aria-label',document.documentElement.dataset.theme==='dark'?'Use light theme':'Use dark theme')}document.addEventListener('click',function(e){if(!e.target.closest('.theme-toggle'))return;var t=document.documentElement.dataset.theme==='dark'?'light':'dark';document.documentElement.dataset.theme=t;try{localStorage.setItem('larust-theme',t)}catch(_){}s()});document.addEventListener('larust:spa:navigated',s);s()})()</script>
@larustscripts
</body>
</html>
"##;
/// One example key, deliberately not wired into any generated template -
/// `t("messages.welcome")` in a `{{ }}` expression is enough to use it
/// (see `docs/digging-deeper/localization.md`); forcing every scaffolded
/// page through a translation call would add friction to the common
/// single-locale case this file exists to demonstrate leaving, not adopt.
const LANG_EN_JSON: &str = r#"{
"messages.welcome": "Welcome to :app!"
}
"#;
const WELCOME_BLADE_XR: &str = r#"@extends('layouts.app')
@section('content')
<main class="page">
<section class="hero"><h1 class="display">Ship the pleasant parts.</h1><p class="lead">Larust brings the clarity of Laravel conventions to a fast, strongly typed Rust foundation.</p><div class="hero-actions"><a class="button" href="/register">Start building <span>→</span></a><a class="button button-secondary" href="/posts">Explore Posts</a></div></section>
<section class="feature-grid"><article class="feature"><strong>Conventions first</strong><p>Routes, controllers, requests, and views find their natural home.</p></article><article class="feature"><strong>Rust where it counts</strong><p>Lean on compile-time confidence without losing momentum.</p></article><article class="feature"><strong>Built to make things</strong><p>Start with a small journal and grow toward the product in your head.</p></article></section>
</main>
@endsection
"#;
const POSTS_INDEX_BLADE_XR: &str = r#"@extends('layouts.app')
@section('content')
<main class="page">
<div class="page-heading"><div><h1 class="page-title">Small notes. Fast ideas.</h1></div><a class="button" href="/posts/create">Write a post <span>→</span></a></div>
@if(!flash_success.is_empty())<p class="flash-success">{{ flash_success }}</p>@endif
<section class="post-grid">
@foreach(post in posts)
<article class="post-card"><div><h2 class="post-title">{{ post.title }}</h2><p class="post-meta">A fresh note from your application.</p></div><div class="tag-line"># larust</div></article>
@endforeach
</section>
</main>
@endsection
"#;
const POSTS_INDEX_BLADE_XR_WITH_AUTH: &str = r#"@extends('layouts.app')
@section('content')
<main class="page">
<div class="page-heading"><div><h1 class="page-title">Small notes. Fast ideas.</h1></div><a class="button" href="/posts/create">Write a post <span>→</span></a></div>
@if(!flash_success.is_empty())<p class="flash-success">{{ flash_success }}</p>@endif
<section class="post-grid">
@foreach(post in posts)
<article class="post-card"><div><h2 class="post-title">{{ post.title }}</h2><p class="post-meta">By {{ post.author_name }}</p></div><div class="tag-line"># larust</div></article>
@endforeach
</section>
</main>
@endsection
"#;
const POSTS_CREATE_BLADE_XR: &str = r#"@extends('layouts.app')
@section('content')
<main class="page-narrow"><section class="form-card"><h1>Put the idea on the page.</h1><p>Write something worth returning to.</p><form method="POST" action="/posts">
@csrf
<div class="field"><label for="title">Title</label><input id="title" type="text" name="title" placeholder="An excellent thought" required></div>
<button class="button" type="submit">Publish post <span>→</span></button>
</form><p class="form-footer"><a href="/posts">← Back to the journal</a></p></section></main>
@endsection
"#;
// Auth-only - see `scaffold()`'s own `if auth { ... }` block. The comments
// section here is the one piece of this starter app that demonstrates
// `larust_support::reverb`: every *other* open tab on this exact page
// sees a new comment the instant `CommentController::store` broadcasts
// it, with nobody in that tab doing anything - the one thing neither an
// ordinary form POST nor a `@wire(...)` reactive component can do (both
// are request/response, scoped to the one visitor who acted).
const POSTS_SHOW_BLADE_XR_WITH_AUTH: &str = r#"@extends('layouts.app')
@section('content')
<main class="page-narrow">
<p class="form-footer"><a href="/posts">← Back to posts</a></p>
<section class="form-card">
<h1>{{ title }}</h1>
<p class="post-meta">By {{ author_name }}</p>
</section>
<section class="form-card">
<h2>Comments</h2>
<ul class="comment-list" id="comment-list">
@foreach(comment in comments)
<li class="comment"><p class="comment-body">{{ comment.body }}</p><p class="comment-meta">— {{ comment.author_name }}</p></li>
@endforeach
</ul>
@if(is_authenticated)
<form method="POST" action="/posts/{{ id }}/comments" class="comment-form">
@csrf
<div class="field"><label for="body">Add a comment</label><textarea id="body" name="body" required></textarea></div>
<button class="button" type="submit">Post comment</button>
</form>
@else
<p class="form-footer"><a href="/login">Log in</a> to leave a comment.</p>
@endif
</section>
</main>
<script src="/__larust_reverb/runtime.js"></script>
<script>
// Real-time comments: every *other* open tab on this same post's page
// appends a new comment the instant `CommentController::store`
// broadcasts it. The tab that actually submitted the form gets here
// the ordinary way (redirect + a fresh render of the list above);
// this listener is purely for everyone else.
LarustReverb.channel('posts.{{ id }}.comments').listen('CommentCreated', function (comment) {
var list = document.getElementById('comment-list');
var item = document.createElement('li');
item.className = 'comment';
var body = document.createElement('p');
body.className = 'comment-body';
body.textContent = comment.body;
var meta = document.createElement('p');
meta.className = 'comment-meta';
meta.textContent = '- ' + comment.author;
item.appendChild(body);
item.appendChild(meta);
list.appendChild(item);
});
</script>
@endsection
"#;
const CONTROLLERS_MOD_RS_WITH_AUTH: &str = r#"pub mod auth_controller;
pub mod comment_controller;
pub mod post_controller;
pub use auth_controller::AuthController;
pub use comment_controller::CommentController;
pub use post_controller::PostController;
"#;
const AUTH_CONTROLLER_RS: &str = r#"use larust_http::session::Session;
use larust_support::axum::response::IntoResponse;
use larust_support::view;
use larust_support::AppError;
use crate::models::{NewUser, User};
use crate::requests::{LoginRequest, RegisterRequest};
pub struct AuthController;
impl AuthController {
pub async fn show_register(session: Session) -> Result<impl IntoResponse, AppError> {
let csrf_token = larust_http::csrf::token(&session).await;
let flash_error = flash_error(&session).await;
let is_authenticated = false;
let nav_active = "register";
Ok(view!("auth.register", { csrf_token, flash_error, is_authenticated, nav_active }))
}
pub async fn register(
session: Session,
request: RegisterRequest,
) -> Result<impl IntoResponse, AppError> {
let validated = request.validated();
let existing = User::query()
.where_eq(User::EMAIL, validated.email.clone())
.first()
.await?;
if existing.is_some() {
return Ok(larust_support::redirect()
.route("register")?
.with(&session, "error", "That email is already registered.")
.await);
}
let password_hash = larust_support::auth::hash_password(&validated.password)?;
let user = User::create(NewUser {
name: validated.name,
email: validated.email,
password_hash,
})
.await?;
larust_support::auth::login(&session, &user).await?;
Ok(larust_support::redirect()
.route("posts.index")?
.with(
&session,
"success",
format!("Welcome, {} ({})!", user.name, user.email),
)
.await)
}
pub async fn show_login(session: Session) -> Result<impl IntoResponse, AppError> {
let csrf_token = larust_http::csrf::token(&session).await;
let flash_error = flash_error(&session).await;
let is_authenticated = false;
let nav_active = "login";
Ok(view!("auth.login", { csrf_token, flash_error, is_authenticated, nav_active }))
}
pub async fn login(
session: Session,
request: LoginRequest,
) -> Result<impl IntoResponse, AppError> {
let validated = request.validated();
let user = User::query()
.where_eq(User::EMAIL, validated.email.clone())
.first()
.await?;
// Always run the (deliberately expensive) password verification,
// even when no user was found, against a fixed dummy hash - a
// nonexistent email would otherwise short-circuit here and be
// distinguishable from a real one by response latency alone, even
// though the error message shown to the client is identical
// either way (see the `!authenticated` branch below).
let authenticated = match &user {
Some(user) => {
larust_support::auth::verify_password(&user.password_hash, &validated.password)?
}
None => {
larust_support::auth::verify_password(dummy_password_hash(), &validated.password)?;
false
}
};
if !authenticated {
return Ok(larust_support::redirect()
.route("login")?
.with(
&session,
"error",
"Those credentials don't match our records.",
)
.await);
}
let user = user.expect("checked above");
larust_support::auth::login(&session, &user).await?;
Ok(larust_support::redirect()
.route("posts.index")?
.with(&session, "success", format!("Welcome back, {}!", user.name))
.await)
}
pub async fn logout(session: Session) -> Result<impl IntoResponse, AppError> {
larust_support::auth::logout(&session).await?;
larust_support::redirect().to("/")
}
}
async fn flash_error(session: &Session) -> String {
larust_http::session::take::<String>(session, "error")
.await
.ok()
.flatten()
.unwrap_or_default()
}
/// A fixed Argon2 hash nothing will ever match, computed once per process
/// (not per request) - used only to give the "no such user" login path the
/// same Argon2 CPU cost as a real password check.
fn dummy_password_hash() -> &'static str {
static HASH: std::sync::OnceLock<String> = std::sync::OnceLock::new();
HASH.get_or_init(|| {
larust_support::auth::hash_password("not-a-real-account-timing-equalizer")
.expect("hashing a fixed literal string never fails")
})
}
"#;
const AUTH_REGISTER_BLADE_XR: &str = r#"@extends('layouts.app')
@section('content')
<main class="page-narrow"><section class="form-card"><h1>Build your next thing.</h1><p>One account, a clean place to begin.</p>
@if(!flash_error.is_empty())<p class="flash-error">{{ flash_error }}</p>@endif
<form method="POST" action="/register">
@csrf
<div class="field"><label for="name">Your name</label><input id="name" type="text" name="name" placeholder="Ada Lovelace" required></div>
<div class="field"><label for="email">Email address</label><input id="email" type="email" name="email" placeholder="ada@example.com" required></div>
<div class="field"><label for="password">Password</label><input id="password" type="password" name="password" placeholder="At least 8 characters" required></div>
<div class="field"><label for="password-confirmation">Confirm password</label><input id="password-confirmation" type="password" name="password_confirmation" placeholder="Repeat your password" required></div>
<button class="button" type="submit">Create account <span>→</span></button>
</form>
<p class="form-footer">Already have an account? <a href="/login">Log in</a></p></section></main>
@endsection
"#;
const AUTH_LOGIN_BLADE_XR: &str = r#"@extends('layouts.app')
@section('content')
<main class="page-narrow"><section class="form-card"><h1>Pick up where you left off.</h1><p>Your journal is ready when you are.</p>
@if(!flash_error.is_empty())<p class="flash-error">{{ flash_error }}</p>@endif
<form method="POST" action="/login">
@csrf
<div class="field"><label for="email">Email address</label><input id="email" type="email" name="email" placeholder="ada@example.com" required></div>
<div class="field"><label for="password">Password</label><input id="password" type="password" name="password" placeholder="Your password" required></div>
<button class="button" type="submit">Log in <span>→</span></button>
</form>
<p class="form-footer">New here? <a href="/register">Create an account</a></p></section></main>
@endsection
"#;
const CREATE_USERS_TABLE_SQL: &str = "CREATE TABLE users (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n name TEXT NOT NULL,\n email TEXT NOT NULL UNIQUE,\n password_hash TEXT NOT NULL\n);\n";
const REQUESTS_MOD_RS: &str =
"pub mod store_post_request;\n\npub use store_post_request::StorePostRequest;\n";
const REQUESTS_MOD_RS_WITH_AUTH: &str = r#"pub mod login_request;
pub mod register_request;
pub mod store_comment_request;
pub mod store_post_request;
pub use login_request::LoginRequest;
pub use register_request::RegisterRequest;
pub use store_comment_request::StoreCommentRequest;
pub use store_post_request::StorePostRequest;
"#;
const STORE_POST_REQUEST_RS: &str = r#"use larust_support::FormRequest;
#[derive(FormRequest)]
pub struct StorePostRequest {
#[validate(required, length(max = 255))]
pub title: String,
}
"#;
const REGISTER_REQUEST_RS: &str = r#"use larust_support::FormRequest;
#[derive(FormRequest)]
pub struct RegisterRequest {
#[validate(required, length(max = 255))]
pub name: String,
#[validate(required, email)]
pub email: String,
#[validate(required, length(min = 8), confirmed)]
pub password: String,
}
"#;
const LOGIN_REQUEST_RS: &str = r#"use larust_support::FormRequest;
#[derive(FormRequest)]
pub struct LoginRequest {
#[validate(required, email)]
pub email: String,
#[validate(required)]
pub password: String,
}
"#;
const MODELS_MOD_RS: &str = "pub mod post;\n\npub use post::{NewPost, Post};\n";
const MODELS_MOD_RS_WITH_AUTH: &str = r#"pub mod comment;
pub mod post;
pub mod user;
pub use comment::{Comment, NewComment};
pub use post::{NewPost, Post};
pub use user::{NewUser, User};
"#;
const USER_MODEL_RS: &str = r#"use larust_support::orm::sqlx;
use larust_support::{AppError, Model};
use crate::models::Post;
#[derive(Model, sqlx::FromRow)]
#[table("users")]
#[has_many(Post, foreign_key = "user_id")]
pub struct User {
#[primary_key]
pub id: i64,
pub name: String,
pub email: String,
pub password_hash: String,
}
impl larust_support::auth::Authenticatable for User {
fn auth_id(&self) -> i64 {
self.id
}
async fn find_for_auth(id: i64) -> Result<Option<Self>, AppError> {
Self::find(id).await
}
}
"#;
// Empty (no middleware generated yet) but still declared as a real module
// in `main.rs` from the start - `xr make:middleware` only appends to this
// file, it never creates the module wiring itself, so without this a
// generated middleware file would sit on disk uncompiled and unverified.
const MIDDLEWARE_MOD_RS: &str =
"// Middleware generated by `xr make:middleware` is registered here.\n";
// Same shape as `MIDDLEWARE_MOD_RS` above, and for the same reason. Written
// unconditionally regardless of `--auth`: plain `xr new` has no `User`
// model either way, so there's nothing a policy could be written against
// at scaffold time - only a later `xr make:policy` call, once a `User`
// model exists, ever puts real content here.
const POLICIES_MOD_RS: &str = "// Policies generated by `xr make:policy` are registered here.\n";
// Empty (no `xr make:mail` generator exists yet - v1 is a real, usable
// `Mailable` trait + sender, hand-authored per email like `app/Policies`
// was before its generator landed) but still declared as a real module
// from the start, same reasoning as `MIDDLEWARE_MOD_RS` above.
const MAIL_MOD_RS: &str =
"// Mailable types live here - see docs/ARCHITECTURE.md's \"Mail\" section.\n\
// mail().to(...).send(...) delivers immediately; .queue(...) defers\n\
// delivery - see the \"Job types\" note in app/Jobs/mod.rs.\n";
// Same shape as `MAIL_MOD_RS` above - no `xr make:job`/`xr make:event`
// generator yet, but a real, declared module from day one.
const JOBS_MOD_RS: &str = "// Job types (`larust_support::queue::Job`) live here - register each\n\
// with `main.rs`'s `queue:work` branch so `xr queue:work` can run it.\n\
// See docs/ARCHITECTURE.md's \"Events + Jobs/Queues\" section.\n\
//\n\
// main.rs's queue:work branch already registers the framework-owned\n\
// larust_support::mail::MailJob by default, so Mail::queue(...)\n\
// (app/Mail/mod.rs) works out of the box - remove that line if your\n\
// app never uses .queue().\n";
// Laravel's own `app/Console/Commands/` convention, verbatim - unlike its
// `Jobs`/`Events` neighbors above, this one does have a generator
// (`xr make:command`), since a named `Command` is a single, uniformly-
// shaped file (see `MAKE_COMMAND_TEMPLATE`).
const COMMANDS_MOD_RS: &str = "// Command types (`larust_support::console::Command`) live here -\n\
// register each with `routes/console.rs`'s `commands()` function so\n\
// `xr <name>` can run it. `xr make:command` generates a new one.\n";
const EVENTS_MOD_RS: &str = "// Event types (any plain `Clone` struct) live here - register\n\
// listeners for them in `main.rs` via `larust_support::event::listeners()`.\n\
// See docs/ARCHITECTURE.md's \"Events + Jobs/Queues\" section.\n";
// Same shape as `MAIL_MOD_RS`/`JOBS_MOD_RS` above - no `xr make:wire`
// generator yet, but a real, declared module from day one. `main.rs`'s
// `larust_support::wire::components()` call is where each type here gets
// registered under its own `WireComponent::NAME`.
const WIRE_MOD_RS: &str = "// Reactive components (`larust_support::wire::WireComponent`) live\n\
// here - register each with `main.rs`'s `larust_support::wire::components()`\n\
// call so `@wire('name', ...)` in a template can mount it. See\n\
// docs/ARCHITECTURE.md's \"Reactive components\" section.\n";
const FACTORIES_MOD_RS: &str = "// Model factories (`larust_support::orm::Factory`) live here -\n\
// `xr make:factory Post` generates a new one. Used from tests\n\
// (`PostFactory::new().create().await?`) and from `database/seeders`.\n";
// No `Seeder` trait - just a plain async function, same reasoning as
// `MAIL_MOD_RS`'s own "real, usable shape from the start, no generator
// needed for a one-function module" comment. `xr db:seed` (and
// `migrate:fresh --seed`) call this directly.
const SEEDERS_MOD_RS: &str = "// Populates the database with starter/demo data - called by\n\
// `xr db:seed` and `xr migrate:fresh --seed`. Add whatever this app\n\
// needs here, e.g.:\n\
// PostFactory::new().create_many(10).await?;\n\
pub async fn run() -> Result<(), larust_core::AppError> {\n \
Ok(())\n\
}\n";
const POST_MODEL_RS: &str = r#"use larust_support::orm::sqlx;
use larust_support::Model;
#[derive(Model, sqlx::FromRow)]
#[table("posts")]
pub struct Post {
#[primary_key]
pub id: i64,
pub title: String,
}
"#;
const POST_MODEL_RS_WITH_AUTH: &str = r#"use larust_support::orm::sqlx;
use larust_support::Model;
use crate::models::{Comment, User};
#[derive(Model, sqlx::FromRow)]
#[table("posts")]
#[belongs_to(User, foreign_key = "user_id")]
#[has_many(Comment, foreign_key = "post_id")]
pub struct Post {
#[primary_key]
pub id: i64,
pub user_id: i64,
pub title: String,
}
"#;
const CREATE_POSTS_TABLE_SQL: &str = "CREATE TABLE posts (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n title TEXT NOT NULL\n);\n";
const CREATE_POSTS_TABLE_SQL_WITH_AUTH: &str = "CREATE TABLE posts (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n user_id INTEGER NOT NULL REFERENCES users(id),\n title TEXT NOT NULL\n);\n";
// Auth-only (comments need a `User` to attribute authorship to - see
// `scaffold()`'s own `if auth { ... }` block) - `0003`, after `0002`'s
// `users` table since this one references it.
const CREATE_COMMENTS_TABLE_SQL: &str = "CREATE TABLE comments (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n post_id INTEGER NOT NULL REFERENCES posts(id),\n user_id INTEGER NOT NULL REFERENCES users(id),\n body TEXT NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS idx_comments_post_id ON comments(post_id);\n";
// `main.rs` is pure bootstrap now - CLI-subcommand dispatch, DB connect,
// session wiring, `.serve()` - identical regardless of `--auth`, since
// every auth-specific difference (imports, middleware groups, the route
// table itself) lives in `routes/web.rs` instead (see
// `ROUTES_WEB_HEADER`/`ROUTES_WEB_HEADER_WITH_AUTH` below). One shared
// constant, not two, avoids the "two independent strings can silently
// drift out of sync" problem the previous two-constant design had.
const MAIN_RS_HEADER: &str = r#"use larust_http::Router;
#[tokio::main]
async fn main() -> Result<(), larust_core::AppError> {
let command = std::env::args().nth(1);
if command.as_deref() == Some("migrate") {
__CRATE__::connect_database().await?;
larust_support::orm::migrate(&__CRATE__::paths().migrations()).await?;
return Ok(());
}
if command.as_deref() == Some("migrate:fresh") {
__CRATE__::connect_database().await?;
larust_support::orm::migrate_fresh(&__CRATE__::paths().migrations()).await?;
if std::env::args().any(|arg| arg == "--seed") {
__CRATE__::seeders::run().await?;
}
return Ok(());
}
if command.as_deref() == Some("db:seed") {
__CRATE__::connect_database().await?;
__CRATE__::seeders::run().await?;
return Ok(());
}
if command.as_deref() == Some("queue:work") {
__CRATE__::connect_database().await?;
// MailJob is the framework's own job type for Mail::queue(...) -
// registered by default so queued mail works out of the box;
// remove this line if your app never calls .queue().
let registry = larust_support::queue::JobRegistry::new()
.register::<larust_support::mail::MailJob>();
// Register your app's own Job types here, e.g.:
// let registry = registry.register::<__CRATE__::jobs::MyJob>();
return larust_support::queue::work(registry).await;
}
if command.as_deref() == Some("schedule:work") {
__CRATE__::connect_database().await?;
return larust_support::schedule::work(__CRATE__::routes::console::schedule()).await;
}
__DB_MAIN_RS_SNIPPET__if command.as_deref() == Some("route:list") {
let app = __CRATE__::application()?;
let route = __CRATE__::router(&app);
print_routes(&route);
return Ok(());
}
if command.as_deref() == Some("command:list") {
for info in __CRATE__::routes::console::commands().list() {
println!("{:<24} {}", info.name, info.description);
}
return Ok(());
}
// Anything else typed after `xr` (or `cargo run --`) that isn't one of
// the fixed subcommands above is looked up against your own
// `routes/console.rs::commands()` registry - `xr make:command` scaffolds
// a new one. A name matching neither is a loud, immediate error rather
// than silently falling through to `serve()` below - a typo'd
// subcommand accidentally starting the web server instead of failing
// is exactly the kind of silent gap this framework avoids elsewhere.
if let Some(name) = command.as_deref() {
// App-defined commands often query models, so they need the same
// database initialization the built-in database-backed commands do.
__CRATE__::connect_database().await?;
let args: Vec<String> = std::env::args().skip(2).collect();
if __CRATE__::routes::console::commands()
.dispatch(name, &args)
.await?
{
return Ok(());
}
eprintln!("error: unknown command {name:?} (see `command:list`)");
std::process::exit(1);
}
__CRATE__::serve().await
}
"#;
const MAIN_RS_TAIL: &str = r#"
fn print_routes(route: &Router) {
for info in route.routes() {
println!(
"{:<7} {:<24} {}",
info.method,
info.path,
info.name.as_deref().unwrap_or("")
);
}
}
"#;
// Spliced into `MAIN_RS_HEADER` at the `__DB_MAIN_RS_SNIPPET__` token, only
// when `"db"` was selected (see `scaffold()`'s `resolved_support_features`)
// - the same "presence/absence of a fixed snippet at generation time"
// mechanism `ROUTES_WEB_HEADER` vs. `ROUTES_WEB_HEADER_WITH_AUTH` already
// establishes for `--auth`, not `#[cfg]` (the generated app has no Cargo
// `db` feature of its own to gate on - `larust-support`'s `db` feature,
// baked into its dependency line at scaffold time, is the only toggle).
// Every call here goes through `larust_support::db::...`, never a bare
// `serde_json::...` path, so this needs no new direct Cargo dependency on
// the generated app's own `Cargo.toml`.
const DB_MAIN_RS_SNIPPET: &str = r#"if command.as_deref() == Some("db:list") {
larust_support::db::connect(&__CRATE__::paths().join("database/db.redb")).await?;
for key in larust_support::db::keys().await? {
println!("{key}");
}
return Ok(());
}
if command.as_deref() == Some("db:get") {
larust_support::db::connect(&__CRATE__::paths().join("database/db.redb")).await?;
let key = std::env::args().nth(2).expect("usage: xr db:get <key>");
match larust_support::db::get_raw(&key).await? {
Some(value) => println!("{value}"),
None => println!("(no value for {key})"),
}
return Ok(());
}
if command.as_deref() == Some("db:put") {
larust_support::db::connect(&__CRATE__::paths().join("database/db.redb")).await?;
let key = std::env::args().nth(2).expect("usage: xr db:put <key> <value>");
let raw = std::env::args().nth(3).expect("usage: xr db:put <key> <value>");
larust_support::db::put_raw(&key, larust_support::db::parse_cli_value(&raw)).await?;
return Ok(());
}
if command.as_deref() == Some("db:forget") {
larust_support::db::connect(&__CRATE__::paths().join("database/db.redb")).await?;
let key = std::env::args().nth(2).expect("usage: xr db:forget <key>");
larust_support::db::forget(&key).await?;
return Ok(());
}
"#;
// Spliced at `__DB_SERVE_SNIPPET__` in `lib.rs`'s `serve()`, right before
// the `.with_sessions(...)` call - every `if command == Some("db:...")` arm
// above (in `main.rs`) connects the store itself before returning early,
// but the dashboard route (`DbPlugin`, registered in `routes/web.rs`) is
// reached from `serve()`'s path, which otherwise never calls
// `larust_support::db::connect()` at all. A real bug caught by this crate's
// own live sanity check, not a hypothetical: without this, every request
// to `/__larust_db` 500s with "embedded db not connected", every single
// time, since the serving process itself never touches the CLI-only
// connect calls above.
const DB_SERVE_SNIPPET: &str =
"larust_support::db::connect(&paths().join(\"database/db.redb\")).await?;\n ";
/// `crate_ident` is the app's library crate name as `use`-able Rust syntax
/// (see [`crate_ident`]) - `main.rs` is a separate crate from `lib.rs`
/// even within one package, so it reaches `connect_database`/`application`/
/// `router`/`serve`/`routes`/etc. via `use {crate_ident}::...`, not a `mod`
/// declaration of its own. `has_db` splices in [`DB_MAIN_RS_SNIPPET`] (see
/// its own doc comment) only when the `db` optional feature was selected -
/// [`DB_SERVE_SNIPPET`] is [`lib_rs`]'s concern, not this function's.
fn main_rs(crate_ident: &str, has_db: bool) -> String {
let db_main_snippet = if has_db { DB_MAIN_RS_SNIPPET } else { "" };
// `__DB_MAIN_RS_SNIPPET__` first, `__CRATE__` second - the snippet
// itself now contains its own `__CRATE__` token (for `paths()`), which
// would never get substituted if the crate-name pass ran first and
// only saw the *outer* template, before the snippet was ever spliced
// in. A real bug, caught by generating a real app with `--features
// db` and reading the output rather than assumed from the code alone.
format!("{MAIN_RS_HEADER}{MAIN_RS_TAIL}")
.replace("__DB_MAIN_RS_SNIPPET__", db_main_snippet)
.replace("__CRATE__", crate_ident)
}
/// The app modules (`controllers`/`middleware`/`models`/`policies`/
/// `requests`/`mail`/`jobs`/`events`), declared once in `lib.rs` rather
/// than duplicated between `main.rs` and `tests/*.rs` - giving the
/// generated app a library target is what lets `tests/*.rs` (compiled as
/// its own separate crate) reach them at all via `use {crate_ident}::...`,
/// the same way `main.rs` now does. Also carries the shared server-
/// bootstrap functions (`connect_database`/`port`/`application`/`router`/
/// `serve`) - split out of `main.rs` so an embedded host (a Tauri desktop
/// shell, when `xr new --tauri`/`xr add tauri` scaffolds `src-tauri/`) can
/// call `serve()` from its own binary without duplicating the bootstrap
/// sequence or pulling in `main.rs`'s CLI-subcommand dispatch.
const LIB_RS: &str = r#"#[path = "../config/mod.rs"]
pub mod config;
#[path = "../app/Http/Controllers/mod.rs"]
pub mod controllers;
#[path = "../app/Http/Middleware/mod.rs"]
pub mod middleware;
#[path = "../app/Mail/mod.rs"]
pub mod mail;
#[path = "../app/Jobs/mod.rs"]
pub mod jobs;
#[path = "../app/Events/mod.rs"]
pub mod events;
#[path = "../app/Console/Commands/mod.rs"]
pub mod commands;
#[path = "../app/Wire/mod.rs"]
pub mod wire_components;
#[path = "../app/Models/mod.rs"]
pub mod models;
#[path = "../app/Policies/mod.rs"]
pub mod policies;
#[path = "../app/Http/Requests/mod.rs"]
pub mod requests;
#[path = "../database/factories/mod.rs"]
pub mod factories;
#[path = "../database/seeders/mod.rs"]
pub mod seeders;
#[path = "../routes/mod.rs"]
pub mod routes;
/// This app's own root directory, independent of the process's current
/// working directory - `env!("CARGO_MANIFEST_DIR")` is a compile-time
/// constant Cargo sets per-*package*, so it resolves identically whether
/// read from this library target or from `main.rs`'s separate binary
/// target. Threading this through `.env`/migrations/database resolution
/// (below, and in `main.rs`'s own CLI dispatch) is what makes `cargo run
/// -p __CRATE__` from the *workspace* root behave identically to `cd`-ing
/// into this app's own directory first - `Application::new()`/a bare
/// relative `Path::new("database/migrations")` would each silently
/// resolve against the wrong directory otherwise.
///
/// `LARUST_APP_ROOT` (a real environment variable - never read from
/// `.env`, since `.env`'s own location is exactly what this decides)
/// overrides that compile-time default, the same `xr upgrade`/
/// `LARUST_CHECKOUT_ROOT` pattern: without it, a binary built on one
/// machine and *copied* elsewhere to actually run - rather than built
/// in place there, the way `xr deploy` does it - would still look for
/// `.env`/`storage/`/`database/` at the build machine's own path. Set
/// it (e.g. a systemd unit's own `Environment=LARUST_APP_ROOT=...`
/// line) for a minimal deployment that's nothing but the compiled
/// binary and an `.env` file next to wherever it's actually run from.
pub fn paths() -> larust_core::AppPaths {
larust_core::AppPaths::new(larust_core::resolve_app_root(env!("CARGO_MANIFEST_DIR")))
}
pub async fn connect_database() -> Result<(), larust_core::AppError> {
larust_support::orm::connect(&database_url()?).await
}
/// Resolves `config/database.rs`'s active connection to the URL
/// `larust_support::orm::connect()` needs - with one extra step
/// `ConnectionConfig::to_url()` itself can't do: a *relative* sqlite path
/// (`config/database.rs`'s own default, `database/database.sqlite`) needs
/// resolving against this app's own root ([`paths`]), not the process's
/// current working directory, so `xr dev`/`cargo run` behave identically
/// regardless of where they're invoked from. An absolute path or
/// `:memory:` is left untouched.
fn database_url() -> Result<String, larust_core::AppError> {
let url = config::database::config().default_connection_url()?;
let relative_sqlite_path = url
.strip_prefix("sqlite://")
.filter(|path| !path.starts_with('/') && !path.starts_with(":memory:"))
.map(str::to_string);
Ok(match relative_sqlite_path {
Some(relative) => {
let path = paths().join(relative);
format!("sqlite:///{}", path.to_string_lossy().replace('\\', "/"))
}
None => url,
})
}
/// The app's configured HTTP port (`APP_PORT`, default 34187) - reads the
/// raw `config/app.rs` JSON directly rather than `larust_core::config()`,
/// since the latter panics until `Application::new()`/`at_root()` has
/// run, and an embedded host needs this *before* it can call `serve()`
/// (typically on its own background thread) to know what URL to point
/// its webview at.
pub fn port() -> u16 {
config::app::config()["app_port"]
.as_u64()
.and_then(|value| u16::try_from(value).ok())
.unwrap_or(34187)
}
/// Loads config and registers error pages - the first half of `serve()`,
/// split out so `route:list` can build just enough to print the route
/// table without connecting the database or attaching sessions.
/// `at_root`, not `new()` - see [`paths`]'s own doc comment for why a
/// real binary should always prefer it. Resolves the root the identical
/// `LARUST_APP_ROOT`-overridable way `paths()` itself does - this is
/// the function that actually constructs the live, serving
/// `Application`, so it's exactly the one call site where getting this
/// wrong would silently defeat the whole point of that override.
pub fn application() -> Result<larust_core::Application, larust_core::AppError> {
let app = larust_core::Application::at_root(
larust_core::resolve_app_root(env!("CARGO_MANIFEST_DIR")),
config::app::config,
)?;
// Renders once here, not per request - drop `resources/views/errors/
// 404.blade.xr`/`500.blade.xr` into your own app to override either;
// with no file there, this compiles to Larust's own built-in default.
Ok(app.with_error_pages(larust_core::ErrorPages {
not_found: larust_support::error_view!("404"),
internal: larust_support::error_view!("500"),
}))
}
/// The merged `web` + `api` route table - no sessions attached yet, since
/// `route:list` needs this much without a database. `.merge`, not
/// `.group` - keeps `routes::api`'s own middleware stack independent of
/// `routes::web`'s (CSRF among others); see `Router::merge`'s own doc
/// comment.
pub fn router(app: &larust_core::Application) -> larust_http::Router {
larust_support::wire::components()
// Register your app's own reactive components here, e.g.:
// .register::<crate::wire_components::MyComponent>()
.publish();
routes::web::routes().merge(&app.config().api_prefix, routes::api::routes())
}
/// Connects the database, attaches sessions, and serves - the shared core
/// both `main.rs`'s default (no-subcommand) path and any embedded host
/// need. Does NOT handle the `migrate`/`db:*`/`queue:work`/`schedule:work`/
/// `route:list` CLI subcommands - those stay in `main.rs`, CLI-only.
pub async fn serve() -> Result<(), larust_core::AppError> {
let app = application()?;
let route = router(&app);
connect_database().await?;
__DB_SERVE_SNIPPET__let route = route
.with_sessions(larust_support::orm::pool()?, app.config().session_secure_cookie)
.await?;
app.router(route.into_axum_router()).serve().await
}
"#;
/// `has_db` splices in [`DB_SERVE_SNIPPET`] (see its own doc comment) only
/// when the `db` optional feature was selected - mirrors [`main_rs`]'s
/// identical `__DB_MAIN_RS_SNIPPET__` handling for its own token.
fn lib_rs(has_db: bool) -> String {
let db_serve_snippet = if has_db { DB_SERVE_SNIPPET } else { "" };
LIB_RS.replace("__DB_SERVE_SNIPPET__", db_serve_snippet)
}
/// Cargo's own rule for deriving a library crate's `use`-path identifier
/// from a package name: hyphens become underscores, nothing else changes
/// (no case conversion) - needed because `validate_app_name` allows
/// hyphens (`xr new my-app`), but `use my-app::...` isn't valid Rust
/// syntax.
pub(crate) fn crate_ident(app_name: &str) -> String {
app_name.replace('-', "_")
}
// A real, passing example - not just an empty directory - so `xr new`
// produces a genuinely working test out of the box. Builds its own small
// router for just the one route under test (the same pattern this
// framework's own internal test suites already use, e.g.
// `larust-auth/tests/guard.rs`), rather than trying to replicate the
// route table in `src/main.rs` (which lives outside the library crate
// this file can `use`).
const TESTS_EXAMPLE_RS: &str = r#"use __CRATE__::controllers::PostController;
use larust_http::Route;
use larust_support::axum::http::StatusCode;
use larust_testing::{test_db, TestClient};
#[tokio::test]
async fn posts_index_loads() {
let pool = test_db(std::path::Path::new("database/migrations"))
.await
.unwrap();
let router = Route::get("/posts", PostController::index)
.with_sessions(&pool, false)
.await
.unwrap()
.into_axum_router();
let mut client = TestClient::new(router, &pool);
client.get("/posts").await.assert_status(StatusCode::OK);
}
"#;
// Mirrors `MAIN_RS_HEADER`'s own "one shared tail" reasoning: `index()` is
// identical regardless of `--auth`, only the route table itself (and its
// imports) differs, so it lives in one shared tail rather than being
// duplicated between two full-file constants.
const ROUTES_WEB_HEADER: &str = r#"use crate::controllers::PostController;
use larust_http::session::Session;
use larust_http::{Route, Router};
pub fn routes() -> Router {
let route = Route::get("/", index)
.get("/posts", PostController::index)
.name("posts.index")
.get("/posts/create", PostController::create)
.name("posts.create")
.get("/posts/{post}", PostController::show)
.name("posts.show")
.post("/posts", PostController::store)
.name("posts.store")
.plugin(larust_support::wire::WirePlugin)
.plugin(larust_support::spa::SpaPlugin)
.plugin(larust_support::image::ImagePlugin);
__DB_ROUTE_SNIPPET__route
.middleware(larust_http::axum::middleware::from_fn(
larust_http::csrf::verify,
))
.middleware(larust_http::axum::middleware::from_fn(
larust_http::locale::negotiate,
))
}
"#;
const ROUTES_WEB_HEADER_WITH_AUTH: &str = r#"use crate::controllers::{AuthController, CommentController, PostController};
use larust_http::session::Session;
use larust_http::{Route, Router};
use larust_support::auth::{redirect_authenticated, require_auth};
pub fn routes() -> Router {
let route = Route::get("/", index)
.get("/posts", PostController::index)
.name("posts.index")
.get("/posts/{post}", PostController::show)
.name("posts.show")
.plugin(larust_support::wire::WirePlugin)
.plugin(larust_support::spa::SpaPlugin)
.plugin(larust_support::image::ImagePlugin)
// Public read (anyone can watch a post's comments live); only
// *posting* one requires login, gated below inside the
// `require_auth` group like `posts.store`. Registered before
// `.with_sessions(...)` runs (in `main.rs`, after this function
// returns) so `reverb::socket`'s `Session` extractor actually has
// a session layer to read from.
.plugin(larust_support::reverb::ReverbPlugin)
// Creating a post requires login (Laravel's
// `Route::middleware('auth')->group(...)`) - group-scoped
// middleware only wraps the routes registered inside this closure,
// it never affects the read-only routes above.
.group("", |r: Router| {
r.middleware(larust_http::axum::middleware::from_fn(require_auth))
.get("/posts/create", PostController::create)
.name("posts.create")
.post("/posts", PostController::store)
.name("posts.store")
.post("/posts/{post}/comments", CommentController::store)
.name("posts.comments.store")
})
// The inverse: an already-logged-in user is bounced away from
// register/login (Laravel's `guest` middleware).
.group("", |r: Router| {
r.middleware(larust_http::axum::middleware::from_fn(
redirect_authenticated,
))
.get("/register", AuthController::show_register)
.name("register")
.post("/register", AuthController::register)
.name("register.store")
.get("/login", AuthController::show_login)
.name("login")
.post("/login", AuthController::login)
.name("login.store")
})
.post("/logout", AuthController::logout)
.name("logout");
// CSRF is a web-routes-only concern (it protects cookie-
// authenticated browser form submissions) - it must never reach
// `routes/api.rs`'s entries. That isolation comes from
// `src/main.rs` combining this router with `routes::api::routes()`
// via `Router::merge` (not `.group`, which deliberately shares a
// parent's top-level middleware with whatever it registers) - this
// call itself doesn't need to know or care where in the chain it
// sits relative to that.
__DB_ROUTE_SNIPPET__route
.middleware(larust_http::axum::middleware::from_fn(
larust_http::csrf::verify,
))
.middleware(larust_http::axum::middleware::from_fn(
larust_http::locale::negotiate,
))
}
"#;
const ROUTES_WEB_TAIL: &str = r#"
async fn index(session: Session) -> Result<impl larust_support::axum::response::IntoResponse, larust_core::AppError> {
let csrf_token = larust_http::csrf::token(&session).await;
let is_authenticated = larust_support::auth::check(&session).await?;
let nav_active = "home";
Ok(larust_support::view!("welcome", { csrf_token, is_authenticated, nav_active }))
}
"#;
const ROUTES_API_RS: &str = r#"// Mounted under the configured API prefix (`config/app.rs`'s
// `api_prefix`, `"/api"` by default) by `src/lib.rs`'s `router()` function's
// `Router::merge(&app.config().api_prefix, ...)` call, which keeps this
// router's own top-level middleware independent of `routes::web`'s (see
// `Router::merge`'s own doc comment for why that has to be `.merge`, not
// `.group`). Empty of app routes for now - add them here the same way
// `routes/web.rs` does, e.g. `Route::get("/posts", ApiPostController::index)`.
//
// Deliberately does *not* apply `.middleware(csrf::verify)` the way
// `routes/web.rs` does - CSRF protects cookie-authenticated browser form
// submissions specifically, which an API consumer doesn't participate in.
//
// Rate-limited by default (60 requests/minute per caller, keyed by their
// real IP address) - Laravel's own `throttle:60,1` default. Adjust or
// remove via `larust_http::throttle::per(max_requests, window)`.
//
// `locale::negotiate_from_header` is `routes/web.rs`'s session-based
// `locale::negotiate` for a router with no session at all - it reads the
// caller's `Accept-Language` header instead, so any translated error
// message returned from here still resolves through whatever locale the
// caller actually asked for.
use larust_http::Router;
pub fn routes() -> Router {
Router::new()
.middleware(larust_http::throttle::per_minute(60))
.middleware(larust_http::axum::middleware::from_fn(
larust_http::locale::negotiate_from_header,
))
}
"#;
const ROUTES_CONSOLE_RS: &str = r#"// Home for schedule declarations and named CLI commands - `src/main.rs`
// calls `schedule()`/`commands()` and hands the result to
// `larust_support::schedule::work`/`CommandRegistry::dispatch`.
use larust_support::console::CommandRegistry;
use larust_support::schedule::Schedule;
pub fn schedule() -> Schedule {
Schedule::new()
// Add your own scheduled tasks here, e.g.:
// .daily(|| async { ... Ok(()) })
}
pub fn commands() -> CommandRegistry {
CommandRegistry::new()
// Register your app's own Command types here, e.g.:
// .register::<crate::commands::ReportPosts>()
}
"#;
const ROUTES_MOD_RS: &str = "pub mod api;\npub mod console;\npub mod web;\n";
// Spliced into `ROUTES_WEB_HEADER`/`ROUTES_WEB_HEADER_WITH_AUTH` at the
// `__DB_ROUTE_SNIPPET__` token, only when `"db"` was selected - see
// `DB_MAIN_RS_SNIPPET`'s own doc comment for why this is presence/absence
// of a fixed snippet rather than `#[cfg]`. Router-build-time, not
// per-request: read once, when `routes()` runs. `try_config()`, not
// `config()` - the latter panics if `Application::new()` hasn't run yet,
// and `routes()` needs to stay callable standalone (a route-listing test
// building the router directly, with no `Application::new()` call
// anywhere, is a real pattern this codebase already uses - confirmed by a
// real panic caught in exactly that shape of test). Missing config reads
// as "not debug", matching `larust_http::session::cookie_name()`'s own
// `try_config()` precedent for the identical situation. Never reachable
// in a deployment that leaves `APP_DEBUG` at its production-safe `false`
// default - this is a dev tool (see `larust-db`'s own `DbPlugin` doc
// comment for the *second*, independent password gate that still applies
// regardless).
const DB_ROUTE_SNIPPET: &str = r#"let route = if larust_core::try_config().is_some_and(|c| c.app_debug) {
route.plugin(larust_support::db::DbPlugin)
} else {
route
};
"#;
fn routes_web_rs(auth: bool, crate_ident: &str, has_db: bool) -> String {
let header = if auth {
ROUTES_WEB_HEADER_WITH_AUTH
} else {
ROUTES_WEB_HEADER
};
let db_snippet = if has_db { DB_ROUTE_SNIPPET } else { "" };
format!("{header}{ROUTES_WEB_TAIL}")
.replace("__CRATE__", crate_ident)
.replace("__DB_ROUTE_SNIPPET__", db_snippet)
}
// `/storage/logs`/`/storage/releases` - both written to lazily at runtime
// (`crate::logging`'s rotating file writer, `release_slots::publish`), not
// pre-created by `APP_DIRS` above; a fresh app's own git repo (this
// template's gitignore, not this workspace's own broader one - see the
// repo root's own `.gitignore` for the equivalent Laravel-style `storage/`
// section that already covers `demo/`) would otherwise risk committing
// rotated log files or built release binaries the first time either
// actually gets used.
//
// `/database/*.sqlite-*` (alongside plain `*.sqlite`) is not optional
// hygiene - reported directly, from a real production incident: SQLite's
// WAL journal mode, which `larust_orm::pool::connect` enables
// unconditionally for every app (`PRAGMA journal_mode = WAL` - see that
// function's own doc comment), creates `database.sqlite-wal`/
// `database.sqlite-shm` sidecar files alongside the main database file
// during completely ordinary operation, not just in some unusual
// configuration. Without this line, a `git add .` happening to run while
// those files exist commits them - and since they only make sense
// alongside the *exact* main database file that produced them, a later
// `git pull` on a *different* running instance (a server whose own
// database has since diverged) overwrites its WAL/SHM state with a
// mismatched snapshot from the committing machine, corrupting it (`PRAGMA
// integrity_check` reporting "database disk image is malformed" is
// exactly what this looks like). Plain `*.sqlite` alone doesn't match
// either suffix at all - `-wal`/`-shm` are appended to the *whole*
// filename, not swapped in as a different extension - so this gap was
// there from this template's very first version, not a regression.
const GITIGNORE: &str = "/target\n.env\n.env.local\n/database/*.sqlite\n/database/*.sqlite-*\n\
/storage/logs\n/storage/releases\n";
// VS Code has no built-in language mode for `.blade.xr` - without this,
// every template opens as plain text with zero syntax highlighting.
// "blade" (registered by the recommended `onecentlin.laravel-blade`
// extension - see VSCODE_EXTENSIONS_JSON below) gives real `@if`/
// `@foreach`/`{{ }}` directive highlighting, not just the surrounding
// HTML. If that extension isn't installed, VS Code falls back to treating
// the file as plain text (no highlighting at all) rather than erroring -
// the `extensions.json` recommendation is what makes declining that a
// deliberate choice instead of a silent downgrade.
// `material-icon-theme.files.associations` maps `.blade.xr` onto that
// extension's own built-in "laravel" icon (confirmed against its source -
// it ships a Laravel icon, but keys it on `.blade.php`/`.inky.php` only,
// so `.blade.xr` gets a generic file icon without this override). A no-op
// if that particular icon theme isn't installed/active - same soft,
// additive shape as the syntax-highlighting recommendation below.
const VSCODE_SETTINGS_JSON: &str = r#"{
"files.associations": {
"*.blade.xr": "blade"
},
"material-icon-theme.files.associations": {
"*.blade.xr": "laravel"
}
}
"#;
const VSCODE_EXTENSIONS_JSON: &str = r#"{
"recommendations": [
"onecentlin.laravel-blade",
"pkief.material-icon-theme"
]
}
"#;
/// Scaffolds a plain `xr new <path>` app, also turning on the given
/// `larust-support` Tier-1 shim features (`xr new --features
/// permissions,sanctum`, or the interactive wizard's own multi-select -
/// see `wizard.rs`'s `OPTIONAL_FEATURES`) - the same `features = [...]`
/// mechanism `xr convert` already uses via `new_app_from_workspace`, just
/// with the workspace root auto-detected (walking up from the target
/// directory) instead of given explicitly. Before this existed, a
/// developer who wanted e.g. `permissions` had no way to ask for it from
/// `xr new` at all - only hand-editing the generated `Cargo.toml`'s
/// `larust-support` line afterward (documented in its own doc comment
/// there) or going through `xr convert` on a Laravel app whose
/// `composer.json` already required the equivalent package. Pass `&[]`
/// for the no-optional-features case - that's every call site in this
/// module's own tests below, and `main.rs`'s own `Command::New` dispatch
/// when the wizard/`--features` selected nothing.
pub fn new_app_with_features(
target: &str,
auth: bool,
support_features: &[&str],
tauri: bool,
) -> Result<()> {
new_app_with_workspace(target, auth, None, support_features, tauri)
}
/// Scaffolds an application using `workspace_root` to resolve Larust's local
/// path dependencies, even when the target is outside that workspace.
///
/// `xr convert --out` needs this form: the converted project is commonly a
/// sibling of the source Laravel application rather than a child of the
/// Larust checkout that provides the unpublished framework crates.
/// `support_features` is `composer::required_features(&packages)` - the
/// `larust-support` Cargo features the source app's own `composer.json`
/// implies (see that function's own doc comment).
pub fn new_app_from_workspace(
target: &str,
auth: bool,
workspace_root: &Path,
support_features: &[&str],
tauri: bool,
) -> Result<()> {
new_app_with_workspace(target, auth, Some(workspace_root), support_features, tauri)
}
fn new_app_with_workspace(
target: &str,
auth: bool,
workspace_root: Option<&Path>,
support_features: &[&str],
tauri: bool,
) -> Result<()> {
let root = PathBuf::from(target);
let target_is_nonempty = if root.exists() {
!root.is_dir()
|| std::fs::read_dir(&root)
.with_context(|| format!("reading target directory {}", root.display()))?
.next()
.is_some()
} else {
false
};
anyhow::ensure!(
!target_is_nonempty,
"target directory `{}` already exists and is not empty",
root.display()
);
if let Err(err) = scaffold(&root, auth, workspace_root, support_features, tauri) {
// Best-effort cleanup: don't leave a half-written project behind
// that then blocks a retry with "already exists".
let _ = std::fs::remove_dir_all(&root);
return Err(err);
}
println!("Created new Larust application at {}", root.display());
Ok(())
}
// Paths for the demo `Post` scaffold (model/controller/migration/views/test)
// that `remove_demo_scaffold` (crates/larust-cli/src/convert.rs) strips back
// out of a converted Laravel app. Named here, next to the `write_file` calls
// that actually produce them, and consumed directly by `convert.rs` via
// `DEMO_SCAFFOLD_FILES`/`DEMO_SCAFFOLD_MOD_FILES` so the two lists can't
// silently drift apart the way two independently hardcoded copies could.
const POST_CONTROLLER_PATH: &str = "app/Http/Controllers/post_controller.rs";
const STORE_POST_REQUEST_PATH: &str = "app/Http/Requests/store_post_request.rs";
const POST_MODEL_PATH: &str = "app/Models/post.rs";
const CREATE_POSTS_TABLE_PATH: &str = "database/migrations/0001_create_posts_table.sql";
const TESTS_EXAMPLE_PATH: &str = "tests/posts_test.rs";
const LAYOUT_APP_BLADE_XR_PATH: &str = "resources/views/layouts/app.blade.xr";
const WELCOME_BLADE_XR_PATH: &str = "resources/views/welcome.blade.xr";
const LANG_EN_JSON_PATH: &str = "resources/lang/en.json";
const POSTS_INDEX_BLADE_XR_PATH: &str = "resources/views/posts/index.blade.xr";
const POSTS_CREATE_BLADE_XR_PATH: &str = "resources/views/posts/create.blade.xr";
const CONTROLLERS_MOD_PATH: &str = "app/Http/Controllers/mod.rs";
const REQUESTS_MOD_PATH: &str = "app/Http/Requests/mod.rs";
const MODELS_MOD_PATH: &str = "app/Models/mod.rs";
/// Files that only exist because of the demo `Post` scaffold - deleted
/// outright by `remove_demo_scaffold` when converting a real Laravel app.
pub(crate) const DEMO_SCAFFOLD_FILES: &[&str] = &[
POST_CONTROLLER_PATH,
STORE_POST_REQUEST_PATH,
POST_MODEL_PATH,
CREATE_POSTS_TABLE_PATH,
TESTS_EXAMPLE_PATH,
LAYOUT_APP_BLADE_XR_PATH,
WELCOME_BLADE_XR_PATH,
POSTS_INDEX_BLADE_XR_PATH,
POSTS_CREATE_BLADE_XR_PATH,
];
/// `mod.rs` files that reference the demo scaffold and get reset to empty
/// (rather than deleted, since the directory itself must stay a valid
/// module) by `remove_demo_scaffold`.
pub(crate) const DEMO_SCAFFOLD_MOD_FILES: &[&str] =
&[CONTROLLERS_MOD_PATH, REQUESTS_MOD_PATH, MODELS_MOD_PATH];
fn scaffold(
root: &Path,
auth: bool,
workspace_root: Option<&Path>,
support_features: &[&str],
tauri: bool,
) -> Result<()> {
let app_name = validate_app_name(root)?;
write_dir(root)?;
// Requires `root` to already exist on disk (canonicalize needs a real
// path), and is the step most likely to fail (no ambient workspace) -
// do it before creating the rest of the tree so failure leaves as
// little behind as possible.
let target_abs = root
.canonicalize()
.with_context(|| format!("resolving {}", root.display()))?;
// `Some(_)` only when `--workspace <path>` was given explicitly - every
// Larust crate is published to crates.io now, so there's nothing to
// auto-discover by walking up from the target anymore (the old
// behavior, before this - deliberately not replaced with an
// auto-detect-if-we-happen-to-be-inside-a-checkout fallback: this
// codebase's own convention is explicit, not inferred, and that
// fallback would make `xr new`'s own output depend on *where you
// happened to run it from*, not what you asked for). `None` here
// means `crate_dependency` resolves every framework crate as a plain
// `version = "..."` dependency instead of a local `path` one - no
// checkout needed at all.
let ws_root = match workspace_root {
Some(root) => {
let root = root
.canonicalize()
.with_context(|| format!("resolving Larust workspace {}", root.display()))?;
anyhow::ensure!(
root.join("Cargo.toml").is_file(),
"Larust workspace {} has no Cargo.toml",
root.display()
);
Some(root)
}
None => None,
};
// `--auth` always generates the comments example (see the `if auth`
// block below), which is the one thing in this starter app that
// actually calls `larust_support::reverb`, so `reverb` needs to be a
// real compiled-in feature whenever `auth` is set - regardless of
// whatever `support_features` already carries from elsewhere
// (`composer::required_features`, for `xr convert`; whatever `xr new
// --features ...`/the interactive wizard selected, for a plain `xr
// new`). This turning-on is unconditional and not user-visible as a
// choice at all - unlike every other Tier-1 shim feature, which is
// strictly opt-in (see `new_app_with_features`'s own doc comment) -
// because it isn't a Laravel-package equivalent a developer decides to
// adopt; it's this starter's own baseline example needing the crate it
// demonstrates.
let mut resolved_support_features: Vec<&str> = support_features.to_vec();
if auth {
resolved_support_features.push("reverb");
}
// Exactly one sqlx driver, always - `larust-support`'s own default
// (`default = ["sqlite"]`) only exists for an app scaffolded before
// this feature did; every app scaffolded from here on picks one
// explicitly and turns that default off (see `crate_dependency`'s own
// `default_features` handling below). `xr new` never asks (matches
// `DB_CONNECTION`'s own `"sqlite"` default exactly - zero new CLI/
// wizard surface); `xr convert` already knows the source Laravel
// app's real driver and pushes the matching feature into
// `support_features` itself before calling here (see
// `convert.rs::detect_target_driver`), so this only ever falls back
// to `"sqlite"` when nothing more specific was already requested.
if !resolved_support_features
.iter()
.any(|f| matches!(*f, "sqlite" | "mysql" | "postgres"))
{
resolved_support_features.push("sqlite");
}
resolved_support_features.sort_unstable();
resolved_support_features.dedup();
// Drives `main_rs`/`routes_web_rs`'s own snippet splicing - see
// `DB_MAIN_RS_SNIPPET`'s doc comment for why that's presence/absence of
// fixed text rather than `#[cfg]`.
let has_db = resolved_support_features.contains(&"db");
// The same one driver `resolved_support_features` above guarantees is
// present, needed again by `cargo_toml()` for the app's own *direct*
// `sqlx` dependency line (`#[derive(Model)]`'s `sqlx::FromRow` can't be
// reached through `larust-support`'s re-export - see that call site's
// own comment) - without this, a converted MySQL/Postgres app would
// still only ever get a `sqlite`-only sqlx build, unable to actually
// connect.
let db_driver_feature = resolved_support_features
.iter()
.find(|f| matches!(**f, "sqlite" | "mysql" | "postgres"))
.expect("exactly one sqlx driver feature was pushed above");
let deps: Vec<(&str, String)> = FRAMEWORK_CRATES
.iter()
.map(|name| {
// Only `larust-support` has optional Tier-1 shim features to
// turn on - every other framework crate always gets `&[]`
// (byte-for-byte the same dependency line as before this
// parameter existed).
let is_support = *name == "larust-support";
let features: &[&str] = if is_support {
&resolved_support_features
} else {
&[]
};
// `default-features = false` for `larust-http` too, not just
// `larust-support`: the app depends on `larust-http` *directly*
// here (it's in `FRAMEWORK_CRATES`), a second, independent
// edge to the same crate `larust-support`'s own cascade (see
// its `Cargo.toml`) doesn't control - leaving this edge's
// `default-features` at `true` would silently re-activate
// `larust-http`'s own `default = ["sqlite", "mysql",
// "postgres"]` (see `larust-orm/Cargo.toml`'s comment on that
// shape) regardless of what the `larust-support` edge
// selected, defeating the whole point (confirmed empirically
// via `cargo tree -i sqlx-mysql` before this fix - `sqlx-mysql`
// was still present through exactly this second path).
// `larust-core` has no such features to lose either way, but
// is included here too rather than special-cased out, so a
// future feature on it doesn't silently reopen this same gap.
let default_features = *name == "larust-core";
Ok((
*name,
crate_dependency(
ws_root.as_deref(),
&target_abs,
name,
features,
default_features,
)?,
))
})
.collect::<Result<_>>()?;
let dev_deps: Vec<(&str, String)> = DEV_FRAMEWORK_CRATES
.iter()
.map(|name| {
Ok((
*name,
crate_dependency(ws_root.as_deref(), &target_abs, name, &[], true)?,
))
})
.collect::<Result<_>>()?;
for dir in APP_DIRS {
write_dir(&root.join(dir))?;
}
write_dir(&root.join("src"))?;
write_file(
&root.join("Cargo.toml"),
cargo_toml(&app_name, &deps, &dev_deps, db_driver_feature),
)?;
write_file(&root.join("src/lib.rs"), lib_rs(has_db))?;
write_file(
&root.join("src/main.rs"),
main_rs(&crate_ident(&app_name), has_db),
)?;
write_file(
&root.join(TESTS_EXAMPLE_PATH),
TESTS_EXAMPLE_RS.replace("__CRATE__", &crate_ident(&app_name)),
)?;
write_file(
&root.join(CONTROLLERS_MOD_PATH),
if auth {
CONTROLLERS_MOD_RS_WITH_AUTH
} else {
CONTROLLERS_MOD_RS
},
)?;
write_file(
&root.join(POST_CONTROLLER_PATH),
if auth {
POST_CONTROLLER_RS_WITH_AUTH
} else {
POST_CONTROLLER_RS
},
)?;
write_file(
&root.join(REQUESTS_MOD_PATH),
if auth {
REQUESTS_MOD_RS_WITH_AUTH
} else {
REQUESTS_MOD_RS
},
)?;
write_file(&root.join(STORE_POST_REQUEST_PATH), STORE_POST_REQUEST_RS)?;
write_file(
&root.join(MODELS_MOD_PATH),
if auth {
MODELS_MOD_RS_WITH_AUTH
} else {
MODELS_MOD_RS
},
)?;
write_file(
&root.join(POST_MODEL_PATH),
if auth {
POST_MODEL_RS_WITH_AUTH
} else {
POST_MODEL_RS
},
)?;
write_file(&root.join("app/Http/Middleware/mod.rs"), MIDDLEWARE_MOD_RS)?;
write_file(&root.join("app/Policies/mod.rs"), POLICIES_MOD_RS)?;
write_file(&root.join("app/Mail/mod.rs"), MAIL_MOD_RS)?;
write_file(&root.join("app/Jobs/mod.rs"), JOBS_MOD_RS)?;
write_file(&root.join("app/Events/mod.rs"), EVENTS_MOD_RS)?;
write_file(&root.join("app/Console/Commands/mod.rs"), COMMANDS_MOD_RS)?;
write_file(&root.join("app/Wire/mod.rs"), WIRE_MOD_RS)?;
write_file(&root.join("database/factories/mod.rs"), FACTORIES_MOD_RS)?;
write_file(&root.join("database/seeders/mod.rs"), SEEDERS_MOD_RS)?;
write_file(
&root.join(CREATE_POSTS_TABLE_PATH),
if auth {
CREATE_POSTS_TABLE_SQL_WITH_AUTH
} else {
CREATE_POSTS_TABLE_SQL
},
)?;
write_file(&root.join(LAYOUT_APP_BLADE_XR_PATH), LAYOUT_APP_BLADE_XR)?;
write_file(&root.join(WELCOME_BLADE_XR_PATH), WELCOME_BLADE_XR)?;
write_file(&root.join(LANG_EN_JSON_PATH), LANG_EN_JSON)?;
write_file(
&root.join(POSTS_INDEX_BLADE_XR_PATH),
if auth {
POSTS_INDEX_BLADE_XR_WITH_AUTH
} else {
POSTS_INDEX_BLADE_XR
},
)?;
write_file(
&root.join(POSTS_CREATE_BLADE_XR_PATH),
POSTS_CREATE_BLADE_XR,
)?;
write_file(&root.join("routes/mod.rs"), ROUTES_MOD_RS)?;
write_file(
&root.join("routes/web.rs"),
routes_web_rs(auth, &crate_ident(&app_name), has_db),
)?;
write_file(&root.join("routes/api.rs"), ROUTES_API_RS)?;
write_file(&root.join("routes/console.rs"), ROUTES_CONSOLE_RS)?;
write_file(&root.join("config/app.rs"), config_app_rs(&app_name))?;
write_file(
&root.join("config/database.rs"),
config_template::render_database_config_rs(),
)?;
write_file(
&root.join("config/mod.rs"),
"pub mod app;\npub mod database;\n",
)?;
write_file(&root.join(".env"), dot_env_contents(tauri))?;
write_file(&root.join(".gitignore"), GITIGNORE)?;
write_file(&root.join(".vscode/settings.json"), VSCODE_SETTINGS_JSON)?;
write_file(
&root.join(".vscode/extensions.json"),
VSCODE_EXTENSIONS_JSON,
)?;
if tauri {
write_tauri_scaffold(root, &crate_ident(&app_name), &app_name)?;
}
if auth {
write_dir(&root.join("resources/views/auth"))?;
write_file(
&root.join("app/Http/Requests/register_request.rs"),
REGISTER_REQUEST_RS,
)?;
write_file(
&root.join("app/Http/Requests/login_request.rs"),
LOGIN_REQUEST_RS,
)?;
write_file(&root.join("app/Models/user.rs"), USER_MODEL_RS)?;
write_file(
&root.join("app/Http/Controllers/auth_controller.rs"),
AUTH_CONTROLLER_RS,
)?;
write_file(
&root.join("resources/views/auth/register.blade.xr"),
AUTH_REGISTER_BLADE_XR,
)?;
write_file(
&root.join("resources/views/auth/login.blade.xr"),
AUTH_LOGIN_BLADE_XR,
)?;
write_file(
&root.join("database/migrations/0002_create_users_table.sql"),
CREATE_USERS_TABLE_SQL,
)?;
// Live comments - the one piece of this starter that demonstrates
// `larust_support::reverb` (see `resolved_support_features`
// above). Needs a `User` to attribute a comment to, so it's
// auth-only, unlike everything else in this function.
write_file(&root.join("app/Models/comment.rs"), COMMENT_MODEL_RS)?;
write_file(
&root.join("app/Http/Requests/store_comment_request.rs"),
STORE_COMMENT_REQUEST_RS,
)?;
write_file(
&root.join("app/Http/Controllers/comment_controller.rs"),
COMMENT_CONTROLLER_RS,
)?;
write_file(
&root.join("resources/views/posts/show.blade.xr"),
POSTS_SHOW_BLADE_XR_WITH_AUTH,
)?;
write_file(
&root.join("database/migrations/0003_create_comments_table.sql"),
CREATE_COMMENTS_TABLE_SQL,
)?;
}
Ok(())
}
/// Validates that the target path's final component is safe to interpolate
/// into generated Rust identifiers and string literals (package name,
/// `config/app.rs`'s own `app_name` default). Rejecting anything outside a
/// conservative charset up front means the generator never has to worry
/// about escaping quotes or control characters.
fn validate_app_name(root: &Path) -> Result<String> {
let app_name = root
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("larust-app")
.to_string();
anyhow::ensure!(
!app_name.is_empty()
&& app_name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'),
"invalid application name `{app_name}`: use only letters, digits, `-`, and `_`"
);
// `app_name` itself only ever became a Cargo package name and a
// private `mod` declaration before `lib.rs`/`__CRATE__` existed, so a
// leading digit or a Rust keyword was harmless. Now `crate_ident`
// (hyphens→underscores) gets substituted directly into `use
// {crate_ident}::...` paths in `main.rs`/`tests/posts_test.rs`, so it
// has to be validated as a real Rust identifier - reusing
// `larust_convert::codegen::validate_identifier` (charset, leading
// digit, Rust keywords, and `__WORD__`-shaped placeholder collisions)
// rather than duplicating that logic here. Checking
// `crate_ident(&app_name)` itself, not the pre-transform `app_name`,
// matters: a hyphenated name that's harmless on its own (`--CRATE--`)
// can still transform into something placeholder-shaped (`__CRATE__`)
// once hyphens become underscores.
larust_convert::codegen::validate_identifier(&crate_ident(&app_name))
.with_context(|| format!("invalid application name `{app_name}`"))?;
Ok(app_name)
}
pub(crate) fn write_dir(path: &Path) -> Result<()> {
std::fs::create_dir_all(path).with_context(|| format!("creating {}", path.display()))
}
pub(crate) fn write_file(path: &Path, contents: impl AsRef<[u8]>) -> Result<()> {
std::fs::write(path, contents).with_context(|| format!("writing {}", path.display()))
}
/// Strips `canonicalize()`'s own `\\?\` verbatim-path prefix, if present -
/// a no-op on Unix (that prefix is Windows-only, `canonicalize()` there
/// never adds one) and a no-op for any path that never carried it. Needed
/// because that prefix, embedded as a `Cargo.toml` `path = "..."` value,
/// is what makes Cargo's manifest parser reject it outright with "invalid
/// path url" - a plain absolute path with the identical target, minus
/// just this prefix, parses and resolves fine (confirmed directly against
/// a real scratch crate, cross-drive included).
fn strip_verbatim_prefix(path: &Path) -> PathBuf {
const VERBATIM_PREFIX: &str = r"\\?\";
match path.to_str() {
Some(s) if s.starts_with(VERBATIM_PREFIX) => PathBuf::from(&s[VERBATIM_PREFIX.len()..]),
_ => path.to_path_buf(),
}
}
/// The version every crates.io-mode dependency (`ws_root: None` below)
/// pins against - `larust-cli`'s own compiled-in package version, not a
/// hardcoded literal, so a future `xr release` version bump can't silently
/// drift out of sync with what newly-scaffolded apps actually ask for. A
/// plain `"0.5.0"` string is already a caret requirement by Cargo's own
/// default (`^0.5.0`, not an exact pin) - nothing extra needed for normal
/// patch/compatible updates to keep resolving.
const FRAMEWORK_VERSION: &str = env!("CARGO_PKG_VERSION");
/// Resolves a framework crate as a dependency of the app being scaffolded.
/// `ws_root: Some(_)` is `--workspace` mode (a `path` dependency, relative
/// to `target_abs` when possible - exactly today's long-standing
/// behavior, for contributors scaffolding a test app against local,
/// possibly-unpublished framework changes). `ws_root: None` is the default
/// since every Larust crate is now on crates.io: a plain `version =
/// "...\"` dependency, no checkout needed at all.
///
/// `features` is almost always empty (every framework crate except
/// `larust-support` has no optional features at all) - when non-empty,
/// appends a `features = [...]` field, the mechanism `xr convert` uses to
/// turn `composer.json`'s own `require` block into which of
/// `larust-support`'s optional Tier-1 shim features the generated
/// `Cargo.toml` turns on (see `composer::required_features`).
/// `default_features = false` is only ever needed for `larust-support`
/// today - it now always carries exactly one `sqlite`/`mysql`/`postgres`
/// driver feature (see `scaffold()`'s own `resolved_support_features`
/// handling), replacing its own `default = ["sqlite"]` fallback (kept
/// there purely for an *already-scaffolded* app generated before this
/// feature existed - see `larust-support/Cargo.toml`'s own comment) rather
/// than adding to it.
fn crate_dependency(
ws_root: Option<&Path>,
target_abs: &Path,
crate_name: &str,
features: &[&str],
default_features: bool,
) -> Result<String> {
let Some(ws_root) = ws_root else {
let mut parts = vec![format!("version = \"{FRAMEWORK_VERSION}\"")];
if !default_features {
parts.push("default-features = false".to_string());
}
if !features.is_empty() {
let feature_list = features
.iter()
.map(|f| format!("\"{f}\""))
.collect::<Vec<_>>()
.join(", ");
parts.push(format!("features = [{feature_list}]"));
}
return Ok(format!("{{ {} }}", parts.join(", ")));
};
let crate_path = ws_root.join("crates").join(crate_name);
let rel = pathdiff::diff_paths(&crate_path, target_abs).with_context(|| {
format!(
"could not compute a relative path to {crate_name} \
(target and workspace may be on different drives)"
)
})?;
// `pathdiff::diff_paths` never actually returns `None` for this on
// Windows - confirmed directly, not assumed: given two canonicalized
// absolute paths with no common root (e.g. the new app on `C:` and
// the workspace checkout on `E:` - a real case, not hypothetical:
// `xr convert` deliberately resolves the workspace from its own
// compile-time checkout regardless of wherever `--out` points, and
// GitHub's hosted Windows runners checkout to `D:` while `TEMP`
// resolves to `C:`), it silently falls back to returning `crate_path`
// itself, verbatim and still absolute, rather than failing. The
// `.with_context(...)` above is dead code for this real failure mode,
// not a safety net.
//
// No relative path is *expressible* here - Windows has none across
// drive letters, full stop - but that doesn't mean this has to be an
// error: a plain absolute path dependency (`path = "E:/vsprojects/
// Larust/crates/larust-core"`, no prefix) resolves and builds
// correctly, cross-drive included - confirmed directly against a real
// scratch crate. What actually breaks is `canonicalize()`'s own
// `\\?\`-prefixed verbatim syntax riding along in `rel` here (still
// `crate_path`, unchanged) - Cargo's manifest parser rejects that
// outright with "invalid path url", a confusing failure one `cargo
// build` away from its real cause. Stripping just that prefix - not
// rejecting the cross-drive case outright - is what actually fixes
// the original bug report without also breaking `xr convert`'s own
// documented "destination lives anywhere" design.
let path = if rel.is_relative() {
rel.to_string_lossy().replace('\\', "/")
} else {
strip_verbatim_prefix(&rel)
.to_string_lossy()
.replace('\\', "/")
};
let mut parts = vec![format!("path = \"{path}\"")];
if !default_features {
parts.push("default-features = false".to_string());
}
if !features.is_empty() {
let feature_list = features
.iter()
.map(|f| format!("\"{f}\""))
.collect::<Vec<_>>()
.join(", ");
parts.push(format!("features = [{feature_list}]"));
}
Ok(format!("{{ {} }}", parts.join(", ")))
}
fn cargo_toml(
app_name: &str,
deps: &[(&str, String)],
dev_deps: &[(&str, String)],
db_driver_feature: &str,
) -> String {
let mut out = format!(
"[package]\nname = \"{app_name}\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[dependencies]\n"
);
for (name, dep) in deps {
out.push_str(&format!("{name} = {dep}\n"));
}
out.push_str("tokio = { version = \"1\", features = [\"full\"] }\n");
// sqlx's own `#[derive(FromRow)]` generates code referencing `::sqlx::...`
// directly - it doesn't honor a local `use larust_support::orm::sqlx;`
// alias, so unlike the rest of the framework it can't be fully hidden
// behind `larust-support`. This is a real limitation of sqlx (and
// several other derive-macro crates), not a Larust design choice.
// `db_driver_feature` mirrors whatever driver `larust-support`'s own
// dependency line above just selected - see `scaffold()`'s own
// `db_driver_feature` comment for why this can't just always say
// `"sqlite"` (a converted MySQL/Postgres app needs to actually be able
// to connect).
out.push_str(&format!(
"sqlx = {{ version = \"0.8\", default-features = false, features = [\"runtime-tokio\", \"{db_driver_feature}\", \"derive\"] }}\n",
));
// Same limitation, same reasoning as `sqlx` above: `#[derive(Serialize,
// Deserialize)]` generates code referencing `::serde::...` directly,
// not honoring a `larust_support`-re-exported alias, so a `Job`'s own
// payload struct - a real app-defined type, not a framework internal -
// needs `serde` as a direct dependency to derive against. `Event`
// payloads need no such exception: `Event` is `Clone`-based, never
// serialized.
out.push_str("serde = { version = \"1\", features = [\"derive\"] }\n");
// A transitive dependency (pulled in via ICU/URL-parsing crates several
// framework crates use), pinned here for the same reason this repo's
// own root `Cargo.toml`/`Cargo.lock` already resolve to it rather than
// 1.13.0: `tinyvec` 1.13.0 fails to compile under rustc 1.98+ ("cannot
// find macro `vec` in this scope" - confirmed live, reproduced and
// fixed by pinning to this exact version). A freshly scaffolded app has
// no lockfile of its own yet, so without this it would resolve fresh to
// whatever crates.io currently has as latest - silently inheriting that
// break the moment someone runs `xr new` on an affected toolchain, with
// no framework code of their own to blame. Remove once a fixed release
// ships upstream.
out.push_str("tinyvec = \"=1.12.0\"\n");
out.push_str("\n[dev-dependencies]\n");
for (name, dep) in dev_deps {
out.push_str(&format!("{name} = {dep}\n"));
}
out.push_str(include_str!("build_profiles.toml"));
out
}
/// `config/app.rs`'s content for a freshly scaffolded app - the same
/// literal defaults `config_app_toml` (this function's TOML-era
/// predecessor) used, re-expressed via [`config_template::render_app_config_rs`]'s
/// shared `env_or`/`env_bool`-backed template so `.env` can still override
/// any of them, matching `xr convert`'s own use of the same template.
/// `tauri` picks which of the two mutually exclusive `DEPLOY_TYPE` example
/// lines is left active - see [`write_tauri_scaffold`]'s own doc comment
/// for why `xr new --tauri`/`xr add tauri` are the only two writers of an
/// uncommented `DEPLOY_TYPE=app` line.
fn dot_env_contents(tauri: bool) -> String {
let deploy_type_line = if tauri {
"DEPLOY_TYPE=app\n"
} else {
"# DEPLOY_TYPE=web\n"
};
format!(
"APP_ENV=local\nAPP_PORT=34187\n\
# Which named connection below is active - sqlite, mysql, mariadb,\n\
# pgsql, or sqlsrv (see config/database.rs). sqlsrv isn't connectable\n\
# via this framework's ORM at all - see the larust-mssql crate.\n\
DB_CONNECTION=sqlite\n\
# DB_HOST=127.0.0.1\n\
# DB_PORT=3306\n\
# DB_DATABASE=larust\n\
# DB_USERNAME=root\n\
# DB_PASSWORD=\n\
# DB_CHARSET=utf8mb4\n\
# Base URL used by url()/asset() to build absolute URLs from a relative path.\n\
APP_URL=http://localhost\n\
# t()/t_with() resolve against this locale by default; APP_FALLBACK_LOCALE is\n\
# tried next when a key is missing from the current locale's own translation\n\
# file (see resources/lang/en.json). No effect until a route actually attaches\n\
# larust_http::locale::negotiate - see routes/web.rs.\n\
APP_LOCALE=en\n\
APP_FALLBACK_LOCALE=en\n\
# Browsers only treat loopback/`localhost` as a secure context over plain HTTP.\n\
# Set this to false if you serve local dev from a custom hostname (e.g. a .test\n\
# domain in /etc/hosts) or the session cookie will be silently dropped.\n\
SESSION_SECURE_COOKIE=true\n\
# \"database\" (default) - sessions live in DB_CONNECTION's database. \"file\"\n\
# writes one file per session to storage/sessions/ instead - no database\n\
# round trip for session reads/writes, at the cost of only working on a single\n\
# server (every process needs to see the same directory).\n\
# SESSION_DRIVER=database\n\
# Renders full error detail (message, source chain, panics) as an HTML page\n\
# instead of a generic \"internal server error\". Never enable outside local dev.\n\
APP_DEBUG=true\n\
# \"stdout\" (default) - everything goes to the terminal. \"file\" writes to\n\
# storage/logs/larust.log instead (rotated once it passes LOG_MAX_SIZE, oldest\n\
# kept backups deleted beyond LOG_KEEP_FILES). \"stack\" does both at once.\n\
# LOG_CHANNEL=stdout\n\
# trace/debug/info/warn/error - leave unset to keep this framework's own\n\
# default (verbose locally, quieter in any other APP_ENV).\n\
# LOG_LEVEL=debug\n\
# LOG_MAX_SIZE=10485760\n\
# LOG_KEEP_FILES=5\n\
# \"log\" writes a mail's rendered subject/body to the app's own log output\n\
# instead of sending it - no SMTP server needed for local dev or `cargo test`.\n\
# Set this to \"smtp\" and fill in the fields below to send for real.\n\
MAIL_DRIVER=log\n\
# MAIL_HOST=smtp.example.com\n\
# Port 587 (the standard submission port almost every real provider\n\
# expects) needs \"starttls\", not \"tls\" (implicit TLS, port 465's\n\
# convention) - pick the pairing that matches your provider's setup.\n\
# MAIL_PORT=587\n\
# MAIL_USERNAME=\n\
# MAIL_PASSWORD=\n\
# MAIL_ENCRYPTION=starttls\n\
# MAIL_FROM_ADDRESS=hello@example.com\n\
# MAIL_FROM_NAME=\n\
# \"database\" stores cache/queue entries in the same connection\n\
# config/database.rs selects above; \"redis\" uses Redis instead.\n\
# CACHE_DRIVER=database\n\
# QUEUE_DRIVER=database\n\
# \"web\" (default) - an ordinary server, published via `xr deploy`.\n\
# \"app\" - a Tauri desktop build, published via `xr deploy` from\n\
# src-tauri/ (scaffold it first with `xr add tauri` if you didn't\n\
# pass --tauri to `xr new`).\n\
{deploy_type_line}"
)
}
const TAURI_CARGO_TOML: &str = r#"[package]
name = "__PACKAGE__-tauri"
version = "0.1.0"
edition = "2021"
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
__PACKAGE__ = { path = ".." }
tauri = { version = "2", features = [] }
tokio = { version = "1", features = ["rt-multi-thread"] }
[[bin]]
name = "__PACKAGE__-tauri"
path = "src/main.rs"
"#;
const TAURI_BUILD_RS: &str = "fn main() {\n tauri_build::build();\n}\n";
const TAURI_MAIN_RS: &str = r#"// Spawns the same `__CRATE__::serve()` this app's ordinary web binary
// (`src/main.rs`) calls, on a background thread of its own runtime, then
// points a native webview at it - the "embedded local server" model: one
// router, one set of business logic, reached over loopback HTTP instead of
// duplicated behind a second frontend stack.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
let runtime = tokio::runtime::Runtime::new()
.expect("failed to start the embedded server's async runtime");
let handle = runtime.handle().clone();
std::thread::spawn(move || {
handle.block_on(async {
if let Err(err) = __CRATE__::serve().await {
eprintln!("embedded server exited: {err}");
}
});
});
let url = format!("http://127.0.0.1:{}", __CRATE__::port());
tauri::Builder::default()
.setup(move |app| {
let target = tauri::WebviewUrl::External(url.parse().expect("valid embedded server URL"));
tauri::WebviewWindowBuilder::new(app, "main", target)
.title("__APP_NAME__")
.build()?;
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running the Tauri application");
}
"#;
/// Written by both `scaffold()` (when `xr new --tauri`) and `xr add tauri`
/// (`add.rs`, retrofitting an already-scaffolded app) - the single code
/// path that writes `src-tauri/`, so the two entry points can't drift.
/// `src-tauri/Cargo.toml` deliberately depends on the parent app crate via
/// a plain `path = ".."` rather than joining it as a workspace member - the
/// app root has no `[workspace]` table of its own (`find_workspace_root`
/// only ever looks *upward*, for the ambient Larust checkout), so this is a
/// perfectly ordinary sibling crate, the same split
/// `create-tauri-app`-style scaffolds use. No icon files are generated
/// here - `cargo tauri dev` doesn't need any, and `cargo tauri build`'s
/// install-style hint if `src-tauri/icons/` is still empty (`deploy.rs`'s
/// `deploy_app`) is cheaper than shipping an image-processing dependency
/// in `xr` just to produce placeholder art nobody keeps.
pub(crate) fn write_tauri_scaffold(root: &Path, crate_ident: &str, app_name: &str) -> Result<()> {
write_dir(&root.join("src-tauri/src"))?;
write_dir(&root.join("src-tauri/icons"))?;
write_file(
&root.join("src-tauri/Cargo.toml"),
TAURI_CARGO_TOML.replace("__PACKAGE__", app_name),
)?;
write_file(&root.join("src-tauri/build.rs"), TAURI_BUILD_RS)?;
write_file(
&root.join("src-tauri/tauri.conf.json"),
tauri_conf_json(app_name),
)?;
write_file(
&root.join("src-tauri/src/main.rs"),
TAURI_MAIN_RS
.replace("__CRATE__", crate_ident)
.replace("__APP_NAME__", app_name),
)?;
Ok(())
}
/// Tauri v2 config schema. `bundle.icon` starts empty - see
/// [`write_tauri_scaffold`]'s own doc comment on why icons aren't
/// generated at scaffold time. The window's real content comes from
/// `src/main.rs`'s own `WebviewUrl::External(...)` call, not from
/// `build.frontendDist` - there's no separate frontend bundle here, so
/// that field just needs to point at *something* that exists to satisfy
/// the schema, and `public/` (already scaffolded for the ordinary web
/// binary's own static-asset serving) already does.
fn tauri_conf_json(app_name: &str) -> String {
format!(
r#"{{
"$schema": "https://schema.tauri.app/config/2",
"productName": {app_name:?},
"version": "0.1.0",
"identifier": "com.larust.{app_name}",
"build": {{
"frontendDist": "../public"
}},
"app": {{
"windows": [
{{
"title": {app_name:?},
"width": 1024,
"height": 768
}}
]
}},
"bundle": {{
"active": true,
"targets": "all",
"icon": []
}}
}}
"#
)
}
fn config_app_rs(app_name: &str) -> String {
let mut defaults = HashMap::new();
defaults.insert("app_name", format!("{app_name:?}"));
// Local-dev-friendly: `false` is `Config`'s own generic default
// (matching a production-safe fallback), but a freshly scaffolded app
// is always local dev - same override `.env`'s own `APP_DEBUG=true`
// line already carries, kept here too as this file's own fallback if
// `.env` ever goes missing.
defaults.insert("app_debug", "true".to_string());
config_template::render_app_config_rs(&defaults, &[])
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
#[test]
fn crate_dependency_computes_relative_path_into_crates_dir() {
let tmp = tempfile::tempdir().unwrap();
fs::create_dir_all(tmp.path().join("crates").join("larust-core")).unwrap();
let app_root = tmp.path().join("examples").join("blog");
fs::create_dir_all(&app_root).unwrap();
let dep = crate_dependency(Some(tmp.path()), &app_root, "larust-core", &[], true).unwrap();
assert_eq!(dep, "{ path = \"../../crates/larust-core\" }");
}
#[test]
fn crate_dependency_emits_a_version_requirement_in_crates_io_mode() {
// `ws_root: None` - the default now that every Larust crate is
// published, exercised with no filesystem at all (unlike the
// `--workspace` tests above, which need a real tempdir to compute
// a path against): this mode never touches `target_abs`.
let app_root = Path::new("/irrelevant/for/this/mode");
let dep = crate_dependency(None, app_root, "larust-core", &[], true).unwrap();
assert_eq!(dep, format!("{{ version = \"{FRAMEWORK_VERSION}\" }}"));
}
#[test]
fn crate_dependency_crates_io_mode_still_honors_default_features_and_feature_list() {
let app_root = Path::new("/irrelevant/for/this/mode");
let dep = crate_dependency(None, app_root, "larust-support", &["sqlite"], false).unwrap();
assert_eq!(
dep,
format!(
"{{ version = \"{FRAMEWORK_VERSION}\", default-features = false, \
features = [\"sqlite\"] }}"
)
);
}
#[test]
fn crate_dependency_adds_default_features_false_when_asked() {
let tmp = tempfile::tempdir().unwrap();
fs::create_dir_all(tmp.path().join("crates").join("larust-support")).unwrap();
let app_root = tmp.path().join("examples").join("blog");
fs::create_dir_all(&app_root).unwrap();
let dep = crate_dependency(
Some(tmp.path()),
&app_root,
"larust-support",
&["sqlite"],
false,
)
.unwrap();
assert_eq!(
dep,
"{ path = \"../../crates/larust-support\", default-features = false, \
features = [\"sqlite\"] }"
);
}
#[test]
#[cfg(windows)]
fn crate_dependency_falls_back_to_a_plain_absolute_path_across_different_drives() {
// Real paths, not a tempdir: reproduces a real incident directly
// (`xr convert`'s own `run()` always resolves the workspace from
// its compile-time checkout regardless of wherever `--out` points
// - see that function's own doc comment - and GitHub's hosted
// Windows runners checkout to `D:` while `TEMP` resolves to `C:`,
// a real case this exact scenario hit in CI) without needing a
// second drive to actually exist locally - this function never
// touches the filesystem itself (the caller canonicalizes first),
// so synthetic absolute paths exercise the identical code path.
// No relative path exists across drive letters on Windows, full
// stop - but that's not an error case: a plain absolute path
// dependency resolves and builds fine, cross-drive included
// (confirmed directly against a real scratch crate).
let ws_root = Path::new(r"E:\vsprojects\Larust");
let target_abs = Path::new(r"C:\Users\someone\myapp");
let dep = crate_dependency(Some(ws_root), target_abs, "larust-core", &[], true).unwrap();
assert_eq!(
dep,
"{ path = \"E:/vsprojects/Larust/crates/larust-core\" }"
);
}
#[test]
#[cfg(windows)]
fn strip_verbatim_prefix_removes_the_windows_canonicalize_prefix() {
// The actual mechanism behind the fix above: `canonicalize()`'s
// own `\\?\`-prefixed form is what Cargo's manifest parser
// rejects outright with "invalid path url" - confirmed directly
// against a real `cargo check` - even though the identical path
// minus just this prefix resolves fine.
assert_eq!(
strip_verbatim_prefix(Path::new(r"\\?\E:\vsprojects\Larust")),
Path::new(r"E:\vsprojects\Larust")
);
// A path that never carried the prefix passes through unchanged -
// the common case, and what every same-drive scaffold already
// exercises via the relative-path branch that never calls this at
// all.
assert_eq!(
strip_verbatim_prefix(Path::new(r"E:\vsprojects\Larust")),
Path::new(r"E:\vsprojects\Larust")
);
}
#[test]
fn crate_dependency_appends_features_when_given() {
let tmp = tempfile::tempdir().unwrap();
fs::create_dir_all(tmp.path().join("crates").join("larust-support")).unwrap();
let app_root = tmp.path().join("examples").join("blog");
fs::create_dir_all(&app_root).unwrap();
let dep = crate_dependency(
Some(tmp.path()),
&app_root,
"larust-support",
&["permissions", "sanctum"],
true,
)
.unwrap();
assert_eq!(
dep,
"{ path = \"../../crates/larust-support\", features = [\"permissions\", \"sanctum\"] }"
);
}
#[test]
fn new_app_succeeds_outside_any_workspace_using_crates_io_dependencies() {
// The real behavior change this whole milestone is about: no
// ambient Larust checkout anywhere above `target`, and no
// `--workspace` given either - this used to be a hard error
// ("`xr new` currently requires running from inside a Larust
// workspace checkout") before every Larust crate was published.
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("app");
new_app_with_features(target.to_str().unwrap(), false, &[], false).unwrap();
let cargo_toml = fs::read_to_string(target.join("Cargo.toml")).unwrap();
assert!(
cargo_toml.contains(&format!("version = \"{FRAMEWORK_VERSION}\"")),
"expected a crates.io version requirement with no workspace available, got:\n{cargo_toml}"
);
assert!(
!cargo_toml.contains("path = \"../"),
"must not fall back to a local path dependency with no workspace available: \
{cargo_toml}"
);
}
#[test]
fn validate_app_name_rejects_unsafe_characters() {
assert!(validate_app_name(Path::new("my\"app")).is_err());
}
#[test]
fn validate_app_name_accepts_normal_names() {
assert_eq!(
validate_app_name(Path::new("/tmp/examples/blog")).unwrap(),
"blog"
);
}
#[test]
fn validate_app_name_rejects_names_shaped_like_a_template_placeholder() {
assert!(validate_app_name(Path::new("/tmp/__CRATE__")).is_err());
}
#[test]
fn validate_app_name_rejects_a_hyphenated_name_whose_crate_ident_is_placeholder_shaped() {
// `app_name` itself ("--CRATE--") isn't `__`-shaped and passes the
// charset check, but `crate_ident("--CRATE--")` ("__CRATE__")
// collides with the `__CRATE__` template placeholder - the guard
// has to check the post-transform identifier, not the raw name.
assert!(validate_app_name(Path::new("/tmp/--CRATE--")).is_err());
}
#[test]
fn validate_app_name_rejects_a_name_starting_with_a_digit() {
// Harmless before `crate_ident` started flowing into `use`
// paths (`app_name` was only ever a Cargo package name and a
// private `mod` declaration) - `use 9lives::...` is a syntax
// error now that it's a real identifier.
assert!(validate_app_name(Path::new("/tmp/9lives")).is_err());
}
#[test]
fn validate_app_name_rejects_a_rust_keyword() {
// `use type::controllers::...;` is a syntax error.
assert!(validate_app_name(Path::new("/tmp/type")).is_err());
}
#[test]
fn crate_ident_replaces_hyphens_with_underscores() {
assert_eq!(crate_ident("my-app"), "my_app");
assert_eq!(crate_ident("blog"), "blog");
assert_eq!(crate_ident("my_app"), "my_app");
}
#[test]
fn new_app_cleans_up_partial_scaffold_on_failure() {
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("orphan-app");
// A deliberately bogus `--workspace` path - still fails *after*
// `scaffold()` has already created the root directory (the write
// the cleanup path exists to undo), unlike the crates.io default,
// which no longer has any fallible step here at all.
let bogus_workspace = tmp.path().join("does-not-exist");
let result = new_app_from_workspace(
target.to_str().unwrap(),
false,
&bogus_workspace,
&[],
false,
);
assert!(result.is_err());
assert!(
!target.exists(),
"partial scaffold should be cleaned up on failure"
);
}
#[test]
fn new_app_with_auth_creates_the_auth_specific_files() {
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("examples").join("blog");
new_app_with_features(target.to_str().unwrap(), true, &[], false).unwrap();
for path in [
"app/Models/user.rs",
"app/Http/Controllers/auth_controller.rs",
"app/Http/Requests/register_request.rs",
"app/Http/Requests/login_request.rs",
"resources/views/auth/register.blade.xr",
"resources/views/auth/login.blade.xr",
"database/migrations/0002_create_users_table.sql",
"app/Models/comment.rs",
"app/Http/Controllers/comment_controller.rs",
"app/Http/Requests/store_comment_request.rs",
"resources/views/posts/show.blade.xr",
"database/migrations/0003_create_comments_table.sql",
] {
assert!(
target.join(path).exists(),
"`xr new --auth` should create {path}"
);
}
let routes_web_rs = fs::read_to_string(target.join("routes/web.rs")).unwrap();
assert!(
routes_web_rs.contains("AuthController") && routes_web_rs.contains("require_auth"),
"routes/web.rs should wire up AuthController and the require_auth middleware"
);
}
#[test]
fn new_app_without_auth_does_not_create_auth_specific_files() {
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("examples").join("blog");
new_app_with_features(target.to_str().unwrap(), false, &[], false).unwrap();
assert!(!target.join("app/Models/user.rs").exists());
assert!(!target
.join("app/Http/Controllers/auth_controller.rs")
.exists());
let routes_web_rs = fs::read_to_string(target.join("routes/web.rs")).unwrap();
assert!(!routes_web_rs.contains("AuthController"));
// Live comments need a `User` to attribute a comment to - see
// `scaffold()`'s own `if auth { ... }` block - so a non-auth app
// gets none of it, and `reverb` stays off in its `Cargo.toml`.
assert!(!target.join("app/Models/comment.rs").exists());
assert!(!routes_web_rs.contains("CommentController"));
let cargo_toml = fs::read_to_string(target.join("Cargo.toml")).unwrap();
assert!(
!cargo_toml.contains("reverb"),
"Cargo.toml was: {cargo_toml}"
);
}
#[test]
fn new_app_with_auth_wires_up_live_comments() {
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("examples").join("blog");
new_app_with_features(target.to_str().unwrap(), true, &[], false).unwrap();
let cargo_toml = fs::read_to_string(target.join("Cargo.toml")).unwrap();
assert!(
cargo_toml.contains("\"reverb\""),
"Cargo.toml should turn on the reverb feature for an auth app: {cargo_toml}"
);
let routes_web_rs = fs::read_to_string(target.join("routes/web.rs")).unwrap();
assert!(
routes_web_rs.contains("CommentController")
&& routes_web_rs.contains(".plugin(larust_support::wire::WirePlugin)")
&& routes_web_rs.contains(".plugin(larust_support::spa::SpaPlugin)")
&& routes_web_rs.contains(".plugin(larust_support::image::ImagePlugin)")
&& routes_web_rs.contains(".plugin(larust_support::reverb::ReverbPlugin)"),
"routes/web.rs should wire up CommentController and the wire/spa/image/reverb \
plugins: {routes_web_rs}"
);
let show_view =
fs::read_to_string(target.join("resources/views/posts/show.blade.xr")).unwrap();
assert!(
show_view.contains("LarustReverb") && show_view.contains("CommentCreated"),
"posts/show.blade.xr should wire up the reverb client: {show_view}"
);
}
#[test]
fn new_app_with_tauri_scaffolds_src_tauri() {
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("examples").join("blog");
new_app_with_features(target.to_str().unwrap(), false, &[], true).unwrap();
assert!(target.join("src-tauri/Cargo.toml").is_file());
assert!(target.join("src-tauri/build.rs").is_file());
assert!(target.join("src-tauri/tauri.conf.json").is_file());
assert!(target.join("src-tauri/src/main.rs").is_file());
assert!(target.join("src-tauri/icons").is_dir());
let cargo_toml = fs::read_to_string(target.join("src-tauri/Cargo.toml")).unwrap();
assert!(
cargo_toml.contains("blog = { path = \"..\" }"),
"src-tauri/Cargo.toml should depend on the parent app crate by path: {cargo_toml}"
);
let env = fs::read_to_string(target.join(".env")).unwrap();
assert!(
env.contains("\nDEPLOY_TYPE=app\n") && !env.contains("# DEPLOY_TYPE=app"),
".env should uncomment DEPLOY_TYPE=app when --tauri is passed: {env}"
);
}
#[test]
fn new_app_without_tauri_has_no_src_tauri() {
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("examples").join("blog");
new_app_with_features(target.to_str().unwrap(), false, &[], false).unwrap();
assert!(!target.join("src-tauri").exists());
let env = fs::read_to_string(target.join(".env")).unwrap();
assert!(env.contains("# DEPLOY_TYPE=web"));
}
/// Guards the coupling `convert.rs`'s `remove_demo_scaffold` documents:
/// every path in `DEMO_SCAFFOLD_FILES`/`DEMO_SCAFFOLD_MOD_FILES` must
/// actually exist after a real scaffold, or `xr convert` would try to
/// delete/reset a file that was never written. Catches the case someone
/// adds a new demo `write_file` call with an inline literal path
/// without also adding it to one of these two shared arrays.
#[test]
fn every_demo_scaffold_path_exists_after_a_real_scaffold() {
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("examples").join("blog");
new_app_with_features(target.to_str().unwrap(), false, &[], false).unwrap();
for relative in DEMO_SCAFFOLD_FILES {
assert!(
target.join(relative).is_file(),
"DEMO_SCAFFOLD_FILES entry {relative:?} was not written by scaffold()"
);
}
for relative in DEMO_SCAFFOLD_MOD_FILES {
assert!(
target.join(relative).is_file(),
"DEMO_SCAFFOLD_MOD_FILES entry {relative:?} was not written by scaffold()"
);
}
}
/// The real local checkout, not whatever happens to be published on
/// crates.io - mirrors `convert.rs::run()`'s own identical arithmetic
/// exactly. Every test below that actually *compiles* or *resolves*
/// its scaffold output needs this explicitly, now that `ws_root: None`
/// means crates.io by default: without it, these tests would silently
/// start verifying whatever version is currently published instead of
/// the source sitting right here, uncommitted changes included -
/// exactly the regression-catching power they exist for.
fn local_workspace_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.and_then(Path::parent)
.expect("CARGO_MANIFEST_DIR should be nested two levels under the workspace root")
.to_path_buf()
}
/// Scaffolds a real `xr new --auth` app into this crate's own
/// `target/tmp/`, then actually **compiles it** - same "scratch-
/// scaffold verification" technique `convert.rs`'s own
/// `converts_the_fixture_app_into_a_project_that_compiles` uses (see
/// its doc comment): a temporary `[workspace]` table isolates the
/// generated crate from the outer workspace (it isn't matched by
/// `crates/*`, so without this Cargo would error "believes it's in a
/// workspace when it's not"), `cargo build` runs against it
/// standalone, then the whole output directory is discarded. No
/// scaffold.rs test previously proved the generated app actually
/// compiles at all - every other test here only asserts on file
/// existence/content strings - so this is the first, and specifically
/// targets `--auth` since that's the branch the live-comments example
/// (and its new `reverb` Cargo feature) lives on.
#[test]
fn new_app_with_auth_actually_compiles() {
let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
let out_dir = manifest_dir.join("target/tmp/new_app_auth_integration_test");
if out_dir.exists() {
fs::remove_dir_all(&out_dir).unwrap();
}
fs::create_dir_all(out_dir.parent().unwrap()).unwrap();
new_app_from_workspace(
out_dir.to_str().unwrap(),
true,
&local_workspace_root(),
&[],
false,
)
.unwrap();
let cargo_toml_path = out_dir.join("Cargo.toml");
let mut cargo_toml = fs::read_to_string(&cargo_toml_path).unwrap();
assert!(
cargo_toml.contains("\"reverb\""),
"expected the generated Cargo.toml to enable the `reverb` \
larust-support feature for an auth app, got:\n{cargo_toml}"
);
// Isolate from the outer workspace (see this test's own doc
// comment) so `cargo build` treats it as a standalone crate.
cargo_toml.push_str("\n[workspace]\nmembers = [\".\"]\n");
fs::write(&cargo_toml_path, cargo_toml).unwrap();
let status = std::process::Command::new("cargo")
.args(["build", "--quiet"])
.current_dir(&out_dir)
.status()
.unwrap();
assert!(status.success(), "scaffolded --auth app failed to compile");
fs::remove_dir_all(&out_dir).unwrap();
}
#[test]
fn new_app_without_db_feature_wires_up_neither_the_cli_dispatch_nor_the_dashboard_route() {
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("examples").join("blog");
new_app_with_features(target.to_str().unwrap(), false, &[], false).unwrap();
let main_rs = fs::read_to_string(target.join("src/main.rs")).unwrap();
assert!(!main_rs.contains("db:list"));
let routes_web_rs = fs::read_to_string(target.join("routes/web.rs")).unwrap();
assert!(!routes_web_rs.contains("DbPlugin"));
let cargo_toml = fs::read_to_string(target.join("Cargo.toml")).unwrap();
assert!(
!cargo_toml.contains("\"db\""),
"Cargo.toml was: {cargo_toml}"
);
}
#[test]
fn new_app_with_db_feature_wires_up_dashboard_and_cli() {
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("examples").join("blog");
new_app_with_features(target.to_str().unwrap(), false, &["db"], false).unwrap();
let cargo_toml = fs::read_to_string(target.join("Cargo.toml")).unwrap();
assert!(
cargo_toml.contains("\"db\""),
"Cargo.toml should turn on the db feature: {cargo_toml}"
);
let main_rs = fs::read_to_string(target.join("src/main.rs")).unwrap();
assert!(
main_rs.contains("db:list")
&& main_rs.contains("db:get")
&& main_rs.contains("db:put")
&& main_rs.contains("db:forget"),
"main.rs should wire up all 4 db:* subcommands: {main_rs}"
);
assert!(
!main_rs.contains("__DB_MAIN_RS_SNIPPET__"),
"placeholder should be fully substituted"
);
// The 4 CLI-subcommand connects live in main.rs; the connect
// immediately before `.with_sessions(...)` in the normal
// HTTP-serving path lives in `lib.rs`'s `serve()` (a real bug this
// session's own live sanity check caught: without it, every request
// to `/__larust_db` 500s with "embedded db not connected", since
// the serving process itself never touches the CLI-only connect
// calls in main.rs).
assert_eq!(
main_rs.matches("larust_support::db::connect(").count(),
4,
"main.rs should connect the embedded db in each CLI arm: {main_rs}"
);
let lib_rs = fs::read_to_string(target.join("src/lib.rs")).unwrap();
assert!(
!lib_rs.contains("__DB_SERVE_SNIPPET__"),
"placeholder should be fully substituted"
);
assert_eq!(
lib_rs.matches("larust_support::db::connect(").count(),
1,
"lib.rs's serve() should connect the embedded db once, in the normal serve path: \
{lib_rs}"
);
assert!(
lib_rs.contains(
"larust_support::db::connect(&paths().join(\"database/db.redb\")).await?;\n let route = route"
),
"the embedded db must be connected immediately before .with_sessions(...) runs in \
serve(), not just inside main.rs's early-return CLI arms: {lib_rs}"
);
let routes_web_rs = fs::read_to_string(target.join("routes/web.rs")).unwrap();
assert!(
routes_web_rs.contains("larust_core::try_config().is_some_and(|c| c.app_debug)")
&& routes_web_rs.contains(".plugin(larust_support::db::DbPlugin)"),
"routes/web.rs should register DbPlugin behind an app_debug gate: {routes_web_rs}"
);
assert!(
!routes_web_rs.contains("__DB_ROUTE_SNIPPET__"),
"placeholder should be fully substituted"
);
}
/// Same "scratch-scaffold, compile, discard" technique as
/// `new_app_with_auth_actually_compiles` (see its own doc comment) -
/// this one specifically exercises the `db` optional feature's own
/// scaffolding path (a real Cargo dependency on `larust-db`, plus the
/// spliced `main.rs`/`routes/web.rs` snippets), which nothing else
/// here proves actually compiles.
#[test]
fn new_app_with_db_actually_compiles() {
let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
let out_dir = manifest_dir.join("target/tmp/new_app_db_integration_test");
if out_dir.exists() {
fs::remove_dir_all(&out_dir).unwrap();
}
fs::create_dir_all(out_dir.parent().unwrap()).unwrap();
new_app_from_workspace(
out_dir.to_str().unwrap(),
false,
&local_workspace_root(),
&["db"],
false,
)
.unwrap();
let cargo_toml_path = out_dir.join("Cargo.toml");
let mut cargo_toml = fs::read_to_string(&cargo_toml_path).unwrap();
// Isolate from the outer workspace so `cargo build` treats it as a
// standalone crate - see `new_app_with_auth_actually_compiles`'s
// own doc comment for why this is needed at all.
cargo_toml.push_str("\n[workspace]\nmembers = [\".\"]\n");
fs::write(&cargo_toml_path, cargo_toml).unwrap();
let status = std::process::Command::new("cargo")
.args(["build", "--quiet"])
.current_dir(&out_dir)
.status()
.unwrap();
assert!(status.success(), "scaffolded db app failed to compile");
fs::remove_dir_all(&out_dir).unwrap();
}
/// The actual regression proof for the sqlx driver feature-gating
/// cascade (`larust-support`'s `sqlite`/`mysql`/`postgres` features
/// forwarding through `larust-orm`/`larust-cache`/`larust-http`/etc. -
/// see `larust-orm/Cargo.toml`'s own `[features]` comment): a plain
/// `xr new` (sqlite, the default, no other flags) must resolve
/// `sqlx-mysql`/`sqlx-postgres` out of its dependency tree entirely,
/// not just "fewer crates than before" (a fuzzy count would pass for
/// unrelated reasons - this asserts the actual thing that changed).
/// Only needs `cargo tree` (dependency resolution), not a full `cargo
/// build` - meaningfully faster than the `_actually_compiles` tests
/// above, so this isn't `#[ignore]`d.
#[test]
fn new_app_excludes_unused_sqlx_backends_from_its_dependency_tree() {
let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
let out_dir = manifest_dir.join("target/tmp/new_app_sqlx_tree_test");
if out_dir.exists() {
fs::remove_dir_all(&out_dir).unwrap();
}
fs::create_dir_all(out_dir.parent().unwrap()).unwrap();
new_app_from_workspace(
out_dir.to_str().unwrap(),
false,
&local_workspace_root(),
&[],
false,
)
.unwrap();
let cargo_toml_path = out_dir.join("Cargo.toml");
let mut cargo_toml = fs::read_to_string(&cargo_toml_path).unwrap();
// Isolate from the outer workspace - see `new_app_with_auth_
// actually_compiles`'s own doc comment for why this is needed.
cargo_toml.push_str("\n[workspace]\nmembers = [\".\"]\n");
fs::write(&cargo_toml_path, cargo_toml).unwrap();
// No `--locked` - a freshly-scaffolded app has no `Cargo.lock` of
// its own yet, so this genuinely needs to resolve fresh (exactly
// the real-world scenario this test is proving something about).
let output = std::process::Command::new("cargo")
.args(["tree", "--edges", "normal"])
.current_dir(&out_dir)
.output();
let output = match output {
Ok(o) if o.status.success() => o,
Ok(o) => {
fs::remove_dir_all(&out_dir).unwrap();
panic!("cargo tree failed: {}", String::from_utf8_lossy(&o.stderr));
}
Err(_) => {
// Without a `Cargo.lock` yet, `cargo tree` needs to resolve
// against crates.io - if this environment has no network
// access at all, skip rather than fail the whole suite over
// an environment limitation unrelated to what this test
// actually checks.
fs::remove_dir_all(&out_dir).unwrap();
eprintln!("skipping: cargo tree could not run (no cargo on PATH?)");
return;
}
};
let tree = String::from_utf8_lossy(&output.stdout);
assert!(
tree.contains("sqlx-sqlite"),
"the actually-selected driver must still be present: {tree}"
);
assert!(
!tree.contains("sqlx-mysql") && !tree.contains("sqlx-postgres"),
"a plain `xr new` (sqlite) must not pull in the unused mysql/postgres sqlx \
backends:\n{tree}"
);
fs::remove_dir_all(&out_dir).unwrap();
}
#[test]
fn new_app_creates_a_lib_rs_and_wires_main_rs_to_it_by_crate_name() {
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("examples").join("my-blog");
new_app_with_features(target.to_str().unwrap(), false, &[], false).unwrap();
let lib_rs = fs::read_to_string(target.join("src/lib.rs")).unwrap();
assert!(lib_rs.contains("pub mod controllers;"));
assert!(lib_rs.contains("pub mod policies;"));
let main_rs = fs::read_to_string(target.join("src/main.rs")).unwrap();
// The app dir is named `my-blog` (a hyphen) - `main.rs` must
// reference the underscored crate identifier `my_blog`, not the
// literal package name, or `use my-blog::...` would be a syntax
// error.
assert!(
main_rs.contains("my_blog::serve()") && main_rs.contains("my_blog::connect_database()"),
"main.rs was: {main_rs}"
);
assert!(
!main_rs.contains("__CRATE__"),
"placeholder should be fully substituted"
);
// `routes::web::routes()` now lives in `lib.rs`'s own `router()`
// function - internal to the library crate itself, so unqualified
// (no `my_blog::` prefix, unlike main.rs's external reference).
assert!(
lib_rs.contains("routes::web::routes()"),
"lib.rs was: {lib_rs}"
);
// Unlike `main.rs` (a separate binary crate that reaches the
// library via the external `my_blog::` path), `routes/web.rs` is
// compiled as *part of* the library crate itself (`lib.rs`'s
// `#[path = "../routes/mod.rs"]`), so it must reach `controllers`
// via `crate::`, never the external crate name - using the
// external name there is a real compile error (verified: it broke
// a fresh `cargo build` of a scaffolded app before this assertion
// was added).
let routes_web_rs = fs::read_to_string(target.join("routes/web.rs")).unwrap();
assert!(
routes_web_rs.contains("use crate::controllers::"),
"routes/web.rs was: {routes_web_rs}"
);
assert!(
!routes_web_rs.contains("__CRATE__") && !routes_web_rs.contains("my_blog::"),
"routes/web.rs must never reference the external crate name - it's compiled as part \
of the library crate itself: {routes_web_rs}"
);
}
#[test]
fn new_app_adds_larust_testing_as_a_dev_dependency() {
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("examples").join("blog");
new_app_with_features(target.to_str().unwrap(), false, &[], false).unwrap();
let cargo_toml = fs::read_to_string(target.join("Cargo.toml")).unwrap();
assert!(cargo_toml.contains("[dev-dependencies]"));
assert!(cargo_toml.contains("larust-testing"));
}
}