1use std::{
2 fs,
3 path::{Path, PathBuf},
4};
5
6type ProjectResult<T> = Result<T, Box<dyn std::error::Error>>;
7
8const APP_MODULES_MARKER: &str = "// che-rest:startapp modules";
9const APP_INSTALL_MARKER: &str = "// che-rest:startapp installed apps";
10
11#[derive(Debug, Clone)]
12pub struct StartProjectOptions {
13 pub name: String,
14 pub out: PathBuf,
15 pub che_rest_path: String,
16 pub che_orm_path: String,
17 pub with_auth: bool,
18 pub force: bool,
19}
20
21#[derive(Debug, Clone)]
22pub struct StartAppOptions {
23 pub name: String,
24 pub models: Vec<String>,
25 pub root: PathBuf,
26 pub force: bool,
27}
28
29#[derive(Debug, Clone, Copy, Default, clap::ValueEnum)]
30pub enum ProjectLayout {
31 Single,
32 #[default]
33 Modular,
34}
35
36pub fn startproject(options: StartProjectOptions) -> ProjectResult<()> {
37 create_project(&options)?;
38 println!(
39 "Created project {}",
40 options.out.join(&options.name).display()
41 );
42 println!("Next steps:");
43 println!(" cd {}", options.out.join(&options.name).display());
44 println!(" cargo run --bin manage -- createapp tasks --model Task");
45 print_migration_steps();
46 Ok(())
47}
48
49pub fn startproject_with_layout(
52 options: StartProjectOptions,
53 layout: ProjectLayout,
54) -> ProjectResult<()> {
55 create_project(&options)?;
56 let root = options.out.join(&options.name);
57 let models = vec!["Task".to_owned()];
58 match layout {
59 ProjectLayout::Modular => startapp(StartAppOptions {
60 name: "tasks".into(),
61 models,
62 root: root.clone(),
63 force: options.force,
64 })?,
65 ProjectLayout::Single => {
66 write_file(
67 &root.join("src/lib.rs"),
68 &format!(
69 "pub mod apps;\n{}",
70 app_module_template("tasks", &models, "src/migrations")
71 ),
72 )?;
73 write_file(&root.join("src/models.rs"), &models_rs_template(&models))?;
74 write_file(
75 &root.join("src/serializers.rs"),
76 &serializers_rs_template(&models),
77 )?;
78 write_file(&root.join("src/filters.rs"), &filters_rs_template(&models))?;
79 write_file(&root.join("src/views.rs"), &views_rs_template(&models))?;
80 write_file(&root.join("src/migrations/mod.rs"), EMPTY_MIGRATIONS)?;
81 let registry = apps_mod_template(options.with_auth).replace(
82 APP_INSTALL_MARKER,
83 &format!(".add(crate::module())\n {APP_INSTALL_MARKER}"),
84 );
85 write_file(&root.join("src/apps/mod.rs"), ®istry)?;
86 }
87 }
88 write_file(
89 &root.join("README.md"),
90 &project_readme_template(&options.name, layout),
91 )?;
92 println!("Created project {} with {layout:?} layout", root.display());
93 println!("Next steps:");
94 println!(" cd {}", root.display());
95 print_migration_steps();
96 Ok(())
97}
98
99const EMPTY_MIGRATIONS: &str = "// che-orm: migrations begin\npub fn all() -> Vec<che_orm::Migration> { vec![] }\n// che-orm: migrations end\n";
100
101fn print_migration_steps() {
102 println!(" cargo run --bin manage -- schema");
103 println!(" cargo run --bin manage -- makemigrations --name initial");
104 println!(" cargo run --bin manage -- migrate");
105 println!(" cargo run");
106}
107
108fn project_readme_template(name: &str, layout: ProjectLayout) -> String {
109 let source = match layout {
110 ProjectLayout::Single => {
111 "src/ (models.rs, serializers.rs, filters.rs, views.rs and migrations/)"
112 }
113 ProjectLayout::Modular => "src/apps/tasks/",
114 };
115 format!(
116 r#"# {name}
117
118The starter Task REST resource lives in {source}. Models use
119`#[orm(app = super::APP_NAME)]`; Task's table is `tasks_task`.
120The shared `APP_NAME` is returned by `AppModule::name()`.
121
122Generate the first migration explicitly before starting the server:
123
124```bash
125cargo run --bin manage -- schema
126cargo run --bin manage -- makemigrations --name initial
127cargo run --bin manage -- migrate
128cargo run
129```
130
131Configuration lives in `app.toml`. The server listens at `http://127.0.0.1:3000`,
132with Task at `/api/task/` and OpenAPI at `/api/openapi.json`.
133
134```bash
135cargo run --bin manage -- createapp blog --model Post
136cargo run --bin manage -- makemigrations --name add_blog
137cargo run --bin manage -- migrate
138```
139
140`createapp` (also named `startapp`) works in either layout and creates
141`src/apps/blog/` with models, serializers, filters, ViewSets, an `APP_NAME`
142constant and an empty compiled migration registry. Installing an app registers
143its migrations. Existing applied migrations must retain their identities and
144checksums. An explicit `#[orm(table = "existing_table")]` preserves an existing
145physical table name.
146
147Select exactly one backend through Cargo features (`sqlite` or `postgres`) and
148use a matching URL in app.toml. Startup does not apply migrations.
149"#
150 )
151}
152
153fn create_project(options: &StartProjectOptions) -> ProjectResult<()> {
154 validate_project_name(&options.name)?;
155
156 let project_dir = options.out.join(&options.name);
157 prepare_project_dir(&project_dir, options.force)?;
158
159 let crate_name = options.name.replace('-', "_");
160
161 write_file(
162 &project_dir.join("Cargo.toml"),
163 &cargo_toml_template(&options.name, &options.che_rest_path, &options.che_orm_path),
164 )?;
165 write_file(&project_dir.join("app.toml"), app_toml_template())?;
166 write_file(
167 &project_dir.join("AGENTS.md"),
168 &agents_md_template(options.with_auth),
169 )?;
170 write_file(&project_dir.join("src/lib.rs"), lib_rs_template())?;
171 write_file(
172 &project_dir.join("src/main.rs"),
173 &main_rs_template(&crate_name),
174 )?;
175 write_file(
176 &project_dir.join("src/bin/manage.rs"),
177 &manage_rs_template(&crate_name),
178 )?;
179 write_file(
180 &project_dir.join("src/apps/mod.rs"),
181 &apps_mod_template(options.with_auth),
182 )?;
183
184 Ok(())
185}
186
187pub fn startapp(options: StartAppOptions) -> ProjectResult<()> {
188 validate_app_name(&options.name)?;
189 let models = if options.models.is_empty() {
190 vec![default_model_name(&options.name)]
191 } else {
192 options.models
193 };
194 for model in &models {
195 validate_model_name(model)?;
196 }
197
198 let app_dir = options.root.join("src/apps").join(&options.name);
199 prepare_app_dir(&app_dir, options.force)?;
200
201 write_file(&app_dir.join("models.rs"), &models_rs_template(&models))?;
202 write_file(
203 &app_dir.join("serializers.rs"),
204 &serializers_rs_template(&models),
205 )?;
206 write_file(&app_dir.join("filters.rs"), &filters_rs_template(&models))?;
207 write_file(&app_dir.join("views.rs"), &views_rs_template(&models))?;
208 write_file(
209 &app_dir.join("mod.rs"),
210 &app_mod_template(&options.name, &models),
211 )?;
212 register_app(&options.root.join("src/apps/mod.rs"), &options.name)?;
213 write_file(&app_dir.join("migrations/mod.rs"), EMPTY_MIGRATIONS)?;
214
215 println!("Created app {}", app_dir.display());
216 println!("Next steps:");
217 println!(" cargo run --bin manage -- makemigrations");
218 println!(" cargo run --bin manage -- migrate");
219 Ok(())
220}
221
222fn prepare_app_dir(app_dir: &Path, force: bool) -> ProjectResult<()> {
223 if !app_dir.exists() {
224 fs::create_dir_all(app_dir)?;
225 return Ok(());
226 }
227
228 if !app_dir.is_dir() {
229 return Err(format!("app path is not a directory: {}", app_dir.display()).into());
230 }
231
232 if force {
233 return Ok(());
234 }
235
236 if fs::read_dir(app_dir)?.next().is_some() {
237 return Err(format!(
238 "app directory already exists and is not empty: {}",
239 app_dir.display()
240 )
241 .into());
242 }
243
244 Ok(())
245}
246
247fn prepare_project_dir(project_dir: &Path, force: bool) -> ProjectResult<()> {
248 if !project_dir.exists() {
249 fs::create_dir_all(project_dir)?;
250 return Ok(());
251 }
252
253 if !project_dir.is_dir() {
254 return Err(format!("project path is not a directory: {}", project_dir.display()).into());
255 }
256
257 if force {
258 return Ok(());
259 }
260
261 if fs::read_dir(project_dir)?.next().is_some() {
262 return Err(format!(
263 "project directory already exists and is not empty: {}",
264 project_dir.display()
265 )
266 .into());
267 }
268
269 Ok(())
270}
271
272fn write_file(path: &Path, content: &str) -> ProjectResult<()> {
273 if let Some(parent) = path.parent() {
274 fs::create_dir_all(parent)?;
275 }
276 fs::write(path, content)?;
277 Ok(())
278}
279
280fn validate_project_name(name: &str) -> ProjectResult<()> {
281 let mut chars = name.chars();
282 let Some(first) = chars.next() else {
283 return Err("project name cannot be empty".into());
284 };
285
286 if !first.is_ascii_lowercase() {
287 return Err("project name must start with a lowercase ascii letter".into());
288 }
289
290 if !chars.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_' || ch == '-') {
291 return Err(
292 "project name must contain only lowercase ascii letters, digits, underscores, and hyphens"
293 .into(),
294 );
295 }
296
297 Ok(())
298}
299
300fn validate_app_name(name: &str) -> ProjectResult<()> {
301 const RESERVED: &[&str] = &[
302 "as",
303 "async",
304 "await",
305 "break",
306 "const",
307 "continue",
308 "crate",
309 "dyn",
310 "else",
311 "enum",
312 "extern",
313 "false",
314 "fn",
315 "for",
316 "gen",
317 "if",
318 "impl",
319 "in",
320 "let",
321 "loop",
322 "match",
323 "mod",
324 "move",
325 "mut",
326 "pub",
327 "ref",
328 "return",
329 "self",
330 "static",
331 "struct",
332 "super",
333 "trait",
334 "true",
335 "type",
336 "unsafe",
337 "use",
338 "where",
339 "while",
340 "abstract",
341 "become",
342 "box",
343 "do",
344 "final",
345 "macro",
346 "override",
347 "priv",
348 "typeof",
349 "unsized",
350 "virtual",
351 "yield",
352 "try",
353 "installed_apps",
354 "che_rest",
355 ];
356 if RESERVED.contains(&name) {
357 return Err("app name must be a non-keyword snake_case Rust identifier".into());
358 }
359 let mut chars = name.chars();
360 let Some(first) = chars.next() else {
361 return Err("app name cannot be empty".into());
362 };
363
364 if !first.is_ascii_lowercase() {
365 return Err("app name must start with a lowercase ascii letter".into());
366 }
367
368 if !chars.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_') {
369 return Err(
370 "app name must contain only lowercase ascii letters, digits, and underscores".into(),
371 );
372 }
373
374 Ok(())
375}
376
377fn validate_model_name(name: &str) -> ProjectResult<()> {
378 let mut chars = name.chars();
379 let Some(first) = chars.next() else {
380 return Err("model name cannot be empty".into());
381 };
382
383 if !first.is_ascii_uppercase() {
384 return Err("model name must start with an uppercase ascii letter".into());
385 }
386
387 if !chars.all(|ch| ch.is_ascii_alphanumeric()) {
388 return Err("model name must contain only ascii letters and digits".into());
389 }
390
391 Ok(())
392}
393
394fn cargo_toml_template(name: &str, che_rest_path: &str, che_orm_path: &str) -> String {
395 let che_orm = dependency("che-orm", "0.4.0", che_orm_path);
396 let che_rest = dependency("che-rest", env!("CARGO_PKG_VERSION"), che_rest_path);
397 let backend = if cfg!(feature = "postgres") {
398 "postgres"
399 } else {
400 "sqlite"
401 };
402 format!(
403 r#"[package]
404name = "{name}"
405version = "0.1.0"
406edition = "2024"
407rust-version = "1.89"
408default-run = "{name}"
409publish = false
410
411[workspace]
412
413[features]
414default = ["{backend}"]
415sqlite = ["che-orm/sqlite", "che-rest/sqlite"]
416postgres = ["che-orm/postgres", "che-rest/postgres"]
417
418[dependencies]
419axum = "0.8"
420{che_orm}
421{che_rest}
422serde = {{ version = "1", features = ["derive"] }}
423time = "0.3"
424tokio = {{ version = "1", features = ["macros", "net", "rt-multi-thread", "sync"] }}
425"#
426 )
427}
428
429fn dependency(name: &str, version: &str, path: &str) -> String {
430 if path.is_empty() {
431 format!("{name} = {{ version = \"{version}\", default-features = false }}")
432 } else {
433 format!(
434 "{name} = {{ version = \"{version}\", path = \"{path}\", default-features = false }}"
435 )
436 }
437}
438
439fn app_toml_template() -> &'static str {
440 #[cfg(feature = "postgres")]
441 return r#"[database]
442url = "postgresql://localhost/che_rest"
443max_connections = 8
444
445[server]
446host = "127.0.0.1"
447port = 3000
448api_prefix = "/api"
449"#;
450 #[cfg(feature = "sqlite")]
451 r#"[database]
452url = "sqlite://db.sqlite?mode=rwc"
453max_connections = 64
454
455[server]
456host = "127.0.0.1"
457port = 3000
458api_prefix = "/api"
459"#
460}
461
462fn agents_md_template(with_auth: bool) -> String {
463 let auth_note = if with_auth {
464 "- `che_rest::auth::module()` is installed; session login is available at `/api-session-auth/login/`.\n"
465 } else {
466 "- Authentication is not installed; add `che_rest::auth::module()` before using protected routes.\n"
467 };
468
469 format!(
470 r#"# Project Guide
471
472This is a `che-rest` application. Follow the workflow below instead of creating database tables in
473application startup.
474
475## Canonical Workflow
476
477```bash
478cargo run --bin manage -- schema
479cargo run --bin manage -- makemigrations --name initial
480cargo run --bin manage -- migrate
481cargo run
482```
483
484`makemigrations` compares installed schemas with the compiled migration registry and writes Rust
485migration modules under `src/apps/<app>/migrations/`. Apps expose their compiled
486history through `AppModule::migrations()` and their source directory through
487`migration_path()`. `migrate` collects installed app histories through the built-in
488forward-only executor for the selected backend. Enable exactly one application
489feature, `sqlite` or `postgres`; use `--no-default-features --features postgres`
490when selecting PostgreSQL in a SQLite-default application. All ORM/framework
491dependencies must use the same backend; changing only the URL is insufficient.
492`migrate` is the deployment command that creates or changes database tables;
493`Server::build()` does not alter the schema.
494
495## App Structure
496
497- `src/apps/mod.rs`: installed app registry used by both the server and management commands.
498- `src/apps/<app>/models.rs`: `che-orm` models and database fields.
499- `src/apps/<app>/serializers.rs`: generated ORM2 input/output DTOs.
500- `src/apps/<app>/filters.rs`: list query filters.
501- `src/apps/<app>/views.rs`: typed CRUD viewsets and permissions.
502- `src/bin/manage.rs`: management command entrypoint.
503- `src/apps/<app>/migrations/`: portable application-owned compiled history.
504
505The `single` layout keeps the starter app's files in `src/` and its migration
506history in `src/migrations/`; additional apps still live in `src/apps/<app>/`.
507`createapp` is an alias for `startapp` and works in either layout. Share a
508`pub const APP_NAME: &str` between `AppModule::name()` and model attributes
509`#[orm(app = super::APP_NAME)]`. `Task` in `tasks` uses `tasks_task`.
510
511Register CRUD with `ctx.viewset_with(views::UserViewSet)`. This registers the model
512schema, API metadata, and router together. Do not use only `ctx.route(...)` for a model API.
513
514## Conventions
515
516- Assign server-owned fields in `ViewSet::prepare_create()` or a custom serializer validation flow.
517- Mark server-owned serializer fields read-only so clients cannot supply them.
518- Database operations are async. Use awaited methods and transaction callbacks
519 `|tx| Box::pin(async move {{ ... }})`.
520- Keep serializers database-independent; load relations in the ViewSet queryset.
521- Preserve applied migration identities and checksums. Review generated operations
522 and use explicit data migrations when existing values need conversion.
523- Use `IsAuthenticated` for resources that require the current user.
524- Application events use `AppState::app_channels()` and `AppModule::subscribe()`.
525- `AppState::app_channels()` is for internal application events and is never a public WebSocket channel.
526- Public WebSocket signals use `AppState::signals()` and must be declared with `ModuleContext::signal(...)`; CRUD lifecycle signals are opt-in via `ViewSet::signal_access` and publish `{{ "id": ... }}` payloads.
527- Generated admin uses session cookies and the readable `csrf_token` cookie.
528{auth_note}
529## Synchronization
530
531Generated apps use ordinary CRUD models by default. For local-first models, use
532UUID keys and `#[orm(sync, sync_name = "app.model")]` with shared business fields.
533Register server models with `SchemaSet::server_model` and client models with
534`SchemaSet::client_model`; only clients create shadow tables. Keep stable wire
535names with field-level `#[orm(sync_name = "stable_name")]` when renaming fields.
536
537Implement `SyncViewSet` and install `SyncEndpoints::new(...)` in `ViewSet::configure`.
538Provide a registry containing the model and its dependencies, select scope from
539trusted context, and enforce access with `AccessPolicy`. Sync endpoints require
540authentication. A constant scope with `AllowAll` represents a shared partition,
541not per-user isolation. Ordinary POST/PATCH/PUT/DELETE handle sync delivery;
542there is no separate sync/push route.
543
544Apply compiled migrations for sync infrastructure before serving requests. Writes
545outside the ViewSet adapter must use the configured `SyncServer::database()` or
546`SyncClient::database()` handle, or an explicit sync facade; raw SQL and original
547unconfigured handles bypass capture. Configured server reads authorize scope and
548filter scope/tombstones, including SELECT ASTs and transaction reads.
549
550Clients call `pull()` to download, `flush()` to deliver and `full_load()` explicitly
551for initial loading or expired cursors. Pending operations retry with their original
552IDs. `sync_once()` is a compatibility cycle that can load snapshots automatically.
553Clients target one persistent server history; database replacement/history rewind
554is unsupported. Preserve receipts, tombstones and record revisions when pruning
555journals. Clone one SyncClient to share locks for a client database.
556
557## Verification
558
559After changing a model, run:
560
561```bash
562cargo run --bin manage -- makemigrations
563cargo run --bin manage -- migrate
564cargo check
565```
566
567When adding or changing an endpoint, also run `cargo run --bin manage -- generate-ts` and inspect the
568generated OpenAPI at `/api/openapi.json` while the server is running.
569
570OpenAPI metadata is available from the running server at `/api/openapi.json` by default.
571"#
572 )
573}
574
575fn lib_rs_template() -> &'static str {
576 "pub mod apps;\n"
577}
578
579fn main_rs_template(crate_name: &str) -> String {
580 format!(
581 r#"use che_rest::{{AppState, Server}};
582
583#[tokio::main]
584async fn main() -> Result<(), Box<dyn std::error::Error>> {{
585 let state = AppState::from_config_file("app.toml").await?;
586 let server_config = state.config.server.clone();
587 let app = Server::new(state)
588 .install({crate_name}::apps::installed_apps())
589 .api_prefix(&server_config.api_prefix)
590 .build()
591 .await?;
592
593 let address = format!("{{}}:{{}}", server_config.host, server_config.port);
594 let listener = tokio::net::TcpListener::bind(&address).await?;
595 axum::serve(listener, app).await?;
596
597 Ok(())
598}}
599"#
600 )
601}
602
603fn manage_rs_template(crate_name: &str) -> String {
604 format!(
605 r#"use che_rest::Management;
606
607#[tokio::main]
608async fn main() -> Result<(), Box<dyn std::error::Error>> {{
609 Management::new({crate_name}::apps::installed_apps())
610 .project_root(env!("CARGO_MANIFEST_DIR"))
611 .run()
612 .await
613}}
614"#
615 )
616}
617
618fn apps_mod_template(with_auth: bool) -> String {
619 let auth_module = if with_auth {
620 "\n .add(che_rest::auth::module())"
621 } else {
622 ""
623 };
624
625 format!(
626 r#"{APP_MODULES_MARKER}
627
628use che_rest::InstalledApps;
629
630pub fn installed_apps() -> InstalledApps {{
631 InstalledApps::new(){auth_module}
632 {APP_INSTALL_MARKER}
633}}
634"#
635 )
636}
637
638fn register_app(apps_mod_path: &Path, app_name: &str) -> ProjectResult<()> {
639 let content = fs::read_to_string(apps_mod_path).map_err(|error| {
640 format!(
641 "could not read {}; create it or register `pub mod {app_name};` manually: {error}",
642 apps_mod_path.display()
643 )
644 })?;
645
646 if !content.contains(APP_MODULES_MARKER) || !content.contains(APP_INSTALL_MARKER) {
647 return Err(format!(
648 "created app files, but {} has no che-rest startapp markers; add `pub mod {app_name};` and `.add({app_name}::module())` manually",
649 apps_mod_path.display()
650 )
651 .into());
652 }
653
654 let module_line = format!("pub mod {app_name};");
655 let install_line = format!(" .add({app_name}::module())");
656 let with_module = if content.contains(&module_line) {
657 content
658 } else {
659 content.replace(
660 APP_MODULES_MARKER,
661 &format!("{APP_MODULES_MARKER}\n{module_line}"),
662 )
663 };
664 let with_install = if with_module.contains(&install_line) {
665 with_module
666 } else {
667 with_module.replace(
668 APP_INSTALL_MARKER,
669 &format!("{install_line}\n {APP_INSTALL_MARKER}"),
670 )
671 };
672
673 fs::write(apps_mod_path, with_install)?;
674 Ok(())
675}
676
677fn default_model_name(app_name: &str) -> String {
678 let base = app_name.strip_suffix("app").unwrap_or(app_name);
679 singular_model_name(base)
680}
681
682fn singular_model_name(name: &str) -> String {
683 let singular = name.strip_suffix('s').unwrap_or(name);
684 to_pascal_case(singular)
685}
686
687fn to_pascal_case(value: &str) -> String {
688 value
689 .split('_')
690 .filter(|part| !part.is_empty())
691 .map(|part| {
692 let mut chars = part.chars();
693 match chars.next() {
694 Some(first) => first.to_ascii_uppercase().to_string() + chars.as_str(),
695 None => String::new(),
696 }
697 })
698 .collect()
699}
700
701fn to_snake_case(value: &str) -> String {
702 let mut output = String::new();
703 for (index, ch) in value.chars().enumerate() {
704 if ch.is_ascii_uppercase() {
705 if index > 0 {
706 output.push('_');
707 }
708 output.push(ch.to_ascii_lowercase());
709 } else {
710 output.push(ch);
711 }
712 }
713 output
714}
715
716fn model_blocks(models: &[String]) -> String {
717 models
718 .iter()
719 .map(|model| {
720 format!(
721 r#"#[derive(Debug, che_orm::Model)]
722#[orm(app = super::APP_NAME)]
723pub struct {model} {{
724 #[orm(primary_key)]
725 pub id: i64,
726 pub name: String,
727 #[orm(auto_now_add)]
728 pub created_at: OffsetDateTime,
729 #[orm(auto_now)]
730 pub updated_at: OffsetDateTime,
731}}
732"#
733 )
734 })
735 .collect::<Vec<_>>()
736 .join("\n")
737}
738
739fn models_rs_template(models: &[String]) -> String {
740 format!("use time::OffsetDateTime;\n\n{}", model_blocks(models))
741}
742
743fn serializers_rs_template(models: &[String]) -> String {
744 let imports = models.join(", ");
745 let blocks = models
746 .iter()
747 .map(|model| {
748 format!(
749 r#"#[derive(che_orm::ModelSerializer)]
750#[serializer(model = {model})]
751pub struct {model}Serializer {{
752 #[serializer(read_only)]
753 pub id: i64,
754 pub name: String,
755 #[serializer(read_only)]
756 pub created_at: time::OffsetDateTime,
757 #[serializer(read_only)]
758 pub updated_at: time::OffsetDateTime,
759}}
760"#
761 )
762 })
763 .collect::<Vec<_>>()
764 .join("\n");
765 format!("use super::models::{{{imports}}};\n\n{blocks}")
766}
767
768fn filters_rs_template(models: &[String]) -> String {
769 let imports = models.join(", ");
770 let blocks = models
771 .iter()
772 .map(|model| {
773 format!(
774 r#"#[derive(Clone, Copy, Default)]
775pub struct {model}FilterSet;
776
777static {upper}_FILTERS: &[Filter<{model}>] = &[
778 Filter::exact({model}::ID),
779 Filter::contains({model}::NAME),
780 Filter::exact({model}::CREATED_AT),
781 Filter::exact({model}::UPDATED_AT),
782];
783
784impl FilterSetSpec for {model}FilterSet {{
785 type Model = {model};
786
787 fn filters(&self) -> &'static [Filter<{model}>] {{
788 {upper}_FILTERS
789 }}
790}}
791"#,
792 upper = to_snake_case(model).to_ascii_uppercase()
793 )
794 })
795 .collect::<Vec<_>>()
796 .join("\n");
797 format!(
798 "use che_rest::{{Filter, FilterSetSpec}};\n\nuse super::models::{{{imports}}};\n\n{blocks}"
799 )
800}
801
802fn views_rs_template(models: &[String]) -> String {
803 let model_imports = models.join(", ");
804 let filter_imports = models
805 .iter()
806 .map(|model| format!("{model}FilterSet"))
807 .collect::<Vec<_>>()
808 .join(", ");
809 let serializer_imports = models
810 .iter()
811 .map(|model| format!("{model}Serializer"))
812 .collect::<Vec<_>>()
813 .join(", ");
814 let blocks = models
815 .iter()
816 .map(|model| {
817 let path = to_snake_case(model);
818 format!(
819 r#"#[derive(Clone, Copy, Default)]
820pub struct {model}ViewSet;
821
822impl ViewSet for {model}ViewSet {{
823 type Model = {model};
824 type Serializer = {model}Serializer;
825 type ListSerializer = Self::Serializer;
826 type QuerySet = che_orm::DatabaseQuery<{model}>;
827 type FilterSet = {model}FilterSet;
828 type Permission = AllowAny;
829
830 fn get_queryset(&self) -> Self::QuerySet {{
831 che_orm::DatabaseQuery::new({model}::query())
832 }}
833
834 fn path(&self) -> &'static str {{
835 "/{path}"
836 }}
837}}
838"#
839 )
840 })
841 .collect::<Vec<_>>()
842 .join("\n");
843 format!(
844 "use che_rest::{{AllowAny, Model, ViewSet}};\n\nuse super::{{\n filters::{{{filter_imports}}},\n models::{{{model_imports}}},\n serializers::{{{serializer_imports}}},\n}};\n\n{blocks}"
845 )
846}
847
848fn app_mod_template(app_name: &str, models: &[String]) -> String {
849 app_module_template(app_name, models, &format!("src/apps/{app_name}/migrations"))
850}
851
852fn app_module_template(app_name: &str, models: &[String], migration_path: &str) -> String {
853 let module_type = format!("{}Module", to_pascal_case(app_name));
854 let schema_models = models
855 .iter()
856 .map(|model| format!(".model::<models::{model}>()"))
857 .collect::<String>();
858 let viewsets = models
859 .iter()
860 .map(|model| format!(" context.viewset_with(views::{model}ViewSet);"))
861 .collect::<Vec<_>>()
862 .join("\n");
863
864 format!(
865 r#"pub mod filters;
866pub mod models;
867pub mod migrations;
868pub mod serializers;
869pub mod views;
870
871use che_rest::{{AppModule, ModuleContext}};
872
873pub const APP_NAME: &str = "{app_name}";
874
875pub fn module() -> {module_type} {{
876 {module_type}
877}}
878
879pub struct {module_type};
880
881impl AppModule for {module_type} {{
882 fn migrations(&self) -> Vec<che_orm::Migration> {{
883 migrations::all()
884 }}
885
886 fn migration_path(&self) -> Option<&'static str> {{
887 Some(concat!(env!("CARGO_MANIFEST_DIR"), "/{migration_path}"))
888 }}
889 fn name(&self) -> &'static str {{
890 APP_NAME
891 }}
892
893 fn schema(&self) -> che_orm::SchemaSet {{
894 che_orm::SchemaSet::new(){schema_models}
895 }}
896
897 fn init(&self, context: &mut ModuleContext) {{
898{viewsets}
899 }}
900}}
901"#
902 )
903}
904
905#[cfg(all(test, feature = "sqlite"))]
906mod tests {
907 use std::time::{SystemTime, UNIX_EPOCH};
908
909 use super::{
910 ProjectLayout, StartAppOptions, StartProjectOptions, startapp, startproject,
911 startproject_with_layout,
912 };
913
914 fn temp_dir(name: &str) -> std::path::PathBuf {
915 let suffix = SystemTime::now()
916 .duration_since(UNIX_EPOCH)
917 .unwrap()
918 .as_nanos();
919 std::env::temp_dir().join(format!("che_rest_{name}_{suffix}"))
920 }
921
922 #[test]
923 fn startproject_creates_manage_project() {
924 let out = temp_dir("startproject");
925 startproject(StartProjectOptions {
926 name: "todo_api".into(),
927 out: out.clone(),
928 che_rest_path: "../che-rest".into(),
929 che_orm_path: "../che-orm".into(),
930 with_auth: true,
931 force: false,
932 })
933 .unwrap();
934
935 let project = out.join("todo_api");
936 assert!(project.join("src/bin/manage.rs").exists());
937 assert!(!project.join("src/migrations").exists());
938 assert!(
939 std::fs::read_to_string(project.join("src/bin/manage.rs"))
940 .unwrap()
941 .contains(".project_root(env!(\"CARGO_MANIFEST_DIR\"))")
942 );
943 let apps_mod = std::fs::read_to_string(project.join("src/apps/mod.rs")).unwrap();
944 assert!(apps_mod.contains("che_rest::auth::module()"));
945 assert!(apps_mod.contains("che-rest:startapp modules"));
946 assert!(apps_mod.contains("che-rest:startapp installed apps"));
947 let manifest: toml::Value =
948 toml::from_str(&std::fs::read_to_string(project.join("Cargo.toml")).unwrap()).unwrap();
949 let framework: toml::Value = toml::from_str(include_str!("../Cargo.toml")).unwrap();
950 assert_eq!(
951 manifest["dependencies"]["che-rest"]["version"].as_str(),
952 Some(env!("CARGO_PKG_VERSION"))
953 );
954 assert_eq!(
955 manifest["dependencies"]["che-orm"]["version"],
956 framework["dependencies"]["che-orm"]["version"]
957 );
958 assert_eq!(manifest["package"]["rust-version"].as_str(), Some("1.89"));
959 let guide = std::fs::read_to_string(project.join("AGENTS.md")).unwrap();
960 assert!(guide.contains("SyncEndpoints::new"));
961 assert!(guide.contains("database replacement/history rewind"));
962
963 let _ = std::fs::remove_dir_all(out);
964 }
965
966 #[test]
967 fn startapp_creates_files_and_registers_module() {
968 let out = temp_dir("startapp");
969 startproject(StartProjectOptions {
970 name: "todo_api".into(),
971 out: out.clone(),
972 che_rest_path: "../che-rest".into(),
973 che_orm_path: "../che-orm".into(),
974 with_auth: false,
975 force: false,
976 })
977 .unwrap();
978 let project = out.join("todo_api");
979
980 startapp(StartAppOptions {
981 name: "tasks".into(),
982 models: vec!["Task".into(), "Comment".into()],
983 root: project.clone(),
984 force: false,
985 })
986 .unwrap();
987
988 assert!(project.join("src/apps/tasks/models.rs").exists());
989 let apps_mod = std::fs::read_to_string(project.join("src/apps/mod.rs")).unwrap();
990 assert!(apps_mod.contains("pub mod tasks;"));
991 assert!(apps_mod.contains(".add(tasks::module())"));
992 let app_mod = std::fs::read_to_string(project.join("src/apps/tasks/mod.rs")).unwrap();
993 assert!(app_mod.contains("pub mod migrations;"));
994 assert!(app_mod.contains("fn migration_path"));
995 assert!(project.join("src/apps/tasks/migrations/mod.rs").exists());
996 let models = std::fs::read_to_string(project.join("src/apps/tasks/models.rs")).unwrap();
997 assert!(models.contains("pub struct Task"));
998 assert!(models.contains("pub struct Comment"));
999 assert!(models.contains("#[orm(app = super::APP_NAME)]"));
1000 assert!(app_mod.contains("pub const APP_NAME: &str = \"tasks\";"));
1001
1002 let _ = std::fs::remove_dir_all(out);
1003 }
1004
1005 #[test]
1006 fn startapp_defaults_model_from_app_name() {
1007 let out = temp_dir("startapp_default");
1008 startproject(StartProjectOptions {
1009 name: "todo_api".into(),
1010 out: out.clone(),
1011 che_rest_path: "../che-rest".into(),
1012 che_orm_path: "../che-orm".into(),
1013 with_auth: false,
1014 force: false,
1015 })
1016 .unwrap();
1017 let project = out.join("todo_api");
1018
1019 startapp(StartAppOptions {
1020 name: "taskapp".into(),
1021 models: vec![],
1022 root: project.clone(),
1023 force: false,
1024 })
1025 .unwrap();
1026
1027 let models = std::fs::read_to_string(project.join("src/apps/taskapp/models.rs")).unwrap();
1028 assert!(models.contains("pub struct Task"));
1029
1030 let _ = std::fs::remove_dir_all(out);
1031 }
1032
1033 #[test]
1034 fn project_layouts_share_app_names_and_start_without_migrations() {
1035 for layout in [ProjectLayout::Single, ProjectLayout::Modular] {
1036 let out = temp_dir("layouts");
1037 startproject_with_layout(
1038 StartProjectOptions {
1039 name: "layout_api".into(),
1040 out: out.clone(),
1041 che_rest_path: "../che-rest".into(),
1042 che_orm_path: "../che-orm".into(),
1043 with_auth: true,
1044 force: false,
1045 },
1046 layout,
1047 )
1048 .unwrap();
1049 let root = out.join("layout_api");
1050 let (app, path) = match layout {
1051 ProjectLayout::Single => ("src/lib.rs", "src"),
1052 ProjectLayout::Modular => ("src/apps/tasks/mod.rs", "src/apps/tasks"),
1053 };
1054 let module = std::fs::read_to_string(root.join(app)).unwrap();
1055 assert!(module.contains("pub const APP_NAME: &str = \"tasks\";"));
1056 let models = std::fs::read_to_string(root.join(path).join("models.rs")).unwrap();
1057 assert!(models.contains("#[orm(app = super::APP_NAME)]"));
1058 let history = root.join(path).join("migrations");
1059 assert_eq!(std::fs::read_dir(history).unwrap().count(), 1);
1060 startapp(StartAppOptions {
1061 name: "blog".into(),
1062 models: vec!["Post".into()],
1063 root: root.clone(),
1064 force: false,
1065 })
1066 .unwrap();
1067 assert!(
1068 std::fs::read_to_string(root.join("src/apps/mod.rs"))
1069 .unwrap()
1070 .contains(".add(blog::module())")
1071 );
1072 std::fs::remove_dir_all(out).unwrap();
1073 }
1074 }
1075
1076 #[test]
1077 #[ignore = "builds a generated downstream project and executes its migration CLI"]
1078 fn generated_project_builds_and_migrates() {
1079 let suffix = SystemTime::now()
1080 .duration_since(UNIX_EPOCH)
1081 .unwrap()
1082 .as_nanos();
1083 let out = std::env::temp_dir()
1084 .join("opencode")
1085 .join(format!("che_rest_template_{suffix}"));
1086 let framework = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
1087 startproject(StartProjectOptions {
1088 name: "template_smoke".into(),
1089 out: out.clone(),
1090 che_rest_path: framework.display().to_string(),
1091 che_orm_path: framework
1092 .join("../che-orm")
1093 .canonicalize()
1094 .unwrap()
1095 .display()
1096 .to_string(),
1097 with_auth: true,
1098 force: false,
1099 })
1100 .unwrap();
1101 let project = out.join("template_smoke");
1102 startapp(StartAppOptions {
1103 name: "tasks".into(),
1104 models: vec!["Task".into(), "Comment".into()],
1105 root: project.clone(),
1106 force: false,
1107 })
1108 .unwrap();
1109 let run = |args: &[&str]| {
1110 let output = std::process::Command::new(env!("CARGO"))
1111 .args(args)
1112 .current_dir(&project)
1113 .env("CARGO_TARGET_DIR", framework.join("target"))
1114 .output()
1115 .unwrap();
1116 assert!(
1117 output.status.success(),
1118 "cargo {args:?} failed in {}\n{}\n{}",
1119 project.display(),
1120 String::from_utf8_lossy(&output.stdout),
1121 String::from_utf8_lossy(&output.stderr)
1122 );
1123 String::from_utf8(output.stdout).unwrap()
1124 };
1125 run(&["check", "--all-targets"]);
1126 let schema = run(&["run", "--bin", "manage", "--", "schema"]);
1127 assert!(schema.contains("tasks_task"));
1128 run(&[
1129 "run",
1130 "--bin",
1131 "manage",
1132 "--",
1133 "makemigrations",
1134 "--name",
1135 "initial",
1136 ]);
1137 assert!(
1138 project
1139 .join("src/apps/tasks/migrations/m0001_initial.rs")
1140 .exists()
1141 );
1142 run(&["run", "--bin", "manage", "--", "migrate"]);
1143 run(&["run", "--bin", "manage", "--", "migrate"]);
1144 let status = run(&["run", "--bin", "manage", "--", "migrate", "status"]);
1145 assert!(status.contains("tasks"), "{status}");
1146 run(&["run", "--bin", "manage", "--", "makemigrations", "--check"]);
1147 let models_path = project.join("src/apps/tasks/models.rs");
1148 let models = std::fs::read_to_string(&models_path).unwrap();
1149 std::fs::write(
1150 &models_path,
1151 models.replace(
1152 "pub name: String,",
1153 "pub name: String,\n pub detail: Option<String>,",
1154 ),
1155 )
1156 .unwrap();
1157 run(&[
1158 "run",
1159 "--bin",
1160 "manage",
1161 "--",
1162 "makemigrations",
1163 "--name",
1164 "detail",
1165 ]);
1166 assert!(
1167 project
1168 .join("src/apps/tasks/migrations/m0002_detail.rs")
1169 .exists()
1170 );
1171 run(&["run", "--bin", "manage", "--", "migrate"]);
1172 run(&[
1173 "run",
1174 "--bin",
1175 "manage",
1176 "--",
1177 "makemigrations",
1178 "tasks",
1179 "--check",
1180 ]);
1181
1182 let destination = out.join("transferred_app");
1185 startproject(StartProjectOptions {
1186 name: "transferred_app".into(),
1187 out: out.clone(),
1188 che_rest_path: framework.display().to_string(),
1189 che_orm_path: framework
1190 .join("../che-orm")
1191 .canonicalize()
1192 .unwrap()
1193 .display()
1194 .to_string(),
1195 with_auth: true,
1196 force: false,
1197 })
1198 .unwrap();
1199 fn copy_tree(from: &std::path::Path, to: &std::path::Path) {
1200 std::fs::create_dir_all(to).unwrap();
1201 for entry in std::fs::read_dir(from).unwrap() {
1202 let entry = entry.unwrap();
1203 let target = to.join(entry.file_name());
1204 if entry.file_type().unwrap().is_dir() {
1205 copy_tree(&entry.path(), &target);
1206 } else {
1207 std::fs::copy(entry.path(), target).unwrap();
1208 }
1209 }
1210 }
1211 copy_tree(
1212 &project.join("src/apps/tasks"),
1213 &destination.join("src/apps/tasks"),
1214 );
1215 super::register_app(&destination.join("src/apps/mod.rs"), "tasks").unwrap();
1216 let output = std::process::Command::new(env!("CARGO"))
1217 .args(["run", "--bin", "manage", "--", "migrate"])
1218 .current_dir(&destination)
1219 .env("CARGO_TARGET_DIR", framework.join("target"))
1220 .output()
1221 .unwrap();
1222 assert!(
1223 output.status.success(),
1224 "{}",
1225 String::from_utf8_lossy(&output.stderr)
1226 );
1227 let output = std::process::Command::new(env!("CARGO"))
1228 .args(["run", "--bin", "manage", "--", "makemigrations", "--check"])
1229 .current_dir(&destination)
1230 .env("CARGO_TARGET_DIR", framework.join("target"))
1231 .output()
1232 .unwrap();
1233 assert!(
1234 output.status.success(),
1235 "{}",
1236 String::from_utf8_lossy(&output.stderr)
1237 );
1238 std::fs::remove_dir_all(out).unwrap();
1239 }
1240}