1use std::collections::{BTreeMap, BTreeSet};
11use std::path::{Path, PathBuf};
12
13use luxid_core::error::{Error, Result};
14
15use crate::naming::Names;
16
17#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct NewFile {
20 pub path: PathBuf,
21 pub contents: String,
22}
23
24#[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 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
68pub 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#[derive(Debug, Clone)]
79pub enum Dependency {
80 Version(String),
82 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 run -- 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 for module in ["models", "entities", "validators", "services", "middleware"] {
291 plan.file(format!("src/{module}/mod.rs"), format!("{MARK_MODULES}\n"));
292 }
293
294 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 plan.file(
348 ".cargo/config.toml",
349 r#"# A faster linker is the single biggest lever on rebuild time.
350#
351# Uncomment after installing mold (https://github.com/rui314/mold), or swap in
352# `lld`. Left off by default so this project builds anywhere.
353#
354# [target.x86_64-unknown-linux-gnu]
355# rustflags = ["-C", "link-arg=-fuse-ld=mold", "-C", "debuginfo=1"]
356"#,
357 );
358
359 plan.file(
360 "README.md",
361 format!(
362 r#"# {crate_name}
363
364```sh
365cargo run # serve on http://127.0.0.1:3000
366cargo run -- routes # the routing table
367cargo run -- migrate # apply migrations
368cargo run -- openapi # the OpenAPI 3.1 document
369```
370
371Generated by `luxid new`.
372"#
373 ),
374 );
375
376 plan
377}
378
379#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
383pub struct ModelFlags {
384 pub migration: bool,
385 pub factory: bool,
386 pub seeder: bool,
387 pub controller: bool,
388 pub policy: bool,
389 pub requests: bool,
390}
391
392impl ModelFlags {
393 pub fn all() -> Self {
395 Self {
396 migration: true,
397 factory: true,
398 seeder: true,
399 controller: true,
400 policy: true,
401 requests: true,
402 }
403 }
404}
405
406pub fn make_model(names: &Names, flags: ModelFlags, timestamp: &str) -> Plan {
407 let mut plan = Plan::default();
408 let Names {
409 model,
410 snake,
411 plural,
412 ..
413 } = names;
414
415 plan.file(
416 format!("src/models/{snake}.rs"),
417 format!(
418 r#"pub use crate::entities::{plural}::Model as {model};
419
420// Relations, scopes and hooks go here. Declare relations in the attribute and
421// scopes as `#[scope]` functions:
422//
423// #[luxid::model(has_many(posts = Post, fk = "{snake}_id"))]
424// impl {model} {{
425// #[scope]
426// fn active(query: Query<crate::entities::{plural}::Entity>)
427// -> Query<crate::entities::{plural}::Entity>
428// {{
429// query.where_null({model}::deleted_at)
430// }}
431// }}
432#[luxid::model()]
433impl {model} {{}}
434"#
435 ),
436 );
437 plan.insert(
438 "src/models/mod.rs",
439 MARK_MODULES,
440 format!("pub mod {snake};"),
441 );
442
443 plan.file(
446 format!("src/entities/{plural}.rs"),
447 format!(
448 r#"//! Generated from the database schema. Re-run `luxid db:sync` after a
449//! migration rather than editing this by hand.
450
451use sea_orm::entity::prelude::*;
452
453#[derive(Clone, Debug, PartialEq, DeriveEntityModel, serde::Serialize, luxid::Model)]
454#[sea_orm(table_name = "{plural}")]
455pub struct Model {{
456 // <luxid:fields> refreshed by `cargo run -- db:sync`
457 #[sea_orm(primary_key)]
458 pub id: i64,
459 // </luxid:fields>
460 #[sea_orm(ignore)]
461 #[serde(flatten)]
462 pub relations: luxid::Relations,
463}}
464
465#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
466pub enum Relation {{}}
467
468impl ActiveModelBehavior for ActiveModel {{}}
469"#
470 ),
471 );
472 plan.insert(
473 "src/entities/mod.rs",
474 MARK_MODULES,
475 format!("pub mod {plural};"),
476 );
477
478 if flags.migration {
479 let migration = format!("m{timestamp}_create_{plural}");
480
481 plan.file(
482 format!("migration/src/{migration}.rs"),
483 format!(
484 r#"use sea_orm_migration::prelude::*;
485use sea_orm_migration::schema::*;
486
487#[derive(DeriveIden)]
488enum {} {{
489 Table,
490 Id,
491}}
492
493pub struct Migration;
494
495impl MigrationName for Migration {{
496 fn name(&self) -> &str {{
497 "{migration}"
498 }}
499}}
500
501#[async_trait::async_trait]
502impl MigrationTrait for Migration {{
503 async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {{
504 manager
505 .create_table(
506 Table::create()
507 .table({0}::Table)
508 .if_not_exists()
509 .col(pk_auto({0}::Id))
510 // Add your columns here.
511 .to_owned(),
512 )
513 .await
514 }}
515
516 async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {{
517 manager.drop_table(Table::drop().table({0}::Table).to_owned()).await
518 }}
519}}
520"#,
521 crate::naming::to_pascal(plural)
522 ),
523 );
524
525 plan.insert(
526 "migration/src/lib.rs",
527 MARK_MIGRATION_MODULES,
528 format!("mod {migration};"),
529 );
530 plan.insert(
531 "migration/src/lib.rs",
532 MARK_MIGRATIONS,
533 format!("Box::new({migration}::Migration),"),
534 );
535 }
536
537 if flags.requests {
538 let store = &names.store_request;
539 let update = &names.update_request;
540
541 plan.file(
542 format!("src/validators/{snake}.rs"),
543 format!(
544 r#"use luxid::prelude::*;
545use serde::Deserialize;
546
547// `JsonSchema` lets `#[openapi(body = ..)]` describe this request.
548#[derive(Debug, Deserialize, Validate, luxid::JsonSchema)]
549pub struct {store} {{
550 // #[validate(length(min = 1, max = 255))]
551 // pub name: String,
552}}
553
554#[derive(Debug, Deserialize, Validate, luxid::JsonSchema)]
555pub struct {update} {{
556 // #[validate(length(min = 1, max = 255))]
557 // pub name: Option<String>,
558}}
559"#
560 ),
561 );
562 plan.insert(
563 "src/validators/mod.rs",
564 MARK_MODULES,
565 format!("pub mod {snake};"),
566 );
567 }
568
569 if flags.policy {
570 let policy = &names.policy;
571
572 plan.file(
573 format!("src/policies/{snake}_policy.rs"),
574 format!(
575 r#"use luxid::prelude::*;
576
577use crate::models::{snake}::{model};
578
579pub struct {policy};
580
581/// A policy is an ordinary function of `(&Auth, &T) -> bool`. Enforce one with
582/// `ctx.authorize({policy}::update, &{snake})?`, or ask without consequence
583/// with `ctx.can({policy}::update, &{snake})`.
584impl {policy} {{
585 pub fn view(_auth: &Auth, _{snake}: &{model}) -> bool {{
586 true
587 }}
588
589 pub fn update(auth: &Auth, {snake}: &{model}) -> bool {{
590 // Replace with your rule, e.g. comparing the owner to the identity.
591 let _ = {snake};
592 auth.check()
593 }}
594}}
595"#
596 ),
597 );
598 plan.insert(
599 "src/policies/mod.rs",
600 MARK_MODULES,
601 format!("pub mod {snake}_policy;"),
602 );
603 }
604
605 if flags.factory {
606 let factory = &names.factory;
607
608 plan.file(
609 format!("src/factories/{snake}_factory.rs"),
610 format!(
611 r#"use luxid::prelude::*;
612use sea_orm::ActiveValue::Set;
613
614use crate::entities::{plural};
615
616/// The typical {model}. Tests override only what they care about:
617///
618/// {factory}::new().create_one().await?;
619/// {factory}::new().count(3).create().await?;
620/// {factory}::new().state(|row| row.name = Set("Ada".into())).create_one().await?;
621pub struct {factory};
622
623impl Factory for {factory} {{
624 type Active = {plural}::ActiveModel;
625
626 fn definition() -> Self::Active {{
627 {plural}::ActiveModel {{
628 // <luxid:fields> refreshed by `cargo run -- db:sync`
629 // </luxid:fields>
630 ..Default::default()
631 }}
632 }}
633}}
634"#
635 ),
636 );
637 plan.insert(
638 "src/factories/mod.rs",
639 MARK_MODULES,
640 format!("pub mod {snake}_factory;"),
641 );
642 }
643
644 if flags.seeder {
645 let seeder = &names.seeder;
646 let factory = &names.factory;
647
648 plan.file(
649 format!("src/seeders/{snake}_seeder.rs"),
650 format!(
651 r#"use luxid::prelude::*;
652
653use crate::factories::{snake}_factory::{factory};
654
655pub struct {seeder};
656
657impl {seeder} {{
658 pub async fn run() -> luxid::Result<()> {{
659 {factory}::new().count(10).create().await?;
660 Ok(())
661 }}
662}}
663"#
664 ),
665 );
666 plan.insert(
667 "src/seeders/mod.rs",
668 MARK_MODULES,
669 format!("pub mod {snake}_seeder;"),
670 );
671 }
672
673 if flags.controller {
674 let controller = &names.controller;
675 let controller_file = &names.controller_file;
676
677 plan.file(
678 format!("src/controllers/{controller_file}.rs"),
679 format!(
680 r#"use luxid::prelude::*;
681
682use crate::models::{snake}::{model};
683
684pub struct {controller};
685
686#[luxid::controller]
687impl {controller} {{
688 #[openapi(tag = "{plural}")]
689 async fn index(ctx: HttpContext) -> Result<Response> {{
690 let page = ctx.request.input::<u64>("page")?.unwrap_or(1);
691
692 ctx.response.ok({model}::query().paginate(page, 20).await?)
693 }}
694
695 #[openapi(tag = "{plural}", errors = [404])]
696 async fn show(ctx: HttpContext) -> Result<Response> {{
697 let id: i64 = ctx.params.get("id")?;
698
699 ctx.response.ok({model}::find_or_fail(id).await?)
700 }}
701
702 #[openapi(tag = "{plural}", errors = [422])]
703 async fn store(ctx: HttpContext) -> Result<Response> {{
704 let _input = ctx.request.validate::<crate::validators::{snake}::{}>().await?;
705
706 ctx.response.status(501).json("not implemented")
707 }}
708
709 #[openapi(tag = "{plural}", errors = [404, 422])]
710 async fn update(ctx: HttpContext) -> Result<Response> {{
711 let id: i64 = ctx.params.get("id")?;
712 let existing = {model}::find_or_fail(id).await?;
713
714 ctx.authorize(crate::policies::{snake}_policy::{}::update, &existing)?;
715
716 let _input = ctx.request.validate::<crate::validators::{snake}::{}>().await?;
717
718 ctx.response.status(501).json("not implemented")
719 }}
720
721 #[openapi(tag = "{plural}", no_content, errors = [404])]
722 async fn destroy(ctx: HttpContext) -> Result<Response> {{
723 let id: i64 = ctx.params.get("id")?;
724 {model}::find_or_fail(id).await?;
725
726 ctx.response.no_content()
727 }}
728}}
729"#,
730 names.store_request, names.policy, names.update_request
731 ),
732 );
733 plan.insert(
734 "src/controllers/mod.rs",
735 MARK_MODULES,
736 format!("pub mod {controller_file};"),
737 );
738
739 plan.insert(
741 "src/routes.rs",
742 MARK_ROUTES,
743 format!("r.resource(\"/{plural}\", controllers::{controller_file}::{controller});"),
744 );
745 }
746
747 plan
748}
749
750pub fn write(plan: &Plan, root: &Path) -> Result<Vec<PathBuf>> {
757 let mut clashes = Vec::new();
758 for file in &plan.files {
759 if root.join(&file.path).exists() {
760 clashes.push(file.path.display().to_string());
761 }
762 }
763
764 if !clashes.is_empty() {
765 return Err(Error::internal(format!(
766 "these files already exist, so nothing was written: {}",
767 clashes.join(", ")
768 )));
769 }
770
771 let mut written = Vec::new();
772
773 for file in &plan.files {
774 let target = root.join(&file.path);
775
776 if let Some(parent) = target.parent() {
777 std::fs::create_dir_all(parent)
778 .map_err(|err| Error::internal(format!("could not create {parent:?}: {err}")))?;
779 }
780
781 std::fs::write(&target, &file.contents)
782 .map_err(|err| Error::internal(format!("could not write {target:?}: {err}")))?;
783
784 written.push(file.path.clone());
785 }
786
787 for insertion in &plan.insertions {
788 let target = root.join(&insertion.path);
789
790 let existing = std::fs::read_to_string(&target)
791 .map_err(|err| Error::internal(format!("could not read {target:?}: {err}")))?;
792
793 let updated = apply(&existing, insertion.marker, &insertion.line).ok_or_else(|| {
794 Error::internal(format!(
795 "{:?} has no `{}` marker, so there is nowhere to register this. \
796 Add the marker back, or wire it up by hand.",
797 insertion.path, insertion.marker
798 ))
799 })?;
800
801 std::fs::write(&target, updated)
802 .map_err(|err| Error::internal(format!("could not write {target:?}: {err}")))?;
803
804 written.push(insertion.path.clone());
805 }
806
807 written.sort();
808 written.dedup();
809
810 Ok(written)
811}
812
813pub fn apply(source: &str, marker: &str, line: &str) -> Option<String> {
818 let position = source.find(marker)?;
819 let line_start = source[..position]
820 .rfind('\n')
821 .map(|index| index + 1)
822 .unwrap_or(0);
823 let indent = &source[line_start..position];
824
825 let inserted: String = line
826 .lines()
827 .map(|part| format!("{indent}{part}\n"))
828 .collect::<Vec<_>>()
829 .join("");
830
831 let mut out = String::with_capacity(source.len() + inserted.len());
832 out.push_str(&source[..line_start]);
833 out.push_str(&inserted);
834 out.push_str(&source[line_start..]);
835
836 Some(out)
837}
838
839#[cfg(test)]
840mod tests {
841 use super::*;
842
843 #[test]
844 fn inserts_above_the_marker_with_its_indentation() {
845 let source = "fn main() {\n let x = 1;\n // <luxid:routes>\n}\n";
846 let updated = apply(source, MARK_ROUTES, "call_me();").expect("marker present");
847
848 assert_eq!(
849 updated,
850 "fn main() {\n let x = 1;\n call_me();\n // <luxid:routes>\n}\n"
851 );
852 }
853
854 #[test]
855 fn repeated_insertion_keeps_order() {
856 let source = "// <luxid:modules>\n";
857 let once = apply(source, MARK_MODULES, "pub mod a;").expect("marker");
858 let twice = apply(&once, MARK_MODULES, "pub mod b;").expect("marker");
859
860 assert_eq!(twice, "pub mod a;\npub mod b;\n// <luxid:modules>\n");
861 }
862
863 #[test]
864 fn multi_line_insertions_are_indented_line_by_line() {
865 let source = " // <luxid:routes>\n";
866 let updated = apply(source, MARK_ROUTES, "one();\ntwo();").expect("marker");
867
868 assert_eq!(
869 updated,
870 " one();\n two();\n // <luxid:routes>\n"
871 );
872 }
873
874 #[test]
875 fn a_missing_marker_is_reported_rather_than_guessed() {
876 assert!(apply("fn main() {}\n", MARK_ROUTES, "x();").is_none());
877 }
878
879 #[test]
880 fn a_new_app_carries_every_marker_make_model_needs() {
881 let plan = new_app("my-app", &Dependency::Version("0.1".into()));
882
883 let find = |path: &str| {
884 plan.files
885 .iter()
886 .find(|file| file.path == Path::new(path))
887 .unwrap_or_else(|| panic!("{path} missing from the plan"))
888 };
889
890 assert!(find("src/routes.rs").contents.contains(MARK_ROUTES));
891 assert!(find("src/models/mod.rs").contents.contains(MARK_MODULES));
892 assert!(find("src/entities/mod.rs").contents.contains(MARK_MODULES));
893 assert!(
894 find("src/controllers/mod.rs")
895 .contents
896 .contains(MARK_MODULES)
897 );
898 assert!(find("src/factories/mod.rs").contents.contains(MARK_MODULES));
899 assert!(find("src/seeders/mod.rs").contents.contains(MARK_MODULES));
900 assert!(
901 find("migration/src/lib.rs")
902 .contents
903 .contains(MARK_MIGRATIONS)
904 );
905 assert!(
906 find("migration/src/lib.rs")
907 .contents
908 .contains(MARK_MIGRATION_MODULES)
909 );
910 }
911
912 #[test]
913 fn a_hyphenated_app_name_becomes_a_valid_crate_name() {
914 let plan = new_app("my-app", &Dependency::Version("0.1".into()));
915 let manifest = &plan.files[0].contents;
916
917 assert!(manifest.contains(r#"name = "my_app""#), "{manifest}");
918 }
919
920 #[test]
921 fn a_bare_model_generates_only_the_model_and_entity() {
922 let plan = make_model(
923 &Names::new("User"),
924 ModelFlags::default(),
925 "20260101_000001",
926 );
927
928 let paths: Vec<_> = plan
929 .files
930 .iter()
931 .map(|file| file.path.display().to_string())
932 .collect();
933
934 assert_eq!(paths, vec!["src/models/user.rs", "src/entities/users.rs"]);
935 }
936
937 #[test]
938 fn the_all_flag_generates_every_artefact() {
939 let plan = make_model(&Names::new("User"), ModelFlags::all(), "20260101_000001");
940
941 let paths: Vec<_> = plan
942 .files
943 .iter()
944 .map(|file| file.path.display().to_string())
945 .collect();
946
947 for expected in [
948 "src/models/user.rs",
949 "src/entities/users.rs",
950 "migration/src/m20260101_000001_create_users.rs",
951 "src/validators/user.rs",
952 "src/policies/user_policy.rs",
953 "src/factories/user_factory.rs",
954 "src/seeders/user_seeder.rs",
955 "src/controllers/users_controller.rs",
956 ] {
957 assert!(
958 paths.contains(&expected.to_owned()),
959 "{expected} missing from {paths:?}"
960 );
961 }
962 }
963
964 #[test]
965 fn a_controller_registers_one_resource_line() {
966 let plan = make_model(
967 &Names::new("User"),
968 ModelFlags {
969 controller: true,
970 ..ModelFlags::default()
971 },
972 "20260101_000001",
973 );
974
975 let routes = plan
976 .insertions
977 .iter()
978 .find(|insertion| insertion.marker == MARK_ROUTES)
979 .expect("routes registered");
980
981 assert_eq!(routes.line.lines().count(), 1);
984 assert!(
985 routes.line.starts_with(r#"r.resource("/users", "#),
986 "{}",
987 routes.line
988 );
989 assert!(routes.line.contains("UsersController"));
990 }
991
992 #[test]
993 fn migrations_register_both_the_module_and_the_boxed_value() {
994 let plan = make_model(
995 &Names::new("User"),
996 ModelFlags {
997 migration: true,
998 ..ModelFlags::default()
999 },
1000 "20260101_000001",
1001 );
1002
1003 let markers: Vec<_> = plan
1004 .insertions
1005 .iter()
1006 .map(|insertion| insertion.marker)
1007 .collect();
1008
1009 assert!(markers.contains(&MARK_MIGRATION_MODULES));
1010 assert!(markers.contains(&MARK_MIGRATIONS));
1011 }
1012}
1013
1014pub const MARK_FIELDS_OPEN: &str = "// <luxid:fields>";
1015pub const MARK_FIELDS_CLOSE: &str = "// </luxid:fields>";
1016
1017pub fn refresh_fields(source: &str, body: &str) -> Option<String> {
1023 let open = source.find(MARK_FIELDS_OPEN)?;
1024 let close = source[open..].find(MARK_FIELDS_CLOSE)? + open;
1025
1026 let line_start = source[..open]
1027 .rfind('\n')
1028 .map(|index| index + 1)
1029 .unwrap_or(0);
1030 let indent = &source[line_start..open];
1031
1032 let open_line_end = source[open..].find('\n')? + open + 1;
1033
1034 let rendered: String = body
1035 .lines()
1036 .map(|line| format!("{indent}{line}\n"))
1037 .collect::<Vec<_>>()
1038 .join("");
1039
1040 let mut out = String::with_capacity(source.len() + rendered.len());
1041 out.push_str(&source[..open_line_end]);
1042 out.push_str(&rendered);
1043 out.push_str(&source[line_start..]);
1044
1045 let tail_start = close - indent.len();
1047 out.truncate(open_line_end + rendered.len());
1048 out.push_str(&source[tail_start..]);
1049
1050 Some(out)
1051}
1052
1053#[cfg(test)]
1054mod refresh_tests {
1055 use super::*;
1056
1057 const SOURCE: &str = "fn definition() {\n ActiveModel {\n // <luxid:fields>\n old: Set(1),\n // </luxid:fields>\n ..Default::default()\n }\n}\n";
1058
1059 #[test]
1060 fn replaces_only_the_marked_region() {
1061 let updated = refresh_fields(SOURCE, "name: Set(\"name\".to_owned()),").expect("markers");
1062
1063 assert!(updated.contains("name: Set(\"name\".to_owned()),"));
1064 assert!(
1065 !updated.contains("old: Set(1)"),
1066 "the old body was replaced"
1067 );
1068
1069 assert!(updated.contains("..Default::default()"));
1071 assert!(updated.starts_with("fn definition() {"));
1072 assert!(updated.trim_end().ends_with('}'));
1073 }
1074
1075 #[test]
1076 fn is_idempotent() {
1077 let once = refresh_fields(SOURCE, "a: Set(1),").expect("markers");
1078 let twice = refresh_fields(&once, "a: Set(1),").expect("markers");
1079
1080 assert_eq!(once, twice, "resyncing an unchanged schema changes nothing");
1081 }
1082
1083 #[test]
1084 fn keeps_the_marker_indentation() {
1085 let updated = refresh_fields(SOURCE, "a: Set(1),").expect("markers");
1086 assert!(updated.contains("\n a: Set(1),\n"), "{updated}");
1087 }
1088
1089 #[test]
1090 fn an_empty_body_clears_the_region() {
1091 let updated = refresh_fields(SOURCE, "").expect("markers");
1092 assert!(!updated.contains("old: Set(1)"));
1093 }
1094
1095 #[test]
1096 fn a_file_without_markers_is_left_alone() {
1097 assert!(refresh_fields("fn nothing() {}", "a: Set(1),").is_none());
1098 }
1099}
1100
1101pub fn field_attributes(source: &str) -> BTreeMap<String, Vec<String>> {
1110 let mut found: BTreeMap<String, Vec<String>> = BTreeMap::new();
1111
1112 let Some(open) = source.find(MARK_FIELDS_OPEN) else {
1113 return found;
1114 };
1115 let Some(close) = source[open..]
1116 .find(MARK_FIELDS_CLOSE)
1117 .map(|index| index + open)
1118 else {
1119 return found;
1120 };
1121
1122 let mut pending: Vec<String> = Vec::new();
1123
1124 for line in source[open..close].lines() {
1125 let trimmed = line.trim();
1126
1127 if trimmed.starts_with("#[") {
1128 if trimmed != "#[sea_orm(primary_key)]" {
1129 pending.push(trimmed.to_owned());
1130 }
1131 continue;
1132 }
1133
1134 if let Some(rest) = trimmed.strip_prefix("pub ")
1135 && let Some((name, _)) = rest.split_once(':')
1136 && !pending.is_empty()
1137 {
1138 found.insert(name.trim().to_owned(), std::mem::take(&mut pending));
1139 continue;
1140 }
1141
1142 pending.clear();
1143 }
1144
1145 found
1146}
1147
1148#[cfg(test)]
1149mod attribute_tests {
1150 use super::*;
1151
1152 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";
1153
1154 #[test]
1155 fn carries_user_written_attributes_across_a_resync() {
1156 let found = field_attributes(SOURCE);
1157
1158 assert_eq!(
1159 found.get("password"),
1160 Some(&vec!["#[serde(skip_serializing)]".to_owned()])
1161 );
1162 assert_eq!(found.get("email"), None, "no attributes, nothing to carry");
1163 }
1164
1165 #[test]
1166 fn the_generated_primary_key_attribute_is_not_carried() {
1167 assert_eq!(field_attributes(SOURCE).get("id"), None);
1169 }
1170
1171 #[test]
1172 fn a_file_without_markers_yields_nothing() {
1173 assert!(field_attributes("pub struct Model {}").is_empty());
1174 }
1175}