caelix-cli 0.0.3

Command line generator for Caelix applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
use std::{
    env, fmt, fs, io,
    path::{Path, PathBuf},
};

use clap::{Args, Parser, Subcommand};
use heck::{ToKebabCase, ToPascalCase, ToSnakeCase};

pub type Result<T> = std::result::Result<T, CliError>;

#[derive(Debug)]
pub enum CliError {
    Io { path: PathBuf, source: io::Error },
    AlreadyExists(PathBuf),
    InvalidName(String),
}

impl fmt::Display for CliError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
            Self::AlreadyExists(path) => {
                write!(
                    f,
                    "{} already exists; refusing to overwrite",
                    path.display()
                )
            }
            Self::InvalidName(name) => write!(f, "invalid project or feature name `{name}`"),
        }
    }
}

impl std::error::Error for CliError {}

#[derive(Parser, Debug)]
#[command(
    name = "caelix",
    version,
    about = "Generate Caelix applications and features"
)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand, Debug)]
enum Command {
    New(NewArgs),
    #[command(alias = "g")]
    Generate(GenerateArgs),
}

#[derive(Args, Debug)]
struct NewArgs {
    name: String,
}

#[derive(Args, Debug)]
struct GenerateArgs {
    #[command(subcommand)]
    kind: GenerateKind,
}

#[derive(Subcommand, Debug)]
enum GenerateKind {
    Service(NameArgs),
    Controller(NameArgs),
    Module(NameArgs),
}

#[derive(Args, Debug)]
struct NameArgs {
    name: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FeatureName {
    raw: String,
    module_name: String,
    route_path: String,
    type_prefix: String,
}

impl FeatureName {
    pub fn parse(name: impl Into<String>) -> Result<Self> {
        let raw = name.into();
        let trimmed = raw.trim();
        if trimmed.is_empty() || trimmed.contains(['/', '\\']) {
            return Err(CliError::InvalidName(raw));
        }

        let module_name = trimmed.to_snake_case();
        let route_path = trimmed.to_kebab_case();
        let type_prefix = trimmed.to_pascal_case();

        if module_name.is_empty()
            || route_path.is_empty()
            || type_prefix.is_empty()
            || module_name
                .chars()
                .next()
                .is_some_and(|ch| ch.is_ascii_digit())
        {
            return Err(CliError::InvalidName(trimmed.to_string()));
        }

        Ok(Self {
            raw: trimmed.to_string(),
            module_name,
            route_path,
            type_prefix,
        })
    }

    pub fn module_name(&self) -> &str {
        &self.module_name
    }

    pub fn route_path(&self) -> &str {
        &self.route_path
    }

    pub fn service_type(&self) -> String {
        format!("{}Service", self.type_prefix)
    }

    pub fn controller_type(&self) -> String {
        format!("{}Controller", self.type_prefix)
    }

    pub fn module_type(&self) -> String {
        format!("{}Module", self.type_prefix)
    }
}

pub fn run_from_env() -> Result<String> {
    let cwd = env::current_dir().map_err(|source| CliError::Io {
        path: PathBuf::from("."),
        source,
    })?;
    run_from(env::args_os(), cwd)
}

pub fn run_from<I, T>(args: I, cwd: impl AsRef<Path>) -> Result<String>
where
    I: IntoIterator<Item = T>,
    T: Into<std::ffi::OsString> + Clone,
{
    let cli = Cli::parse_from(args);
    run(cli, cwd.as_ref())
}

fn run(cli: Cli, cwd: &Path) -> Result<String> {
    match cli.command {
        Command::New(args) => generate_new(args, cwd),
        Command::Generate(args) => match args.kind {
            GenerateKind::Service(args) => generate_service(&FeatureName::parse(args.name)?, cwd),
            GenerateKind::Controller(args) => {
                generate_controller(&FeatureName::parse(args.name)?, cwd)
            }
            GenerateKind::Module(args) => generate_module(&FeatureName::parse(args.name)?, cwd),
        },
    }
}

fn generate_new(args: NewArgs, cwd: &Path) -> Result<String> {
    let target_dir = cwd.join(&args.name);
    ensure_missing(&target_dir)?;

    let package_name = package_name_for_path(&target_dir, &args.name)?;
    let crate_name = package_name.to_snake_case();

    fs::create_dir_all(target_dir.join("src")).map_err(|source| CliError::Io {
        path: target_dir.join("src"),
        source,
    })?;

    let cargo_toml = render_app_cargo_toml(&package_name);
    create_file(target_dir.join("Cargo.toml"), &cargo_toml)?;
    create_file(target_dir.join("AGENTS.md"), render_agents_md())?;
    create_file(target_dir.join("src/main.rs"), &render_main_rs(&crate_name))?;
    create_file(target_dir.join("src/lib.rs"), render_lib_rs())?;
    create_file(target_dir.join("src/app.rs"), render_app_rs())?;

    Ok(format!(
        "Created Caelix application `{}` in {}\n\nNext steps:\n- cd {}\n- cargo run\n",
        package_name,
        target_dir.display(),
        target_dir.display()
    ))
}

fn generate_service(feature: &FeatureName, cwd: &Path) -> Result<String> {
    let feature_dir = src_dir(cwd).join(feature.module_name());
    let service_path = feature_dir.join("service.rs");
    let mod_path = feature_dir.join("mod.rs");

    ensure_missing(&service_path)?;
    fs::create_dir_all(&feature_dir).map_err(|source| CliError::Io {
        path: feature_dir.clone(),
        source,
    })?;
    create_file(&service_path, &render_service(feature))?;

    let mut created = vec![service_path];
    if !mod_path.exists() {
        create_file(
            &mod_path,
            &render_feature_mod(feature, FeatureModKind::Service),
        )?;
        created.push(mod_path);
    }

    Ok(format!(
        "{}\n\n{}",
        created_files(&created),
        service_instructions(feature)
    ))
}

fn generate_controller(feature: &FeatureName, cwd: &Path) -> Result<String> {
    let feature_dir = src_dir(cwd).join(feature.module_name());
    let service_path = feature_dir.join("service.rs");
    let controller_path = feature_dir.join("controller.rs");
    let mod_path = feature_dir.join("mod.rs");
    let has_service = service_path.exists();

    ensure_missing(&controller_path)?;
    fs::create_dir_all(&feature_dir).map_err(|source| CliError::Io {
        path: feature_dir.clone(),
        source,
    })?;
    create_file(&controller_path, &render_controller(feature, has_service))?;

    let mut created = vec![controller_path];
    if !mod_path.exists() {
        let kind = if has_service {
            FeatureModKind::ControllerWithService
        } else {
            FeatureModKind::Controller
        };
        create_file(&mod_path, &render_feature_mod(feature, kind))?;
        created.push(mod_path);
    }

    let mut output = format!(
        "{}\n\n{}",
        created_files(&created),
        controller_instructions(feature, has_service)
    );
    if !has_service {
        output.push_str(&format!(
            "\n\nNote: src/{}/service.rs was not found, so {} was generated without a {} dependency.\n",
            feature.module_name(),
            feature.controller_type(),
            feature.service_type()
        ));
    }
    Ok(output)
}

fn generate_module(feature: &FeatureName, cwd: &Path) -> Result<String> {
    let feature_dir = src_dir(cwd).join(feature.module_name());
    let mod_path = feature_dir.join("mod.rs");
    let service_path = feature_dir.join("service.rs");
    let controller_path = feature_dir.join("controller.rs");

    ensure_missing(&mod_path)?;
    ensure_missing(&service_path)?;
    ensure_missing(&controller_path)?;

    fs::create_dir_all(&feature_dir).map_err(|source| CliError::Io {
        path: feature_dir.clone(),
        source,
    })?;
    create_file(&mod_path, &render_feature_module(feature))?;
    create_file(&service_path, &render_service(feature))?;
    create_file(&controller_path, &render_controller(feature, true))?;

    Ok(format!(
        "{}\n\n{}",
        created_files(&[mod_path, service_path, controller_path]),
        module_instructions(feature)
    ))
}

fn src_dir(cwd: &Path) -> PathBuf {
    cwd.join("src")
}

fn package_name_for_path(path: &Path, fallback: &str) -> Result<String> {
    let name = path
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or(fallback)
        .trim();

    if name.is_empty() {
        return Err(CliError::InvalidName(fallback.to_string()));
    }

    Ok(name.to_kebab_case())
}

pub fn render_app_cargo_toml(package_name: &str) -> String {
    format!(
        r#"[package]
name = "{package_name}"
version = "0.0.1"
edition = "2024"

[dependencies]
actix-web = "4.14.0"
caelix = "0.0.2"
serde = {{ version = "1.0.228", features = ["derive"] }}
"#
    )
}

fn render_main_rs(crate_name: &str) -> String {
    format!(
        r#"use caelix::Application;
use {crate_name}::AppModule;

#[caelix::main]
async fn main() -> std::io::Result<()> {{
    Application::new::<AppModule>()
        .await
        .listen("127.0.0.1:8080")
        .await
}}
"#,
        crate_name = crate_name
    )
}

fn render_lib_rs() -> &'static str {
    "pub mod app;\n\npub use app::AppModule;\n"
}

fn render_app_rs() -> &'static str {
    r#"use caelix::{Module, ModuleMetadata};

pub struct AppModule;

impl Module for AppModule {
    fn register() -> ModuleMetadata {
        ModuleMetadata::new()
    }
}
"#
}

fn render_agents_md() -> &'static str {
    r#"# Agent Instructions

This is a Caelix application. Use this file as the quick working reference when changing generated app code.

For fuller documentation, refer to https://ohanronnie.github.io/caelix/.

## App Structure

- `src/main.rs` starts the Actix runtime with `Application::new::<AppModule>()`.
- `src/lib.rs` exports the root `AppModule` and should declare feature modules with `pub mod feature_name;`.
- `src/app.rs` owns the root `AppModule`.
- Feature folders usually contain `mod.rs`, `service.rs`, and `controller.rs`.
- Prefer the Caelix CLI for new framework files: `caelix g module name`, `caelix g service name`, and `caelix g controller name`.

## Registration Model

Caelix uses explicit module metadata. Do not rely on filesystem discovery or hidden auto-registration.

- A module implements `Module` and returns `ModuleMetadata`.
- Add generated feature modules to `src/lib.rs`.
- Import feature modules in `src/app.rs`.
- Add `.import::<FeatureModule>()` inside `AppModule::register()`.
- Register services with `.provider::<Service>()`.
- Register controllers with `.controller::<Controller>()`.
- Register async factory values with `.provider_async_factory::<T, _, _>(...)` when construction cannot be expressed as `#[injectable]`.

Example:

```rust
use caelix::{Module, ModuleMetadata};
use crate::users::UsersModule;

pub struct AppModule;

impl Module for AppModule {
    fn register() -> ModuleMetadata {
        ModuleMetadata::new().import::<UsersModule>()
    }
}
```

## Providers And Injection

Prefer `#[injectable]` for services, controllers, guards, and interceptors.

- Injectable fields must be `Arc<T>`.
- `Arc<Logger>` is provided automatically with the struct name as context.
- Unit structs are valid injectables.
- Tuple structs are not supported by `#[injectable]`.
- Manual `Injectable` implementations are acceptable for custom async construction.
- Lifecycle hooks can be implemented on providers: `on_module_init`, `on_bootstrap`, and `on_shutdown`.

Example:

```rust
use std::sync::Arc;
use caelix::{injectable, Logger};

#[injectable]
pub struct UsersService {
    logger: Arc<Logger>,
}
```

## Controllers

Use `#[controller("/base-path")]` on an impl block. Route handlers are async methods.

- Supported route attributes: `#[get]`, `#[post]`, `#[patch]`, `#[put]`, `#[delete]`.
- Supported extractor attributes: `#[param]`, `#[body]`, `#[query]`, `#[user]`.
- Add `#[validate]` to extracted DTOs that implement `validator::Validate`.
- `#[user]` reads from `RequestContext`; missing users become `UnauthorizedException`.

Example:

```rust
use std::sync::Arc;
use caelix::{controller, get, injectable, Result};
use super::UsersService;

#[injectable]
pub struct UsersController {
    service: Arc<UsersService>,
}

#[controller("/users")]
impl UsersController {
    #[get("/{id}")]
    async fn find_one(&self, #[param] id: String) -> Result<String> {
        Ok(self.service.find_one(id).await?)
    }
}
```

## Guards, Interceptors, And Context

- Guards implement `Guard` and return whether a request may continue.
- Interceptors implement `Interceptor` and can wrap handler execution.
- Apply them with `#[use_guard(Type)]` or `#[use_interceptor(Type)]` at controller or method level.
- Controller-level guards/interceptors apply before method-level ones.
- Use `RequestContext` for request method, path, headers, and per-request values such as authenticated users.

## Responses And Errors

Handlers should return values that implement `IntoCaelixResponse`.

- `Result<String>` returns `200 text/plain`.
- `Result<Response<T>>` is the usual JSON response path.
- `Response::Body(value)` returns `200` JSON.
- `Response::WithStatus(status, value)` returns JSON with a custom status.
- `Response::json`, `Response::text`, and `Response::bytes` return explicit raw payloads.
- `Response::no_content()` returns `204`.
- Use Caelix exception types such as `BadRequestException`, `UnauthorizedException`, `ForbiddenException`, `NotFoundException`, and `InternalServerErrorException` for errors.
- Server error messages are intentionally hidden from HTTP responses.

## Cache

Cache support is explicit service-level caching.

- Import `CacheModule` into a module that needs cache support.
- Inject `Arc<Cache>` into services that need cache reads/writes.
- Do not add automatic HTTP response caching.
- If the app needs response caching, implement it with an interceptor that reads from and writes to `Cache`.

## Checks

- Run `cargo test` after code changes when feasible.
- Keep public app code using the `caelix` facade (`use caelix::...`) instead of internal Caelix crate paths.
- When using CLI-generated files, keep the manual registration steps in the command output aligned with `src/lib.rs` and `src/app.rs`.
"#
}

pub fn render_service(feature: &FeatureName) -> String {
    let service = feature.service_type();
    format!(
        r#"use caelix::injectable;

#[injectable]
pub struct {service};

impl {service} {{
    pub fn hello(&self) -> String {{
        "Hello from {service}".to_string()
    }}
}}
"#
    )
}

pub fn render_controller(feature: &FeatureName, has_service: bool) -> String {
    let controller = feature.controller_type();
    let route = feature.route_path();

    if has_service {
        let service = feature.service_type();
        format!(
            r#"use std::sync::Arc;

use caelix::{{controller, get, injectable, Result}};

use super::{service};

#[injectable]
pub struct {controller} {{
    service: Arc<{service}>,
}}

#[controller("/{route}")]
impl {controller} {{
    #[get("")]
    pub async fn hello(&self) -> Result<String> {{
        Ok(self.service.hello())
    }}
}}
"#
        )
    } else {
        format!(
            r#"use caelix::{{controller, get, injectable, Result}};

#[injectable]
pub struct {controller};

#[controller("/{route}")]
impl {controller} {{
    #[get("")]
    pub async fn hello(&self) -> Result<String> {{
        Ok("Hello from {controller}".to_string())
    }}
}}
"#
        )
    }
}

#[derive(Clone, Copy)]
enum FeatureModKind {
    Service,
    Controller,
    ControllerWithService,
}

fn render_feature_mod(feature: &FeatureName, kind: FeatureModKind) -> String {
    let service = feature.service_type();
    let controller = feature.controller_type();

    match kind {
        FeatureModKind::Service => format!(
            r#"pub mod service;

pub use service::{service};
"#
        ),
        FeatureModKind::Controller => format!(
            r#"pub mod controller;

pub use controller::{controller};
"#
        ),
        FeatureModKind::ControllerWithService => format!(
            r#"pub mod controller;
pub mod service;

pub use controller::{controller};
pub use service::{service};
"#
        ),
    }
}

pub fn render_feature_module(feature: &FeatureName) -> String {
    let module = feature.module_type();
    let service = feature.service_type();
    let controller = feature.controller_type();

    format!(
        r#"pub mod controller;
pub mod service;

pub use controller::{controller};
pub use service::{service};

use caelix::{{Module, ModuleMetadata}};

pub struct {module};

impl Module for {module} {{
    fn register() -> ModuleMetadata {{
        ModuleMetadata::new()
            .provider::<{service}>()
            .controller::<{controller}>()
    }}
}}
"#
    )
}

fn service_instructions(feature: &FeatureName) -> String {
    format!(
        r#"Manual registration:
- Ensure `src/{}/mod.rs` contains `pub mod service;` and `pub use service::{};`.
- Add `pub mod {};` to `src/lib.rs` if it is not already declared.
- Add `use crate::{}::{};` to the module that should own the service.
- Add `.provider::<{}>()` inside that module's `register()`."#,
        feature.module_name(),
        feature.service_type(),
        feature.module_name(),
        feature.module_name(),
        feature.service_type(),
        feature.service_type()
    )
}

fn controller_instructions(feature: &FeatureName, has_service: bool) -> String {
    let mut instructions = format!(
        r#"Manual registration:
- Ensure `src/{}/mod.rs` contains `pub mod controller;` and `pub use controller::{};`.
- Add `pub mod {};` to `src/lib.rs` if it is not already declared.
- Add `use crate::{}::{};` to the module that should own the controller.
- Add `.controller::<{}>()` inside that module's `register()`."#,
        feature.module_name(),
        feature.controller_type(),
        feature.module_name(),
        feature.module_name(),
        feature.controller_type(),
        feature.controller_type()
    );

    if has_service {
        instructions.push_str(&format!(
            "\n- Ensure `{}` is registered as a provider in the same module.",
            feature.service_type()
        ));
    }

    instructions
}

fn module_instructions(feature: &FeatureName) -> String {
    format!(
        r#"Manual registration:
- Add `pub mod {};` to `src/lib.rs`.
- Add `use crate::{}::{};` to `src/app.rs`.
- Add `.import::<{}>()` inside `AppModule::register()`."#,
        feature.module_name(),
        feature.module_name(),
        feature.module_type(),
        feature.module_type()
    )
}

fn created_files(paths: &[PathBuf]) -> String {
    let mut output = String::from("Created files:\n");
    for path in paths {
        output.push_str(&format!("- {}\n", path.display()));
    }
    output
}

fn ensure_missing(path: &Path) -> Result<()> {
    if path.exists() {
        Err(CliError::AlreadyExists(path.to_path_buf()))
    } else {
        Ok(())
    }
}

fn create_file(path: impl AsRef<Path>, contents: impl AsRef<str>) -> Result<()> {
    let path = path.as_ref();
    ensure_missing(path)?;
    fs::write(path, contents.as_ref()).map_err(|source| CliError::Io {
        path: path.to_path_buf(),
        source,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn feature_name_converts_to_rust_and_route_names() {
        let feature = FeatureName::parse("auth-session").unwrap();

        assert_eq!(feature.module_name(), "auth_session");
        assert_eq!(feature.route_path(), "auth-session");
        assert_eq!(feature.service_type(), "AuthSessionService");
        assert_eq!(feature.controller_type(), "AuthSessionController");
        assert_eq!(feature.module_type(), "AuthSessionModule");
    }

    #[test]
    fn service_template_uses_injectable_struct() {
        let feature = FeatureName::parse("users").unwrap();
        let rendered = render_service(&feature);

        assert!(rendered.contains("#[injectable]\npub struct UsersService;"));
        assert!(rendered.contains("Hello from UsersService"));
    }

    #[test]
    fn controller_template_omits_service_when_missing() {
        let feature = FeatureName::parse("users").unwrap();
        let rendered = render_controller(&feature, false);

        assert!(rendered.contains("pub struct UsersController;"));
        assert!(!rendered.contains("Arc<UsersService>"));
        assert!(rendered.contains("#[controller(\"/users\")]"));
    }

    #[test]
    fn module_template_registers_provider_and_controller() {
        let feature = FeatureName::parse("users").unwrap();
        let rendered = render_feature_module(&feature);

        assert!(rendered.contains("pub struct UsersModule;"));
        assert!(rendered.contains(".provider::<UsersService>()"));
        assert!(rendered.contains(".controller::<UsersController>()"));
    }
}