# Template Reference Guide

Complete reference for all templates in the complete project generation example.

## Template Variables

All templates support these variables:

| Variable | Default | Description |
|----------|---------|-------------|
| `{{project_name}}` | my-web-service | Project and binary name |
| `{{version}}` | 0.1.0 | Semantic version |
| `{{author}}` | Generated by ggen | Package author |
| `{{port}}` | 3000 | Server port |
| `{{log_level}}` | info | Logging level |
| `{{rust_edition}}` | 2021 | Rust edition |
| `{{api_prefix}}` | /api | API route prefix |
| `{{description}}` | A production-ready... | Package description |

## Template Files

### 1. cargo-toml.tmpl
**Purpose**: Package configuration and dependencies
**Output**: `Cargo.toml`
**Lines**: 25

Generates the package manifest with:
- Package metadata
- Runtime dependencies (actix-web, serde, tokio, etc.)
- Dev dependencies (reqwest, mockito)
- Binary configuration

**Key Variables**:
- `{{project_name}}` - Package name
- `{{version}}` - Package version
- `{{rust_edition}}` - Rust edition (2021)

### 2. main-rs.tmpl
**Purpose**: Application entry point
**Output**: `src/main.rs`
**Lines**: 28

Generates the main server file with:
- HTTP server initialization
- Middleware setup (logging)
- Route configuration
- Health check endpoint

**Key Variables**:
- `{{project_name}}` - Used in logs
- `{{version}}` - Used in logs
- `{{log_level}}` - Default log level
- `{{port}}` - Default server port

### 3. models-mod.tmpl
**Purpose**: Models module definition
**Output**: `src/models/mod.rs`
**Lines**: 5

Exports all model modules:
- `user` module → User, UserId
- `product` module → Product, ProductId

### 4. user-model.tmpl
**Purpose**: User data model
**Output**: `src/models/user.rs`
**Lines**: 65

Generates User model with:
- UUID-based ID
- Name and email fields
- Validation (email format, length)
- Timestamps (created_at, updated_at)
- CreateUserRequest DTO
- Unit tests

**Features**:
- Serde serialization
- Validator integration
- Constructor with UUID generation
- Comprehensive tests

### 5. product-model.tmpl
**Purpose**: Product data model
**Output**: `src/models/product.rs`
**Lines**: 90

Generates Product model with:
- UUID-based ID
- Name, description, price, stock
- Validation (price > 0, stock >= 0)
- Stock checking method
- CreateProductRequest DTO
- Unit tests

**Features**:
- Decimal price handling
- Inventory tracking
- Business logic (is_in_stock)
- Edge case tests

### 6. api-mod.tmpl
**Purpose**: API module definition
**Output**: `src/api/mod.rs`
**Lines**: 5

Exports API components:
- `handlers` module
- `routes` module
- Re-exports configure function

### 7. api-handlers.tmpl
**Purpose**: Request handlers
**Output**: `src/api/handlers.rs`
**Lines**: 110

Generates all API handlers:
- `list_users` - GET all users
- `get_user` - GET user by ID
- `create_user` - POST new user
- `list_products` - GET all products
- `get_product` - GET product by ID
- `create_product` - POST new product

**Features**:
- In-memory storage (AppState)
- Request validation
- Error responses (400, 404)
- JSON serialization
- Logging

### 8. api-routes.tmpl
**Purpose**: Route configuration
**Output**: `src/api/routes.rs`
**Lines**: 22

Configures all API routes:
```
{{api_prefix}}/users
  GET  - list_users
  POST - create_user
{{api_prefix}}/users/{id}
  GET  - get_user
{{api_prefix}}/products
  GET  - list_products
  POST - create_product
{{api_prefix}}/products/{id}
  GET  - get_product
```

**Key Variables**:
- `{{api_prefix}}` - API base path (default: /api)

### 9. config-mod.tmpl
**Purpose**: Config module definition
**Output**: `src/config/mod.rs`
**Lines**: 3

Exports Settings struct from settings module.

### 10. config-settings.tmpl
**Purpose**: Application settings
**Output**: `src/config/settings.rs`
**Lines**: 55

Generates Settings struct with:
- Port (from PORT env var or default)
- Log level (from LOG_LEVEL env var)
- Environment (development/production)
- Helper methods (is_production, is_development)
- Unit tests

**Key Variables**:
- `{{port}}` - Default port
- `{{log_level}}` - Default log level

### 11. integration-test.tmpl
**Purpose**: Integration tests
**Output**: `tests/integration_test.rs`
**Lines**: 200

Generates comprehensive test suite:
- Health check test
- User CRUD tests
- Product CRUD tests
- Validation tests
- Error handling tests

**Test Coverage**:
- List empty collections
- Create entities
- Get by ID
- Validation errors (email, price)
- Not found errors (404)

**Key Variables**:
- `{{project_name}}` - Used in imports
- `{{api_prefix}}` - API route prefix

## Template Usage Examples

### Basic Generation
```bash
./generate-project.sh generate
```

Variables used:
- project_name: my-web-service
- port: 3000
- version: 0.1.0

### Custom Configuration
```bash
./generate-project.sh generate \
  --project-name online-store \
  --port 8080 \
  --author "Your Company" \
  --version 1.0.0
```

### Expected Output Structure
```
output/online-store/
├── Cargo.toml (from cargo-toml.tmpl)
├── src/
│   ├── main.rs (from main-rs.tmpl)
│   ├── models/
│   │   ├── mod.rs (from models-mod.tmpl)
│   │   ├── user.rs (from user-model.tmpl)
│   │   └── product.rs (from product-model.tmpl)
│   ├── api/
│   │   ├── mod.rs (from api-mod.tmpl)
│   │   ├── handlers.rs (from api-handlers.tmpl)
│   │   └── routes.rs (from api-routes.tmpl)
│   └── config/
│       ├── mod.rs (from config-mod.tmpl)
│       └── settings.rs (from config-settings.tmpl)
└── tests/
    └── integration_test.rs (from integration-test.tmpl)
```

## Template Dependencies

Generation order (respects dependencies):

```
1. cargo-toml.tmpl (no dependencies)
   ↓
2. models-mod.tmpl, user-model.tmpl, product-model.tmpl
   ↓
3. config-mod.tmpl, config-settings.tmpl
   ↓
4. api-mod.tmpl, api-handlers.tmpl, api-routes.tmpl
   (depends on models)
   ↓
5. main-rs.tmpl
   (depends on models, api, config)
   ↓
6. integration-test.tmpl
   (depends on all above)
```

## Extending Templates

### Adding a New Model

1. **Create template**: `templates/order-model.tmpl`
```rust
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub type OrderId = Uuid;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Order {
    pub id: OrderId,
    pub user_id: UserId,
    pub total: f64,
}
```

2. **Update models-mod.tmpl**:
```rust
pub mod product;
pub mod user;
pub mod order;  // Add this

pub use order::{Order, OrderId};  // Add this
```

3. **Add to project-spec.yaml**:
```yaml
modules:
  - name: order_model
    template: order-model.tmpl
    output: src/models/order.rs
```

### Adding a New Endpoint

1. **Update api-handlers.tmpl**:
```rust
pub async fn list_orders(data: web::Data<AppState>) -> impl Responder {
    // Implementation
}
```

2. **Update api-routes.tmpl**:
```rust
.route("/orders", web::get().to(list_orders))
```

3. **Update integration-test.tmpl**:
```rust
#[actix_web::test]
async fn test_list_orders() {
    // Test implementation
}
```

## Template Best Practices

### 1. Variable Naming
- Use lowercase with underscores: `{{project_name}}`
- Be descriptive: `{{api_prefix}}` not `{{prefix}}`
- Document in project-spec.yaml

### 2. Validation
- Add validation attributes: `#[validate(email)]`
- Test validation in unit tests
- Handle validation errors in handlers

### 3. Error Handling
- Return appropriate status codes (400, 404, 500)
- Include error messages in JSON
- Log errors with context

### 4. Testing
- Include unit tests in model templates
- Add integration tests for all endpoints
- Test both success and error cases

### 5. Documentation
- Add rustdoc comments for public APIs
- Document expected behavior
- Include usage examples

## Template Validation

The `generate-project.sh validate` command checks:

1. **File existence**: All templates exist
2. **Readability**: Files can be read
3. **Syntax**: No unclosed `{{variables}}`
4. **Variables**: All required variables present

## Troubleshooting Templates

### Variable Not Replaced
**Problem**: Output contains `{{variable_name}}`

**Solution**:
1. Check variable name matches exactly
2. Add to substitute_variables function
3. Verify project-spec.yaml

### Compilation Errors
**Problem**: Generated code doesn't compile

**Solution**:
1. Check template syntax
2. Verify imports and modules
3. Test template manually
4. Run `cargo check` on template

### Test Failures
**Problem**: Integration tests fail

**Solution**:
1. Verify API endpoints match routes
2. Check request/response format
3. Ensure state management works
4. Test manually with curl

## Performance Metrics

| Template | Lines | Variables | Output Size |
|----------|-------|-----------|-------------|
| cargo-toml | 25 | 4 | ~500 bytes |
| main-rs | 28 | 4 | ~600 bytes |
| user-model | 65 | 0 | ~1.8 KB |
| product-model | 90 | 0 | ~2.5 KB |
| api-handlers | 110 | 1 | ~3.2 KB |
| api-routes | 22 | 1 | ~600 bytes |
| integration-test | 200 | 2 | ~6.5 KB |

**Total**: 613 lines → ~17 KB of generated code

## License

This template collection is part of the ggen project.
