armature-cli 0.2.0

CLI tool for Armature framework - scaffolding and development
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
//! Code generation templates for Armature CLI.

use handlebars::Handlebars;
use serde::Serialize;

/// Template registry for code generation.
pub struct TemplateRegistry {
    hbs: Handlebars<'static>,
}

impl TemplateRegistry {
    /// Create a new template registry with all templates registered.
    pub fn new() -> Self {
        let mut hbs = Handlebars::new();
        hbs.set_strict_mode(true);

        // Register all templates
        hbs.register_template_string("controller", CONTROLLER_TEMPLATE)
            .expect("Failed to register controller template");
        hbs.register_template_string("controller_crud", CONTROLLER_CRUD_TEMPLATE)
            .expect("Failed to register controller CRUD template");
        hbs.register_template_string("controller_test", CONTROLLER_TEST_TEMPLATE)
            .expect("Failed to register controller test template");
        hbs.register_template_string("module", MODULE_TEMPLATE)
            .expect("Failed to register module template");
        hbs.register_template_string("middleware", MIDDLEWARE_TEMPLATE)
            .expect("Failed to register middleware template");
        hbs.register_template_string("middleware_test", MIDDLEWARE_TEST_TEMPLATE)
            .expect("Failed to register middleware test template");
        hbs.register_template_string("guard", GUARD_TEMPLATE)
            .expect("Failed to register guard template");
        hbs.register_template_string("guard_test", GUARD_TEST_TEMPLATE)
            .expect("Failed to register guard test template");
        hbs.register_template_string("service", SERVICE_TEMPLATE)
            .expect("Failed to register service template");
        hbs.register_template_string("service_test", SERVICE_TEST_TEMPLATE)
            .expect("Failed to register service test template");
        hbs.register_template_string("main_minimal", MAIN_MINIMAL_TEMPLATE)
            .expect("Failed to register main minimal template");
        hbs.register_template_string("cargo_toml", CARGO_TOML_TEMPLATE)
            .expect("Failed to register Cargo.toml template");
        hbs.register_template_string("env_example", ENV_EXAMPLE_TEMPLATE)
            .expect("Failed to register .env.example template");
        hbs.register_template_string("readme", README_TEMPLATE)
            .expect("Failed to register README template");

        Self { hbs }
    }

    /// Render a template with the given data.
    pub fn render<T: Serialize>(&self, template: &str, data: &T) -> Result<String, String> {
        self.hbs.render(template, data).map_err(|e| e.to_string())
    }
}

impl Default for TemplateRegistry {
    fn default() -> Self {
        Self::new()
    }
}

// =============================================================================
// CONTROLLER TEMPLATES
// =============================================================================

const CONTROLLER_TEMPLATE: &str = r#"//! {{name_pascal}} controller.

use armature::prelude::*;

/// {{name_pascal}} controller handles {{name_snake}} related endpoints.
#[controller("/{{base_path}}")]
#[derive(Default)]
pub struct {{name_pascal}}Controller;

impl {{name_pascal}}Controller {
    /// Get all {{name_snake}}s.
    #[get("/")]
    pub async fn index(&self, _req: HttpRequest) -> Result<HttpResponse, Error> {
        HttpResponse::ok().with_json(&serde_json::json!({
            "message": "List all {{name_snake}}s"
        }))
    }

    /// Get a single {{name_snake}} by ID.
    #[get("/:id")]
    pub async fn show(&self, req: HttpRequest) -> Result<HttpResponse, Error> {
        let id = req.params.get("id").unwrap_or(&"0".to_string()).clone();
        HttpResponse::ok().with_json(&serde_json::json!({
            "message": format!("Get {{name_snake}} with id: {}", id)
        }))
    }
}
"#;

const CONTROLLER_CRUD_TEMPLATE: &str = r#"//! {{name_pascal}} controller with CRUD operations.

use armature::prelude::*;
use serde::{Deserialize, Serialize};

/// {{name_pascal}} data transfer object.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct {{name_pascal}}Dto {
    pub id: Option<u64>,
    pub name: String,
    // Add more fields as needed
}

/// Create {{name_pascal}} request.
#[derive(Debug, Deserialize)]
pub struct Create{{name_pascal}}Request {
    pub name: String,
}

/// Update {{name_pascal}} request.
#[derive(Debug, Deserialize)]
pub struct Update{{name_pascal}}Request {
    pub name: Option<String>,
}

/// {{name_pascal}} controller handles {{name_snake}} CRUD operations.
#[controller("/{{base_path}}")]
#[derive(Default)]
pub struct {{name_pascal}}Controller;

impl {{name_pascal}}Controller {
    /// List all {{name_snake}}s.
    ///
    /// GET /{{base_path}}
    #[get("/")]
    pub async fn index(&self, _req: HttpRequest) -> Result<HttpResponse, Error> {
        // TODO: Implement listing logic
        let items: Vec<{{name_pascal}}Dto> = vec![];
        HttpResponse::ok().with_json(&items)
    }

    /// Get a single {{name_snake}} by ID.
    ///
    /// GET /{{base_path}}/:id
    #[get("/:id")]
    pub async fn show(&self, req: HttpRequest) -> Result<HttpResponse, Error> {
        let id = req.params.get("id")
            .ok_or_else(|| Error::BadRequest("Missing id parameter".to_string()))?;

        // TODO: Implement fetch logic
        let item = {{name_pascal}}Dto {
            id: Some(id.parse().unwrap_or(0)),
            name: "Example".to_string(),
        };

        HttpResponse::ok().with_json(&item)
    }

    /// Create a new {{name_snake}}.
    ///
    /// POST /{{base_path}}
    #[post("/")]
    pub async fn create(&self, req: HttpRequest) -> Result<HttpResponse, Error> {
        let body: Create{{name_pascal}}Request = serde_json::from_slice(&req.body)
            .map_err(|e| Error::BadRequest(format!("Invalid request body: {}", e)))?;

        // TODO: Implement create logic
        let item = {{name_pascal}}Dto {
            id: Some(1),
            name: body.name,
        };

        HttpResponse::created().with_json(&item)
    }

    /// Update an existing {{name_snake}}.
    ///
    /// PUT /{{base_path}}/:id
    #[put("/:id")]
    pub async fn update(&self, req: HttpRequest) -> Result<HttpResponse, Error> {
        let id = req.params.get("id")
            .ok_or_else(|| Error::BadRequest("Missing id parameter".to_string()))?;

        let body: Update{{name_pascal}}Request = serde_json::from_slice(&req.body)
            .map_err(|e| Error::BadRequest(format!("Invalid request body: {}", e)))?;

        // TODO: Implement update logic
        let item = {{name_pascal}}Dto {
            id: Some(id.parse().unwrap_or(0)),
            name: body.name.unwrap_or_else(|| "Updated".to_string()),
        };

        HttpResponse::ok().with_json(&item)
    }

    /// Delete a {{name_snake}}.
    ///
    /// DELETE /{{base_path}}/:id
    #[delete("/:id")]
    pub async fn destroy(&self, req: HttpRequest) -> Result<HttpResponse, Error> {
        let id = req.params.get("id")
            .ok_or_else(|| Error::BadRequest("Missing id parameter".to_string()))?;

        // TODO: Implement delete logic
        let _ = id;

        HttpResponse::no_content()
    }
}
"#;

const CONTROLLER_TEST_TEMPLATE: &str = r#"//! Tests for {{name_pascal}}Controller.

use super::*;

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

    #[tokio::test]
    async fn test_index() {
        let controller = {{name_pascal}}Controller::default();
        let req = HttpRequest::default();

        let response = controller.index(req).await;
        assert!(response.is_ok());
    }

    #[tokio::test]
    async fn test_show() {
        let controller = {{name_pascal}}Controller::default();
        let mut req = HttpRequest::default();
        req.params.insert("id".to_string(), "1".to_string());

        let response = controller.show(req).await;
        assert!(response.is_ok());
    }
}
"#;

// =============================================================================
// MODULE TEMPLATES
// =============================================================================

const MODULE_TEMPLATE: &str = r#"//! {{name_pascal}} module.

use armature::prelude::*;

{{#each controllers}}
mod {{this}};
pub use {{this}}::{{this_pascal}}Controller;
{{/each}}

{{#each providers}}
mod {{this}};
pub use {{this}}::{{this_pascal}}Service;
{{/each}}

/// {{name_pascal}} module bundles related controllers and providers.
#[module(
    controllers: [{{controller_list}}],
    providers: [{{provider_list}}]
)]
#[derive(Default)]
pub struct {{name_pascal}}Module;
"#;

// =============================================================================
// MIDDLEWARE TEMPLATES
// =============================================================================

const MIDDLEWARE_TEMPLATE: &str = r#"//! {{name_pascal}} middleware.

use armature::prelude::*;
use async_trait::async_trait;

/// {{name_pascal}} middleware.
///
/// # Example
///
/// ```rust
/// use armature::prelude::*;
///
/// let middleware = {{name_pascal}}Middleware::new();
/// ```
pub struct {{name_pascal}}Middleware {
    // Add configuration fields here
}

impl {{name_pascal}}Middleware {
    /// Create a new {{name_pascal}}Middleware instance.
    pub fn new() -> Self {
        Self {}
    }
}

impl Default for {{name_pascal}}Middleware {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl Middleware for {{name_pascal}}Middleware {
    async fn handle(&self, req: HttpRequest, next: Next) -> Result<HttpResponse, Error> {
        // Pre-processing: Add logic before the request is handled
        tracing::debug!("{{name_pascal}}Middleware: Processing request to {}", req.path);

        // Call the next middleware/handler
        let response = next(req).await?;

        // Post-processing: Add logic after the response is generated
        tracing::debug!("{{name_pascal}}Middleware: Response status {}", response.status);

        Ok(response)
    }
}
"#;

const MIDDLEWARE_TEST_TEMPLATE: &str = r#"//! Tests for {{name_pascal}}Middleware.

use super::*;

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

    #[tokio::test]
    async fn test_middleware_passes_through() {
        let middleware = {{name_pascal}}Middleware::new();
        let req = HttpRequest::default();

        let next: Next = Box::new(|_req| {
            Box::pin(async { Ok(HttpResponse::ok()) })
        });

        let response = middleware.handle(req, next).await;
        assert!(response.is_ok());
        assert_eq!(response.unwrap().status, 200);
    }
}
"#;

// =============================================================================
// GUARD TEMPLATES
// =============================================================================

const GUARD_TEMPLATE: &str = r#"//! {{name_pascal}} guard.

use armature::prelude::*;
use async_trait::async_trait;

/// {{name_pascal}} guard for route protection.
///
/// # Example
///
/// ```rust
/// use armature::prelude::*;
///
/// let guard = {{name_pascal}}Guard::new();
/// ```
pub struct {{name_pascal}}Guard {
    // Add configuration fields here
}

impl {{name_pascal}}Guard {
    /// Create a new {{name_pascal}}Guard instance.
    pub fn new() -> Self {
        Self {}
    }

    /// Check if the request is authorized.
    fn is_authorized(&self, req: &HttpRequest) -> bool {
        // TODO: Implement authorization logic
        // Example: Check for a valid API key or JWT token
        req.headers.contains_key("authorization")
    }
}

impl Default for {{name_pascal}}Guard {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl Guard for {{name_pascal}}Guard {
    async fn can_activate(&self, req: &HttpRequest) -> Result<bool, Error> {
        if self.is_authorized(req) {
            Ok(true)
        } else {
            Err(Error::Unauthorized("Access denied".to_string()))
        }
    }
}
"#;

const GUARD_TEST_TEMPLATE: &str = r#"//! Tests for {{name_pascal}}Guard.

use super::*;

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

    #[tokio::test]
    async fn test_guard_denies_unauthorized() {
        let guard = {{name_pascal}}Guard::new();
        let req = HttpRequest::default();

        let result = guard.can_activate(&req).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_guard_allows_authorized() {
        let guard = {{name_pascal}}Guard::new();
        let mut req = HttpRequest::default();
        req.headers.insert("authorization".to_string(), "Bearer token".to_string());

        let result = guard.can_activate(&req).await;
        assert!(result.is_ok());
        assert!(result.unwrap());
    }
}
"#;

// =============================================================================
// SERVICE TEMPLATES
// =============================================================================

const SERVICE_TEMPLATE: &str = r#"//! {{name_pascal}} service.

use armature::prelude::*;
use std::sync::Arc;

/// {{name_pascal}} service provides business logic for {{name_snake}} operations.
///
/// # Example
///
/// ```rust
/// use armature::prelude::*;
///
/// let service = {{name_pascal}}Service::new();
/// ```
#[derive(Clone)]
#[injectable]
pub struct {{name_pascal}}Service {
    // Add dependencies here
}

impl {{name_pascal}}Service {
    /// Create a new {{name_pascal}}Service instance.
    pub fn new() -> Self {
        Self {}
    }

    /// Example method - replace with your business logic.
    pub async fn find_all(&self) -> Result<Vec<String>, Error> {
        // TODO: Implement business logic
        Ok(vec![])
    }

    /// Example method - replace with your business logic.
    pub async fn find_by_id(&self, id: u64) -> Result<Option<String>, Error> {
        // TODO: Implement business logic
        let _ = id;
        Ok(None)
    }
}

impl Default for {{name_pascal}}Service {
    fn default() -> Self {
        Self::new()
    }
}
"#;

const SERVICE_TEST_TEMPLATE: &str = r#"//! Tests for {{name_pascal}}Service.

use super::*;

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

    #[tokio::test]
    async fn test_find_all() {
        let service = {{name_pascal}}Service::new();
        let result = service.find_all().await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_find_by_id() {
        let service = {{name_pascal}}Service::new();
        let result = service.find_by_id(1).await;
        assert!(result.is_ok());
    }
}
"#;

// =============================================================================
// PROJECT TEMPLATES
// =============================================================================

const MAIN_MINIMAL_TEMPLATE: &str = r#"//! {{name_pascal}} - Built with Armature Framework

use armature::prelude::*;

mod controllers;

use controllers::health::HealthController;

/// Application module.
#[module(controllers: [HealthController])]
#[derive(Default)]
struct AppModule;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize logging
    tracing_subscriber::fmt::init();

    // Create and run the application
    let app = Application::create::<AppModule>().await;

    let port: u16 = std::env::var("PORT")
        .unwrap_or_else(|_| "3000".to_string())
        .parse()
        .unwrap_or(3000);

    println!("🚀 Server running on http://127.0.0.1:{}", port);

    app.listen(port).await?;

    Ok(())
}
"#;

const CARGO_TOML_TEMPLATE: &str = r#"[package]
name = "{{name_kebab}}"
version = "0.1.0"
edition = "2021"
authors = ["Your Name <your.email@example.com>"]
description = "{{description}}"

[dependencies]
armature = "0.1"
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tracing = "0.1"
tracing-subscriber = "0.3"
async-trait = "0.1"
thiserror = "2.0"

[dev-dependencies]
tokio-test = "0.4"
"#;

const ENV_EXAMPLE_TEMPLATE: &str = r#"# {{name_pascal}} Environment Configuration

# Server
PORT=3000
HOST=127.0.0.1

# Logging
RUST_LOG=info

# Database (if needed)
# DATABASE_URL=postgres://user:password@localhost:5432/{{name_snake}}

# Redis (if needed)
# REDIS_URL=redis://localhost:6379

# JWT (if needed)
# JWT_SECRET=your-secret-key-here
# JWT_EXPIRATION=3600
"#;

const README_TEMPLATE: &str = r#"# {{name_pascal}}

{{description}}

Built with [Armature](https://github.com/pegasusheavy/armature) - A modern Rust web framework.

## Getting Started

### Prerequisites

- Rust 1.75 or later
- Cargo

### Installation

1. Clone the repository
2. Copy `.env.example` to `.env` and configure
3. Run the development server:

```bash
cargo run
```

Or with the Armature CLI:

```bash
armature dev
```

### Development

Generate new code:

```bash
# Generate a controller
armature generate controller users

# Generate a service
armature generate service users

# Generate a complete resource
armature generate resource products --crud
```

### Building for Production

```bash
cargo build --release
```

## Project Structure

```
{{name_kebab}}/
├── src/
│   ├── main.rs           # Application entry point
│   ├── controllers/      # Route handlers
│   ├── services/         # Business logic
│   ├── middleware/       # Request/response middleware
│   └── guards/           # Route guards
├── Cargo.toml
├── .env.example
└── README.md
```

## License

[Your License]
"#;

// =============================================================================
// HELPER FUNCTIONS
// =============================================================================

/// Template data for controller generation.
#[derive(Serialize)]
pub struct ControllerData {
    pub name_pascal: String,
    pub name_snake: String,
    pub name_kebab: String,
    pub base_path: String,
}

/// Template data for module generation.
#[derive(Serialize)]
pub struct ModuleData {
    pub name_pascal: String,
    pub name_snake: String,
    pub controllers: Vec<String>,
    pub providers: Vec<String>,
    pub controller_list: String,
    pub provider_list: String,
}

/// Template data for middleware/guard/service generation.
#[derive(Serialize)]
pub struct ComponentData {
    pub name_pascal: String,
    pub name_snake: String,
    pub name_kebab: String,
}

/// Template data for project generation.
#[derive(Serialize)]
pub struct ProjectData {
    pub name_pascal: String,
    pub name_snake: String,
    pub name_kebab: String,
    pub description: String,
}