lmrc-cli 0.3.16

CLI tool for scaffolding LMRC Stack infrastructure projects
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
//! Application template generation module
//!
//! This module handles generation of applications from embedded templates.
//! It supports multiple template types: gateway (with auth), api (without auth), and migrator.

use colored::Colorize;
use include_dir::{Dir, include_dir};
use lmrc_config_validator::{AppType, ApplicationEntry, LmrcConfig};
use std::fs;
use std::path::Path;

use crate::error::Result;

// Embed template directories at compile time (from embedded-apps/ directory within CLI crate)
static API_SERVICE_TEMPLATE: Dir =
    include_dir!("$CARGO_MANIFEST_DIR/embedded-apps/api-service-template");

// Embed infrastructure apps (ready-to-use, no templating)
static GATEWAY_APP: Dir = include_dir!("$CARGO_MANIFEST_DIR/embedded-apps/gateway");
static INFRA_API_APP: Dir = include_dir!("$CARGO_MANIFEST_DIR/embedded-apps/infra-api");
static INFRA_MIGRATOR_APP: Dir = include_dir!("$CARGO_MANIFEST_DIR/embedded-apps/infra-migrator");
static APP_MIGRATOR_APP: Dir = include_dir!("$CARGO_MANIFEST_DIR/embedded-apps/app-migrator");
static INFRA_FRONT_APP: Dir = include_dir!("$CARGO_MANIFEST_DIR/embedded-apps/infra-front");

/// Generate all applications from config
pub fn generate_applications(project_path: &Path, config: &LmrcConfig) -> Result<()> {
    // First, bundle infrastructure apps (always included)
    bundle_infrastructure_apps(project_path)?;

    // Then generate user-defined applications
    for app in &config.apps.applications {
        generate_single_app_internal(project_path, app, config)?;
    }
    Ok(())
}

/// Generate a single application by name and type (for `lmrc add app` command)
pub fn generate_single_app(
    project_path: &Path,
    app_name: &str,
    app_type: Option<&AppType>,
) -> Result<()> {
    let app = ApplicationEntry {
        name: app_name.to_string(),
        app_type: app_type.cloned(),
        docker: None,
        deployment: None,
    };

    // Create a minimal config for templating
    let config = create_minimal_config_for_templating(app_name);

    generate_single_app_internal(project_path, &app, &config)
}

fn create_minimal_config_for_templating(app_name: &str) -> LmrcConfig {
    use lmrc_config_validator::*;

    LmrcConfig {
        project: ProjectConfig {
            name: "project".to_string(),
            description: "Project".to_string(),
        },
        providers: ProviderConfig {
            server: "hetzner".to_string(),
            kubernetes: "k3s".to_string(),
            database: "postgres".to_string(),
            queue: "rabbitmq".to_string(),
            dns: "cloudflare".to_string(),
            git: "gitlab".to_string(),
        },
        apps: AppsConfig {
            applications: vec![],
        },
        infrastructure: InfrastructureConfig {
            provider: "hetzner".to_string(),
            network: None,
            servers: vec![],
            load_balancer: None,
            k3s: None,
            postgres: None,
            rabbitmq: None,
            vault: None,
            dns: None,
            gitlab: None,
        },
    }
}

/// Bundle ready-to-use infrastructure apps (no templating)
fn bundle_infrastructure_apps(project_path: &Path) -> Result<()> {
    println!("  {} Infrastructure apps...", "Bundling:".cyan());

    // Bundle gateway
    let gateway_path = project_path.join("apps").join("gateway");
    copy_app_as_is(&GATEWAY_APP, &gateway_path)?;
    println!("    {} apps/gateway", "✓".green());

    // Bundle infra-api
    let infra_api_path = project_path.join("apps").join("infra-api");
    copy_app_as_is(&INFRA_API_APP, &infra_api_path)?;
    println!("    {} apps/infra-api", "✓".green());

    // Bundle infra-migrator
    let infra_migrator_path = project_path.join("apps").join("infra-migrator");
    copy_app_as_is(&INFRA_MIGRATOR_APP, &infra_migrator_path)?;
    println!("    {} apps/infra-migrator", "✓".green());

    // Bundle app-migrator
    let app_migrator_path = project_path.join("apps").join("app-migrator");
    copy_app_as_is(&APP_MIGRATOR_APP, &app_migrator_path)?;
    println!("    {} apps/app-migrator", "✓".green());

    // Bundle infra-front
    let infra_front_path = project_path.join("apps").join("infra-front");
    copy_app_as_is(&INFRA_FRONT_APP, &infra_front_path)?;
    println!("    {} apps/infra-front", "✓".green());

    Ok(())
}

/// Copy an app directory as-is without any template processing
fn copy_app_as_is(app_dir: &Dir, dest_path: &Path) -> Result<()> {
    fs::create_dir_all(dest_path)?;

    for entry in app_dir.entries() {
        copy_entry_as_is(entry, dest_path)?;
    }

    Ok(())
}

/// Recursively copy directory entries without any processing
/// Renames .template files back to their original names (e.g., Cargo.toml.template -> Cargo.toml)
fn copy_entry_as_is(entry: &include_dir::DirEntry, base_path: &Path) -> Result<()> {
    match entry {
        include_dir::DirEntry::Dir(dir) => {
            let dir_path = base_path.join(dir.path());
            fs::create_dir_all(&dir_path)?;
            for child in dir.entries() {
                copy_entry_as_is(child, base_path)?;
            }
        }
        include_dir::DirEntry::File(file) => {
            let mut file_path = base_path.join(file.path());

            // Rename .template files back to original (e.g., Cargo.toml.template -> Cargo.toml)
            if let Some(path_str) = file_path.to_str() {
                if path_str.ends_with(".template") {
                    file_path = Path::new(&path_str.trim_end_matches(".template")).to_path_buf();
                }
            }

            if let Some(parent) = file_path.parent() {
                fs::create_dir_all(parent)?;
            }
            fs::write(&file_path, file.contents())?;
        }
    }
    Ok(())
}

/// Generate a single application based on its type (internal version with full config)
fn generate_single_app_internal(
    project_path: &Path,
    app: &ApplicationEntry,
    config: &LmrcConfig,
) -> Result<()> {
    let app_path = project_path.join("apps").join(&app.name);
    fs::create_dir_all(&app_path)?;

    match &app.app_type {
        Some(AppType::Gateway) => {
            // Gateway is bundled as infrastructure app - copy it from embedded
            copy_app_as_is(&GATEWAY_APP, &app_path)?;
            println!("  {} apps/{} (API Gateway with auth)", "Created:".green(), app.name);
        }
        Some(AppType::Api) => {
            generate_from_template(&API_SERVICE_TEMPLATE, &app_path, app, config)?;
            println!("  {} apps/{} (API service)", "Created:".green(), app.name);
        }
        Some(AppType::Migrator) => {
            // Migrator is bundled as app-migrator - copy it from embedded
            copy_app_as_is(&APP_MIGRATOR_APP, &app_path)?;
            println!("  {} apps/{} (Database migrator)", "Created:".green(), app.name);
        }
        Some(AppType::Basic) | None => {
            // Fallback to basic app generation
            generate_basic_app(&app_path, app)?;
            println!("  {} apps/{} (basic app)", "Created:".green(), app.name);
        }
    }

    Ok(())
}

/// Generate application from embedded template
fn generate_from_template(
    template: &Dir,
    app_path: &Path,
    app: &ApplicationEntry,
    config: &LmrcConfig,
) -> Result<()> {
    for entry in template.entries() {
        extract_and_process_entry(entry, app_path, app, config)?;
    }
    Ok(())
}

/// Recursively extract and process template entries
fn extract_and_process_entry(
    entry: &include_dir::DirEntry,
    base_path: &Path,
    app: &ApplicationEntry,
    config: &LmrcConfig,
) -> Result<()> {
    match entry {
        include_dir::DirEntry::Dir(dir) => {
            let dir_path = base_path.join(dir.path());
            fs::create_dir_all(&dir_path)?;
            for child in dir.entries() {
                extract_and_process_entry(child, base_path, app, config)?;
            }
        }
        include_dir::DirEntry::File(file) => {
            let mut file_path = base_path.join(file.path());

            // Rename .template files back to original (e.g., Cargo.toml.template -> Cargo.toml)
            if let Some(path_str) = file_path.to_str() {
                if path_str.ends_with(".template") {
                    file_path = Path::new(&path_str.trim_end_matches(".template")).to_path_buf();
                }
            }

            if let Some(parent) = file_path.parent() {
                fs::create_dir_all(parent)?;
            }

            // Get file contents
            let contents = file.contents();

            // Process text files for placeholder replacement
            if let Ok(text) = std::str::from_utf8(contents) {
                let processed = replace_placeholders(text, app, config);
                fs::write(&file_path, processed)?;
            } else {
                // Binary file, write as-is
                fs::write(&file_path, contents)?;
            }
        }
    }
    Ok(())
}

/// Replace template placeholders with actual values
fn replace_placeholders(content: &str, app: &ApplicationEntry, config: &LmrcConfig) -> String {
    let mut result = content.to_string();

    // Replace app-specific placeholders
    result = result.replace("{{app_name}}", &app.name);

    // Replace port - use deployment port if available, otherwise default
    let port = app
        .deployment
        .as_ref()
        .map(|d| d.port.to_string())
        .unwrap_or_else(|| "8080".to_string());
    result = result.replace("{{app_port}}", &port);

    // Replace project-specific placeholders
    result = result.replace("{{project_name}}", &config.project.name);
    result = result.replace("{{project_description}}", &config.project.description);

    result
}

/// Generate a basic application (fallback for unknown types)
fn generate_basic_app(app_path: &Path, app: &ApplicationEntry) -> Result<()> {
    use lmrc_toml_writer::PackageToml;

    // Create Cargo.toml
    let cargo_toml = PackageToml::new(&app.name)
        .version("0.1.0")
        .edition("2021")
        .dependency_inline("tokio", r#"{ version = "1.0", features = ["full"] }"#)
        .build();

    fs::write(app_path.join("Cargo.toml"), cargo_toml)?;

    // Create src directory and main.rs
    let src_dir = app_path.join("src");
    fs::create_dir_all(&src_dir)?;

    let main_rs = format!(
        r#"#[tokio::main]
async fn main() {{
    println!("Hello from {}!");
}}
"#,
        app.name
    );

    fs::write(src_dir.join("main.rs"), main_rs)?;

    Ok(())
}

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

    #[test]
    fn test_gateway_app_is_embedded() {
        assert!(GATEWAY_APP.get_file("Cargo.toml.template").is_some());
        assert!(GATEWAY_APP.get_file("src/main.rs").is_some());
    }

    #[test]
    fn test_infra_api_app_is_embedded() {
        assert!(INFRA_API_APP.get_file("Cargo.toml.template").is_some());
        assert!(INFRA_API_APP.get_file("src/main.rs").is_some());
    }

    #[test]
    fn test_infra_migrator_app_is_embedded() {
        assert!(INFRA_MIGRATOR_APP.get_file("Cargo.toml.template").is_some());
        assert!(INFRA_MIGRATOR_APP.get_file("src/main.rs").is_some());
    }

    #[test]
    fn test_app_migrator_app_is_embedded() {
        assert!(APP_MIGRATOR_APP.get_file("Cargo.toml.template").is_some());
        assert!(APP_MIGRATOR_APP.get_file("src/main.rs").is_some());
    }

    #[test]
    fn test_api_service_template_is_embedded() {
        assert!(
            API_SERVICE_TEMPLATE
                .get_file("Cargo.toml.template")
                .is_some()
        );
        assert!(API_SERVICE_TEMPLATE.get_file("src/main.rs").is_some());
    }

    #[test]
    fn test_replace_placeholders() {
        let app = ApplicationEntry {
            name: "my-gateway".to_string(),
            app_type: Some(AppType::Gateway),
            docker: None,
            deployment: Some(DeploymentConfig {
                replicas: 1,
                port: 3000,
                cpu_request: None,
                memory_request: None,
                cpu_limit: None,
                memory_limit: None,
                env: vec![],
            }),
        };

        let config = create_test_config();

        let template =
            "name = \"{{app_name}}\"\nport = {{app_port}}\nproject = \"{{project_name}}\"";
        let result = replace_placeholders(template, &app, &config);

        assert!(result.contains("name = \"my-gateway\""));
        assert!(result.contains("port = 3000"));
        assert!(result.contains("project = \"test-project\""));
    }

    #[test]
    fn test_replace_placeholders_with_default_port() {
        let app = ApplicationEntry {
            name: "my-api".to_string(),
            app_type: Some(AppType::Api),
            docker: None,
            deployment: None, // No deployment config = use default port
        };

        let config = create_test_config();

        let template = "PORT={{app_port}}";
        let result = replace_placeholders(template, &app, &config);

        assert!(result.contains("PORT=8080"));
    }

    fn create_test_config() -> LmrcConfig {
        LmrcConfig {
            project: ProjectConfig {
                name: "test-project".to_string(),
                description: "Test project".to_string(),
            },
            providers: ProviderConfig {
                server: "hetzner".to_string(),
                kubernetes: "k3s".to_string(),
                database: "postgres".to_string(),
                queue: "rabbitmq".to_string(),
                dns: "cloudflare".to_string(),
                git: "gitlab".to_string(),
            },
            apps: AppsConfig {
                applications: vec![],
            },
            infrastructure: InfrastructureConfig {
                provider: "hetzner".to_string(),
                network: None,
                servers: vec![],
                k3s: None,
                postgres: None,
                rabbitmq: None,
                vault: None,
                dns: None,
                gitlab: None,
                load_balancer: None,
            },
        }
    }
}