Skip to main content

luxid_cli/
scaffold.rs

1//! File generation for `luxid new` and `luxid make:model`.
2//!
3//! Generation is split into planning and writing. A [`Plan`] is a pure value —
4//! which files, with what contents, and which lines to insert into existing
5//! ones — so the interesting logic is testable without touching a disk.
6//!
7//! Writing never overwrites. A generator that clobbers hand-written code once
8//! is a generator nobody runs again.
9
10use std::collections::{BTreeMap, BTreeSet};
11use std::path::{Path, PathBuf};
12
13use luxid_core::error::{Error, Result};
14
15use crate::naming::Names;
16
17/// A file to create.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct NewFile {
20    pub path: PathBuf,
21    pub contents: String,
22}
23
24/// A line to insert after a marker in an existing file.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct Insertion {
27    pub path: PathBuf,
28    pub marker: &'static str,
29    pub line: String,
30}
31
32#[derive(Debug, Default, Clone, PartialEq, Eq)]
33pub struct Plan {
34    pub files: Vec<NewFile>,
35    pub insertions: Vec<Insertion>,
36}
37
38impl Plan {
39    fn file(&mut self, path: impl Into<PathBuf>, contents: impl Into<String>) {
40        self.files.push(NewFile {
41            path: path.into(),
42            contents: contents.into(),
43        });
44    }
45
46    fn insert(&mut self, path: impl Into<PathBuf>, marker: &'static str, line: impl Into<String>) {
47        self.insertions.push(Insertion {
48            path: path.into(),
49            marker,
50            line: line.into(),
51        });
52    }
53
54    /// Every path this plan touches, for reporting.
55    pub fn touched(&self) -> BTreeSet<&Path> {
56        self.files
57            .iter()
58            .map(|file| file.path.as_path())
59            .chain(
60                self.insertions
61                    .iter()
62                    .map(|insertion| insertion.path.as_path()),
63            )
64            .collect()
65    }
66}
67
68// ---------------------------------------------------------------- markers
69
70pub const MARK_MODULES: &str = "// <luxid:modules>";
71pub const MARK_ROUTES: &str = "// <luxid:routes>";
72pub const MARK_MIGRATIONS: &str = "// <luxid:migrations>";
73pub const MARK_MIGRATION_MODULES: &str = "// <luxid:migration-modules>";
74
75// ------------------------------------------------------------- luxid new
76
77/// How the generated app should depend on Luxid.
78#[derive(Debug, Clone)]
79pub enum Dependency {
80    /// A published version.
81    Version(String),
82    /// A local checkout, for working on the framework itself.
83    Path(String),
84}
85
86impl Dependency {
87    fn luxid(&self) -> String {
88        match self {
89            Self::Version(version) => format!("luxid = \"{version}\""),
90            Self::Path(root) => format!("luxid = {{ path = \"{root}/crates/luxid\" }}"),
91        }
92    }
93
94    fn testing(&self) -> String {
95        match self {
96            Self::Version(version) => format!("luxid-testing = \"{version}\""),
97            Self::Path(root) => {
98                format!("luxid-testing = {{ path = \"{root}/crates/luxid-testing\" }}")
99            }
100        }
101    }
102}
103
104pub fn new_app(name: &str, dependency: &Dependency) -> Plan {
105    let mut plan = Plan::default();
106    let crate_name = crate::naming::to_snake(name);
107
108    plan.file(
109        "Cargo.toml",
110        format!(
111            r#"[package]
112name = "{crate_name}"
113version = "0.1.0"
114edition = "2024"
115
116[dependencies]
117{}
118migration = {{ path = "migration" }}
119
120tokio = {{ version = "1", features = ["macros", "rt-multi-thread"] }}
121serde = {{ version = "1", features = ["derive"] }}
122serde_json = "1"
123sea-orm = {{ version = "2.0", features = [
124    "macros",
125    "runtime-tokio-rustls",
126    "sqlx-sqlite",
127    "sqlx-postgres",
128    "with-chrono",
129] }}
130dotenvy = "0.15"
131
132# Declared directly because their derive macros emit crate-qualified paths:
133# re-exporting them through `luxid` is not enough for `#[derive(..)]` to resolve.
134schemars = "1.2"
135
136[dev-dependencies]
137{}
138
139[profile.dev]
140opt-level = 0
141
142# Dependencies are built optimised once; your own crate stays quick to rebuild.
143[profile.dev.package."*"]
144opt-level = 3
145"#,
146            dependency.luxid(),
147            dependency.testing(),
148        ),
149    );
150
151    plan.file(
152        "migration/Cargo.toml",
153        r#"[package]
154name = "migration"
155version = "0.1.0"
156edition = "2024"
157publish = false
158
159[dependencies]
160sea-orm-migration = { version = "2.0", default-features = false, features = [
161    "runtime-tokio-rustls",
162    "sqlx-sqlite",
163    "sqlx-postgres",
164] }
165"#,
166    );
167
168    plan.file(
169        "migration/src/lib.rs",
170        format!(
171            r#"pub use sea_orm_migration::prelude::*;
172
173{MARK_MIGRATION_MODULES}
174
175pub struct Migrator;
176
177#[async_trait::async_trait]
178impl MigratorTrait for Migrator {{
179    fn migrations() -> Vec<Box<dyn MigrationTrait>> {{
180        vec![
181            {MARK_MIGRATIONS}
182        ]
183    }}
184}}
185"#
186        ),
187    );
188
189    plan.file(
190        "src/main.rs",
191        r#"mod app;
192mod config;
193mod controllers;
194mod entities;
195mod factories;
196mod middleware;
197mod models;
198mod policies;
199mod routes;
200mod seeders;
201mod services;
202mod validators;
203
204#[tokio::main]
205async fn main() -> luxid::Result<()> {
206    let _ = dotenvy::dotenv();
207
208    // `cargo run` serves; `cargo luxid routes`, `migrate`, `openapi`
209    // and friends are all the same binary.
210    luxid::cli::run::<migration::Migrator>(app::build().await?).await
211}
212"#,
213    );
214
215    plan.file(
216        "src/app.rs",
217        r#"use luxid::prelude::*;
218
219/// Assemble the application: configuration, services, middleware, routes.
220pub async fn build() -> luxid::Result<App> {
221    // luxid.toml, with the environment layered over it.
222    let config = Config::load("luxid.toml")?;
223
224    // Accessing a relation that was not eager-loaded becomes an error, which
225    // turns an N+1 into a failing test rather than a production surprise.
226    luxid::set_strict_relations(config.get_or("database.strict_relations", cfg!(debug_assertions))?);
227
228    // SQLite by default so a fresh app runs with no infrastructure. Point
229    // DATABASE_URL at Postgres when you want one.
230    let url = config
231        .get_or("database.url", "sqlite://./app.db?mode=rwc".to_owned())?;
232
233    let db = Db::connect(url).await?;
234
235    Ok(App::new()
236        .config(config)
237        .providers(providers(db))
238        .middleware(WithDatabase)
239        .routes(crate::routes::register))
240}
241
242fn providers(db: Db) -> Providers {
243    Providers::new().singleton(move |_| db.clone())
244}
245"#,
246    );
247
248    plan.file(
249        "src/routes.rs",
250        format!(
251            r#"use luxid::prelude::*;
252
253use crate::controllers;
254
255pub fn register(r: &mut Router) {{
256    r.group("/api", |r| {{
257        r.get("/health", controllers::health_controller::HealthController::show);
258
259        {MARK_ROUTES}
260    }});
261}}
262"#
263        ),
264    );
265
266    plan.file(
267        "src/controllers/mod.rs",
268        format!("pub mod health_controller;\n\n{MARK_MODULES}\n"),
269    );
270
271    plan.file(
272        "src/controllers/health_controller.rs",
273        r#"use luxid::prelude::*;
274use serde_json::json;
275
276pub struct HealthController;
277
278#[luxid::controller]
279impl HealthController {
280    #[openapi(summary = "Liveness probe", tag = "system")]
281    async fn show(ctx: HttpContext) -> Result<Response> {
282        ctx.response.ok(json!({ "status": "ok" }))
283    }
284}
285"#,
286    );
287
288    // `factories` and `seeders` are here because `make:model` registers into
289    // them; a plan that inserts into a file nobody created fails at write time.
290    for module in ["models", "entities", "validators", "services", "middleware"] {
291        plan.file(format!("src/{module}/mod.rs"), format!("{MARK_MODULES}\n"));
292    }
293
294    // These are called from tests, seed commands and controllers you have not
295    // written yet — none of which the binary target can see. Without this a
296    // freshly generated app greets you with dead-code warnings, which is a good
297    // way to teach people to ignore warnings.
298    for module in ["policies", "factories", "seeders"] {
299        plan.file(
300            format!("src/{module}/mod.rs"),
301            format!("#![allow(dead_code)]\n\n{MARK_MODULES}\n"),
302        );
303    }
304
305    plan.file(
306        "src/config/mod.rs",
307        r#"//! Application configuration. Read from the environment here, and bind the
308//! result as a singleton in `app::providers` so actions can resolve it.
309"#,
310    );
311
312    plan.file(
313        ".env.example",
314        r#"# Copy to .env and adjust. These override luxid.toml.
315DATABASE_URL=sqlite://./app.db?mode=rwc
316APP_KEY=change-me-before-deploying
317LUXID_ADDR=127.0.0.1:3000
318"#,
319    );
320
321    plan.file(".gitignore", "/target\n/app.db\n/app.db-*\n.env\n");
322
323    plan.file(
324        "luxid.toml",
325        format!(
326            r#"# Read at boot by `app::build`, and available in any action as
327# `ctx.config`. Environment variables override these: `app.name` is also
328# `APP_NAME`, `database.url` is also `DATABASE_URL`.
329
330[app]
331name = "{crate_name}"
332per_page = 20
333
334[database]
335# url = "postgres://localhost/{crate_name}"
336
337# Reading a relation that was not eager-loaded becomes an error.
338strict_relations = true
339"#
340        ),
341    );
342
343    // Two things live here. The alias is what lets the application's own
344    // commands read as `cargo luxid migrate` rather than `cargo run -- migrate`
345    // — cargo expands it before dispatch, so nothing in the binary changes and
346    // `cargo run -- migrate` keeps working.
347    //
348    // The linker is shipped commented out on purpose. A faster linker is the
349    // biggest single lever on rebuild time, but enabling it by default produces
350    // a project that does not compile on any machine without mold — and this
351    // file gets committed, so it would break teammates too.
352    plan.file(
353        ".cargo/config.toml",
354        r#"# `cargo luxid <command>` runs this application's own command line.
355#
356# It expands to `cargo run --`, so `cargo luxid migrate` and
357# `cargo run -- migrate` are the same thing. Copy this section into any
358# existing project to get the shorter form.
359[alias]
360luxid = "run --"
361
362# A faster linker is the single biggest lever on rebuild time.
363#
364# Uncomment after installing mold (https://github.com/rui314/mold), or swap in
365# `lld`. Left off by default so this project builds anywhere.
366#
367# [target.x86_64-unknown-linux-gnu]
368# rustflags = ["-C", "link-arg=-fuse-ld=mold", "-C", "debuginfo=1"]
369"#,
370    );
371
372    plan.file(
373        "README.md",
374        format!(
375            r#"# {crate_name}
376
377```sh
378cargo run                 # serve on http://127.0.0.1:3000
379cargo luxid routes        # the routing table
380cargo luxid migrate       # apply migrations
381cargo luxid openapi       # the OpenAPI 3.1 document
382```
383
384Generated by `luxid new`.
385"#
386        ),
387    );
388
389    plan
390}
391
392// -------------------------------------------------------- luxid make:model
393
394/// Which artefacts `make:model` should produce.
395#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
396pub struct ModelFlags {
397    pub migration: bool,
398    pub factory: bool,
399    pub seeder: bool,
400    pub controller: bool,
401    pub policy: bool,
402    pub requests: bool,
403}
404
405impl ModelFlags {
406    /// `-a`: everything.
407    pub fn all() -> Self {
408        Self {
409            migration: true,
410            factory: true,
411            seeder: true,
412            controller: true,
413            policy: true,
414            requests: true,
415        }
416    }
417}
418
419pub fn make_model(names: &Names, flags: ModelFlags, timestamp: &str) -> Plan {
420    let mut plan = Plan::default();
421    let Names {
422        model,
423        snake,
424        plural,
425        ..
426    } = names;
427
428    plan.file(
429        format!("src/models/{snake}.rs"),
430        format!(
431            r#"pub use crate::entities::{plural}::Model as {model};
432
433// Relations, scopes and hooks go here. Declare relations in the attribute and
434// scopes as `#[scope]` functions:
435//
436//     #[luxid::model(has_many(posts = Post, fk = "{snake}_id"))]
437//     impl {model} {{
438//         #[scope]
439//         fn active(query: Query<crate::entities::{plural}::Entity>)
440//             -> Query<crate::entities::{plural}::Entity>
441//         {{
442//             query.where_null({model}::deleted_at)
443//         }}
444//     }}
445#[luxid::model()]
446impl {model} {{}}
447"#
448        ),
449    );
450    plan.insert(
451        "src/models/mod.rs",
452        MARK_MODULES,
453        format!("pub mod {snake};"),
454    );
455
456    // The entity is regenerated from the schema by `luxid db:sync`; this stub
457    // exists so the app compiles before the first migration has run.
458    plan.file(
459        format!("src/entities/{plural}.rs"),
460        format!(
461            r#"//! Generated from the database schema. Re-run `luxid db:sync` after a
462//! migration rather than editing this by hand.
463
464use sea_orm::entity::prelude::*;
465
466#[derive(Clone, Debug, PartialEq, DeriveEntityModel, serde::Serialize, luxid::Model)]
467#[sea_orm(table_name = "{plural}")]
468pub struct Model {{
469    // <luxid:fields>  refreshed by `cargo luxid db:sync`
470    #[sea_orm(primary_key)]
471    pub id: i64,
472    // </luxid:fields>
473    #[sea_orm(ignore)]
474    #[serde(flatten)]
475    pub relations: luxid::Relations,
476}}
477
478#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
479pub enum Relation {{}}
480
481impl ActiveModelBehavior for ActiveModel {{}}
482"#
483        ),
484    );
485    plan.insert(
486        "src/entities/mod.rs",
487        MARK_MODULES,
488        format!("pub mod {plural};"),
489    );
490
491    if flags.migration {
492        let migration = format!("m{timestamp}_create_{plural}");
493
494        plan.file(
495            format!("migration/src/{migration}.rs"),
496            format!(
497                r#"use sea_orm_migration::prelude::*;
498use sea_orm_migration::schema::*;
499
500#[derive(DeriveIden)]
501enum {} {{
502    Table,
503    Id,
504}}
505
506pub struct Migration;
507
508impl MigrationName for Migration {{
509    fn name(&self) -> &str {{
510        "{migration}"
511    }}
512}}
513
514#[async_trait::async_trait]
515impl MigrationTrait for Migration {{
516    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {{
517        manager
518            .create_table(
519                Table::create()
520                    .table({0}::Table)
521                    .if_not_exists()
522                    .col(pk_auto({0}::Id))
523                    // Add your columns here.
524                    .to_owned(),
525            )
526            .await
527    }}
528
529    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {{
530        manager.drop_table(Table::drop().table({0}::Table).to_owned()).await
531    }}
532}}
533"#,
534                crate::naming::to_pascal(plural)
535            ),
536        );
537
538        plan.insert(
539            "migration/src/lib.rs",
540            MARK_MIGRATION_MODULES,
541            format!("mod {migration};"),
542        );
543        plan.insert(
544            "migration/src/lib.rs",
545            MARK_MIGRATIONS,
546            format!("Box::new({migration}::Migration),"),
547        );
548    }
549
550    if flags.requests {
551        let store = &names.store_request;
552        let update = &names.update_request;
553
554        plan.file(
555            format!("src/validators/{snake}.rs"),
556            format!(
557                r#"use luxid::prelude::*;
558use serde::Deserialize;
559
560// `JsonSchema` lets `#[openapi(body = ..)]` describe this request.
561#[derive(Debug, Deserialize, Validate, luxid::JsonSchema)]
562pub struct {store} {{
563    // #[validate(length(min = 1, max = 255))]
564    // pub name: String,
565}}
566
567#[derive(Debug, Deserialize, Validate, luxid::JsonSchema)]
568pub struct {update} {{
569    // #[validate(length(min = 1, max = 255))]
570    // pub name: Option<String>,
571}}
572"#
573            ),
574        );
575        plan.insert(
576            "src/validators/mod.rs",
577            MARK_MODULES,
578            format!("pub mod {snake};"),
579        );
580    }
581
582    if flags.policy {
583        let policy = &names.policy;
584
585        plan.file(
586            format!("src/policies/{snake}_policy.rs"),
587            format!(
588                r#"use luxid::prelude::*;
589
590use crate::models::{snake}::{model};
591
592pub struct {policy};
593
594/// A policy is an ordinary function of `(&Auth, &T) -> bool`. Enforce one with
595/// `ctx.authorize({policy}::update, &{snake})?`, or ask without consequence
596/// with `ctx.can({policy}::update, &{snake})`.
597impl {policy} {{
598    pub fn view(_auth: &Auth, _{snake}: &{model}) -> bool {{
599        true
600    }}
601
602    pub fn update(auth: &Auth, {snake}: &{model}) -> bool {{
603        // Replace with your rule, e.g. comparing the owner to the identity.
604        let _ = {snake};
605        auth.check()
606    }}
607}}
608"#
609            ),
610        );
611        plan.insert(
612            "src/policies/mod.rs",
613            MARK_MODULES,
614            format!("pub mod {snake}_policy;"),
615        );
616    }
617
618    if flags.factory {
619        let factory = &names.factory;
620
621        plan.file(
622            format!("src/factories/{snake}_factory.rs"),
623            format!(
624                r#"use luxid::prelude::*;
625
626// Used by the field list below, which `cargo luxid db:sync` fills in from the
627// live schema. Allowed rather than left to warn: a table whose columns are all
628// nullable syncs to an empty list, so the import can be legitimately unused.
629#[allow(unused_imports)]
630use sea_orm::ActiveValue::Set;
631
632use crate::entities::{plural};
633
634/// The typical {model}. Tests override only what they care about:
635///
636/// ```ignore
637/// {factory}::new().create_one().await?;
638/// {factory}::new().count(3).create().await?;
639/// {factory}::new().state(|row| row.name = Set("Ada".into())).create_one().await?;
640/// ```
641pub struct {factory};
642
643impl Factory for {factory} {{
644    type Active = {plural}::ActiveModel;
645
646    fn definition() -> Self::Active {{
647        {plural}::ActiveModel {{
648            // <luxid:fields>  refreshed by `cargo luxid db:sync`
649            // </luxid:fields>
650            ..Default::default()
651        }}
652    }}
653}}
654"#
655            ),
656        );
657        plan.insert(
658            "src/factories/mod.rs",
659            MARK_MODULES,
660            format!("pub mod {snake}_factory;"),
661        );
662    }
663
664    if flags.seeder {
665        let seeder = &names.seeder;
666        let factory = &names.factory;
667
668        plan.file(
669            format!("src/seeders/{snake}_seeder.rs"),
670            format!(
671                r#"use luxid::prelude::*;
672
673use crate::factories::{snake}_factory::{factory};
674
675pub struct {seeder};
676
677impl {seeder} {{
678    pub async fn run() -> luxid::Result<()> {{
679        {factory}::new().count(10).create().await?;
680        Ok(())
681    }}
682}}
683"#
684            ),
685        );
686        plan.insert(
687            "src/seeders/mod.rs",
688            MARK_MODULES,
689            format!("pub mod {snake}_seeder;"),
690        );
691    }
692
693    if flags.controller {
694        let controller = &names.controller;
695        let controller_file = &names.controller_file;
696
697        plan.file(
698            format!("src/controllers/{controller_file}.rs"),
699            format!(
700                r#"use luxid::prelude::*;
701
702use crate::models::{snake}::{model};
703
704pub struct {controller};
705
706#[luxid::controller]
707impl {controller} {{
708    #[openapi(tag = "{plural}")]
709    async fn index(ctx: HttpContext) -> Result<Response> {{
710        let page = ctx.request.input::<u64>("page")?.unwrap_or(1);
711
712        ctx.response.ok({model}::query().paginate(page, 20).await?)
713    }}
714
715    #[openapi(tag = "{plural}", errors = [404])]
716    async fn show(ctx: HttpContext) -> Result<Response> {{
717        let id: i64 = ctx.params.get("id")?;
718
719        ctx.response.ok({model}::find_or_fail(id).await?)
720    }}
721
722    #[openapi(tag = "{plural}", errors = [422])]
723    async fn store(ctx: HttpContext) -> Result<Response> {{
724        let _input = ctx.request.validate::<crate::validators::{snake}::{}>().await?;
725
726        ctx.response.status(501).json("not implemented")
727    }}
728
729    #[openapi(tag = "{plural}", errors = [404, 422])]
730    async fn update(ctx: HttpContext) -> Result<Response> {{
731        let id: i64 = ctx.params.get("id")?;
732        let existing = {model}::find_or_fail(id).await?;
733
734        ctx.authorize(crate::policies::{snake}_policy::{}::update, &existing)?;
735
736        let _input = ctx.request.validate::<crate::validators::{snake}::{}>().await?;
737
738        ctx.response.status(501).json("not implemented")
739    }}
740
741    #[openapi(tag = "{plural}", no_content, errors = [404])]
742    async fn destroy(ctx: HttpContext) -> Result<Response> {{
743        let id: i64 = ctx.params.get("id")?;
744        {model}::find_or_fail(id).await?;
745
746        ctx.response.no_content()
747    }}
748}}
749"#,
750                names.store_request, names.policy, names.update_request
751            ),
752        );
753        plan.insert(
754            "src/controllers/mod.rs",
755            MARK_MODULES,
756            format!("pub mod {controller_file};"),
757        );
758
759        // One line, registering only the actions the controller defines.
760        plan.insert(
761            "src/routes.rs",
762            MARK_ROUTES,
763            format!("r.resource(\"/{plural}\", controllers::{controller_file}::{controller});"),
764        );
765    }
766
767    plan
768}
769
770// -------------------------------------------------------------- writing
771
772/// Write a plan to disk.
773///
774/// Refuses if any file already exists, and writes nothing in that case: a
775/// half-applied generator is worse than one that declined.
776pub fn write(plan: &Plan, root: &Path) -> Result<Vec<PathBuf>> {
777    let mut clashes = Vec::new();
778    for file in &plan.files {
779        if root.join(&file.path).exists() {
780            clashes.push(file.path.display().to_string());
781        }
782    }
783
784    if !clashes.is_empty() {
785        return Err(Error::internal(format!(
786            "these files already exist, so nothing was written: {}",
787            clashes.join(", ")
788        )));
789    }
790
791    let mut written = Vec::new();
792
793    for file in &plan.files {
794        let target = root.join(&file.path);
795
796        if let Some(parent) = target.parent() {
797            std::fs::create_dir_all(parent)
798                .map_err(|err| Error::internal(format!("could not create {parent:?}: {err}")))?;
799        }
800
801        std::fs::write(&target, &file.contents)
802            .map_err(|err| Error::internal(format!("could not write {target:?}: {err}")))?;
803
804        written.push(file.path.clone());
805    }
806
807    for insertion in &plan.insertions {
808        let target = root.join(&insertion.path);
809
810        let existing = std::fs::read_to_string(&target)
811            .map_err(|err| Error::internal(format!("could not read {target:?}: {err}")))?;
812
813        let updated = apply(&existing, insertion.marker, &insertion.line).ok_or_else(|| {
814            Error::internal(format!(
815                "{:?} has no `{}` marker, so there is nowhere to register this. \
816                 Add the marker back, or wire it up by hand.",
817                insertion.path, insertion.marker
818            ))
819        })?;
820
821        std::fs::write(&target, updated)
822            .map_err(|err| Error::internal(format!("could not write {target:?}: {err}")))?;
823
824        written.push(insertion.path.clone());
825    }
826
827    written.sort();
828    written.dedup();
829
830    Ok(written)
831}
832
833/// Insert `line` immediately above `marker`, matching the marker's indentation.
834///
835/// Above rather than below so repeated generation keeps chronological order:
836/// the marker stays at the bottom of its list.
837pub fn apply(source: &str, marker: &str, line: &str) -> Option<String> {
838    let position = source.find(marker)?;
839    let line_start = source[..position]
840        .rfind('\n')
841        .map(|index| index + 1)
842        .unwrap_or(0);
843    let indent = &source[line_start..position];
844
845    let inserted: String = line
846        .lines()
847        .map(|part| format!("{indent}{part}\n"))
848        .collect::<Vec<_>>()
849        .join("");
850
851    let mut out = String::with_capacity(source.len() + inserted.len());
852    out.push_str(&source[..line_start]);
853    out.push_str(&inserted);
854    out.push_str(&source[line_start..]);
855
856    Some(out)
857}
858
859#[cfg(test)]
860mod tests {
861    use super::*;
862
863    #[test]
864    fn inserts_above_the_marker_with_its_indentation() {
865        let source = "fn main() {\n    let x = 1;\n    // <luxid:routes>\n}\n";
866        let updated = apply(source, MARK_ROUTES, "call_me();").expect("marker present");
867
868        assert_eq!(
869            updated,
870            "fn main() {\n    let x = 1;\n    call_me();\n    // <luxid:routes>\n}\n"
871        );
872    }
873
874    #[test]
875    fn repeated_insertion_keeps_order() {
876        let source = "// <luxid:modules>\n";
877        let once = apply(source, MARK_MODULES, "pub mod a;").expect("marker");
878        let twice = apply(&once, MARK_MODULES, "pub mod b;").expect("marker");
879
880        assert_eq!(twice, "pub mod a;\npub mod b;\n// <luxid:modules>\n");
881    }
882
883    #[test]
884    fn multi_line_insertions_are_indented_line_by_line() {
885        let source = "        // <luxid:routes>\n";
886        let updated = apply(source, MARK_ROUTES, "one();\ntwo();").expect("marker");
887
888        assert_eq!(
889            updated,
890            "        one();\n        two();\n        // <luxid:routes>\n"
891        );
892    }
893
894    #[test]
895    fn a_missing_marker_is_reported_rather_than_guessed() {
896        assert!(apply("fn main() {}\n", MARK_ROUTES, "x();").is_none());
897    }
898
899    #[test]
900    fn a_new_app_carries_every_marker_make_model_needs() {
901        let plan = new_app("my-app", &Dependency::Version("0.2".into()));
902
903        let find = |path: &str| {
904            plan.files
905                .iter()
906                .find(|file| file.path == Path::new(path))
907                .unwrap_or_else(|| panic!("{path} missing from the plan"))
908        };
909
910        assert!(find("src/routes.rs").contents.contains(MARK_ROUTES));
911        assert!(find("src/models/mod.rs").contents.contains(MARK_MODULES));
912        assert!(find("src/entities/mod.rs").contents.contains(MARK_MODULES));
913        assert!(
914            find("src/controllers/mod.rs")
915                .contents
916                .contains(MARK_MODULES)
917        );
918        assert!(find("src/factories/mod.rs").contents.contains(MARK_MODULES));
919        assert!(find("src/seeders/mod.rs").contents.contains(MARK_MODULES));
920        assert!(
921            find("migration/src/lib.rs")
922                .contents
923                .contains(MARK_MIGRATIONS)
924        );
925        assert!(
926            find("migration/src/lib.rs")
927                .contents
928                .contains(MARK_MIGRATION_MODULES)
929        );
930    }
931
932    #[test]
933    fn a_hyphenated_app_name_becomes_a_valid_crate_name() {
934        let plan = new_app("my-app", &Dependency::Version("0.2".into()));
935        let manifest = &plan.files[0].contents;
936
937        assert!(manifest.contains(r#"name = "my_app""#), "{manifest}");
938    }
939
940    #[test]
941    fn a_bare_model_generates_only_the_model_and_entity() {
942        let plan = make_model(
943            &Names::new("User"),
944            ModelFlags::default(),
945            "20260101_000001",
946        );
947
948        let paths: Vec<_> = plan
949            .files
950            .iter()
951            .map(|file| file.path.display().to_string())
952            .collect();
953
954        assert_eq!(paths, vec!["src/models/user.rs", "src/entities/users.rs"]);
955    }
956
957    #[test]
958    fn the_all_flag_generates_every_artefact() {
959        let plan = make_model(&Names::new("User"), ModelFlags::all(), "20260101_000001");
960
961        let paths: Vec<_> = plan
962            .files
963            .iter()
964            .map(|file| file.path.display().to_string())
965            .collect();
966
967        for expected in [
968            "src/models/user.rs",
969            "src/entities/users.rs",
970            "migration/src/m20260101_000001_create_users.rs",
971            "src/validators/user.rs",
972            "src/policies/user_policy.rs",
973            "src/factories/user_factory.rs",
974            "src/seeders/user_seeder.rs",
975            "src/controllers/users_controller.rs",
976        ] {
977            assert!(
978                paths.contains(&expected.to_owned()),
979                "{expected} missing from {paths:?}"
980            );
981        }
982    }
983
984    #[test]
985    fn a_controller_registers_one_resource_line() {
986        let plan = make_model(
987            &Names::new("User"),
988            ModelFlags {
989                controller: true,
990                ..ModelFlags::default()
991            },
992            "20260101_000001",
993        );
994
995        let routes = plan
996            .insertions
997            .iter()
998            .find(|insertion| insertion.marker == MARK_ROUTES)
999            .expect("routes registered");
1000
1001        // One line, not five: `resource` registers only the actions the
1002        // controller actually defines.
1003        assert_eq!(routes.line.lines().count(), 1);
1004        assert!(
1005            routes.line.starts_with(r#"r.resource("/users", "#),
1006            "{}",
1007            routes.line
1008        );
1009        assert!(routes.line.contains("UsersController"));
1010    }
1011
1012    #[test]
1013    fn migrations_register_both_the_module_and_the_boxed_value() {
1014        let plan = make_model(
1015            &Names::new("User"),
1016            ModelFlags {
1017                migration: true,
1018                ..ModelFlags::default()
1019            },
1020            "20260101_000001",
1021        );
1022
1023        let markers: Vec<_> = plan
1024            .insertions
1025            .iter()
1026            .map(|insertion| insertion.marker)
1027            .collect();
1028
1029        assert!(markers.contains(&MARK_MIGRATION_MODULES));
1030        assert!(markers.contains(&MARK_MIGRATIONS));
1031    }
1032}
1033
1034pub const MARK_FIELDS_OPEN: &str = "// <luxid:fields>";
1035pub const MARK_FIELDS_CLOSE: &str = "// </luxid:fields>";
1036
1037/// Replace the body between the field markers, preserving everything else.
1038///
1039/// Only the region between the markers is touched, so hand-written rules and
1040/// overrides outside it survive a resync. This is the piece Laravel's stub
1041/// generators never had.
1042pub fn refresh_fields(source: &str, body: &str) -> Option<String> {
1043    let open = source.find(MARK_FIELDS_OPEN)?;
1044    let close = source[open..].find(MARK_FIELDS_CLOSE)? + open;
1045
1046    let line_start = source[..open]
1047        .rfind('\n')
1048        .map(|index| index + 1)
1049        .unwrap_or(0);
1050    let indent = &source[line_start..open];
1051
1052    let open_line_end = source[open..].find('\n')? + open + 1;
1053
1054    let rendered: String = body
1055        .lines()
1056        .map(|line| format!("{indent}{line}\n"))
1057        .collect::<Vec<_>>()
1058        .join("");
1059
1060    let mut out = String::with_capacity(source.len() + rendered.len());
1061    out.push_str(&source[..open_line_end]);
1062    out.push_str(&rendered);
1063    out.push_str(&source[line_start..]);
1064
1065    // `source[line_start..]` re-emits the indent before the closing marker.
1066    let tail_start = close - indent.len();
1067    out.truncate(open_line_end + rendered.len());
1068    out.push_str(&source[tail_start..]);
1069
1070    Some(out)
1071}
1072
1073#[cfg(test)]
1074mod refresh_tests {
1075    use super::*;
1076
1077    const SOURCE: &str = "fn definition() {\n    ActiveModel {\n        // <luxid:fields>\n        old: Set(1),\n        // </luxid:fields>\n        ..Default::default()\n    }\n}\n";
1078
1079    #[test]
1080    fn replaces_only_the_marked_region() {
1081        let updated = refresh_fields(SOURCE, "name: Set(\"name\".to_owned()),").expect("markers");
1082
1083        assert!(updated.contains("name: Set(\"name\".to_owned()),"));
1084        assert!(
1085            !updated.contains("old: Set(1)"),
1086            "the old body was replaced"
1087        );
1088
1089        // Everything outside the markers survives.
1090        assert!(updated.contains("..Default::default()"));
1091        assert!(updated.starts_with("fn definition() {"));
1092        assert!(updated.trim_end().ends_with('}'));
1093    }
1094
1095    #[test]
1096    fn is_idempotent() {
1097        let once = refresh_fields(SOURCE, "a: Set(1),").expect("markers");
1098        let twice = refresh_fields(&once, "a: Set(1),").expect("markers");
1099
1100        assert_eq!(once, twice, "resyncing an unchanged schema changes nothing");
1101    }
1102
1103    #[test]
1104    fn keeps_the_marker_indentation() {
1105        let updated = refresh_fields(SOURCE, "a: Set(1),").expect("markers");
1106        assert!(updated.contains("\n        a: Set(1),\n"), "{updated}");
1107    }
1108
1109    #[test]
1110    fn an_empty_body_clears_the_region() {
1111        let updated = refresh_fields(SOURCE, "").expect("markers");
1112        assert!(!updated.contains("old: Set(1)"));
1113    }
1114
1115    #[test]
1116    fn a_file_without_markers_is_left_alone() {
1117        assert!(refresh_fields("fn nothing() {}", "a: Set(1),").is_none());
1118    }
1119}
1120
1121/// Attributes a user wrote above each field inside the markers.
1122///
1123/// `db:sync` regenerates the field list, which would otherwise discard things
1124/// like `#[serde(skip_serializing)]` on a password hash — a silent change from
1125/// "never sent" to "sent to every client". Attributes are carried across
1126/// instead.
1127///
1128/// `#[sea_orm(primary_key)]` is excluded because the generator emits it itself.
1129pub fn field_attributes(source: &str) -> BTreeMap<String, Vec<String>> {
1130    let mut found: BTreeMap<String, Vec<String>> = BTreeMap::new();
1131
1132    let Some(open) = source.find(MARK_FIELDS_OPEN) else {
1133        return found;
1134    };
1135    let Some(close) = source[open..]
1136        .find(MARK_FIELDS_CLOSE)
1137        .map(|index| index + open)
1138    else {
1139        return found;
1140    };
1141
1142    let mut pending: Vec<String> = Vec::new();
1143
1144    for line in source[open..close].lines() {
1145        let trimmed = line.trim();
1146
1147        if trimmed.starts_with("#[") {
1148            if trimmed != "#[sea_orm(primary_key)]" {
1149                pending.push(trimmed.to_owned());
1150            }
1151            continue;
1152        }
1153
1154        if let Some(rest) = trimmed.strip_prefix("pub ")
1155            && let Some((name, _)) = rest.split_once(':')
1156            && !pending.is_empty()
1157        {
1158            found.insert(name.trim().to_owned(), std::mem::take(&mut pending));
1159            continue;
1160        }
1161
1162        pending.clear();
1163    }
1164
1165    found
1166}
1167
1168#[cfg(test)]
1169mod attribute_tests {
1170    use super::*;
1171
1172    const SOURCE: &str = "pub struct Model {\n    // <luxid:fields>\n    #[sea_orm(primary_key)]\n    pub id: i64,\n    #[serde(skip_serializing)]\n    pub password: String,\n    pub email: String,\n    // </luxid:fields>\n}\n";
1173
1174    #[test]
1175    fn carries_user_written_attributes_across_a_resync() {
1176        let found = field_attributes(SOURCE);
1177
1178        assert_eq!(
1179            found.get("password"),
1180            Some(&vec!["#[serde(skip_serializing)]".to_owned()])
1181        );
1182        assert_eq!(found.get("email"), None, "no attributes, nothing to carry");
1183    }
1184
1185    #[test]
1186    fn the_generated_primary_key_attribute_is_not_carried() {
1187        // The generator emits it, so carrying it too would duplicate it.
1188        assert_eq!(field_attributes(SOURCE).get("id"), None);
1189    }
1190
1191    #[test]
1192    fn a_file_without_markers_yields_nothing() {
1193        assert!(field_attributes("pub struct Model {}").is_empty());
1194    }
1195}