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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
use colored::Colorize;
use include_dir::{Dir, include_dir};
use lmrc_config_validator::LmrcConfig;
use std::fs;
use std::path::Path;

use crate::error::Result;

// Embed the entire pipeline-template directory at compile time (from embedded-apps/)
static PIPELINE_TEMPLATE: Dir = include_dir!("$CARGO_MANIFEST_DIR/embedded-apps/pipeline-template");

pub fn generate_pipeline_app(project_path: &Path, _config: &LmrcConfig) -> Result<()> {
    let pipeline_path = project_path.join("infra").join("pipeline");
    fs::create_dir_all(&pipeline_path)?;

    // Extract embedded pipeline template
    extract_template(&pipeline_path)?;

    println!("  {} infra/pipeline", "Created:".green());
    println!(
        "  {} Pipeline uses lmrc-pipeline library",
        "Note:".bright_blue()
    );
    println!(
        "  {} All files statically validated at compile time",
        "Note:".bright_blue()
    );

    Ok(())
}

/// Extract the embedded pipeline template to the target directory
fn extract_template(target_path: &Path) -> Result<()> {
    // Extract all files from the embedded template
    for entry in PIPELINE_TEMPLATE.entries() {
        extract_entry(entry, target_path)?;
    }
    Ok(())
}

/// Recursively extract directory entries
/// Renames .template files back to their original names (e.g., Cargo.toml.template -> Cargo.toml)
fn extract_entry(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() {
                extract_entry(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(())
}

// Old string-based generation functions removed - now using embedded template files

#[cfg(test)]
mod tests {
    use super::*;
    use lmrc_config_validator::*;
    use std::collections::HashMap;
    use tempfile::TempDir;

    #[test]
    fn test_pipeline_template_is_embedded() {
        // Verify that the template is embedded and contains expected files
        assert!(PIPELINE_TEMPLATE.get_file("Cargo.toml.template").is_some());
        assert!(PIPELINE_TEMPLATE.get_file("src/main.rs").is_some());
    }

    #[test]
    fn test_embedded_cargo_toml_is_valid() {
        let cargo_toml = PIPELINE_TEMPLATE
            .get_file("Cargo.toml.template")
            .expect("Cargo.toml.template should be embedded");
        let content = cargo_toml
            .contents_utf8()
            .expect("Cargo.toml should be UTF-8");

        // Verify it parses as TOML
        let parsed: toml::Value = toml::from_str(content).expect("Cargo.toml should be valid TOML");

        // Verify required fields
        assert_eq!(
            parsed["package"]["name"].as_str(),
            Some("pipeline")
        );
        assert!(parsed["dependencies"]["lmrc-pipeline"].is_table());
        assert!(parsed["dependencies"]["lmrc-config-validator"].is_table());
    }

    #[test]
    fn test_embedded_main_rs_contains_required_code() {
        let main_rs = PIPELINE_TEMPLATE
            .get_file("src/main.rs")
            .expect("main.rs should be embedded");
        let content = main_rs.contents_utf8().expect("main.rs should be UTF-8");

        // Verify it contains expected code patterns
        assert!(content.contains("use lmrc_pipeline"));
        assert!(content.contains("use lmrc_config_validator::LmrcConfig"));
        assert!(content.contains("#[tokio::main]"));
        assert!(content.contains("async fn main()"));
        assert!(content.contains("Commands::Provision"));
        assert!(content.contains("Commands::Deploy"));
        assert!(content.contains("Commands::Full"));
    }

    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![ApplicationEntry {
                    name: "test-app".to_string(),
                    app_type: Some(lmrc_config_validator::AppType::Api),
                    docker: None,
                    deployment: None,
                }],
            },
            infrastructure: InfrastructureConfig {
                provider: "hetzner".to_string(),
                network: None,
                servers: vec![ServerGroup {
                    name: "k3s-server".to_string(),
                    role: ServerRole::K3sControl,
                    server_type: "cx11".to_string(),
                    location: "nbg1".to_string(),
                    count: 1,
                    labels: HashMap::new(),
                    ssh_keys: vec![],
                    image: None,
                }],
                k3s: Some(K3sConfig {
                    version: "v1.28.5+k3s1".to_string(),
                    deploy_on: vec!["k3s-server".to_string()],
                    control_plane_servers: vec!["k3s-server".to_string()],
                    worker_servers: vec![],
                    enable_traefik: true,
                    enable_metrics_server: false,
                    server_flags: vec![],
                    agent_flags: vec![],
                }),
                postgres: Some(PostgresConfig {
                    version: "16".to_string(),
                    database_name: "testdb".to_string(),
                    deployment_mode: PostgresDeploymentMode::InCluster,
                    standalone: None,
                    in_cluster: Some(PostgresInClusterConfig {
                        namespace: "default".to_string(),
                        storage_class: "local-path".to_string(),
                        storage_size: "10Gi".to_string(),
                        use_operator: false,
                    }),
                }),
                rabbitmq: None,
                vault: None,
                dns: Some(DnsConfig {
                    provider: "cloudflare".to_string(),
                    domain: "test.example.com".to_string(),
                    records: vec![],
                }),
                gitlab: Some(GitLabConfig {
                    url: "https://gitlab.com".to_string(),
                    namespace: "testuser".to_string(),
                }),
                load_balancer: None,
            },
        }
    }

    #[test]
    fn test_generate_pipeline_app_creates_directory() {
        let temp_dir = TempDir::new().unwrap();
        let config = create_test_config();

        let result = generate_pipeline_app(temp_dir.path(), &config);
        assert!(result.is_ok());

        let pipeline_path = temp_dir.path().join("infra").join("pipeline");
        assert!(pipeline_path.exists());
        assert!(pipeline_path.is_dir());
    }

    #[test]
    fn test_generate_pipeline_app_creates_cargo_toml() {
        let temp_dir = TempDir::new().unwrap();
        let config = create_test_config();

        generate_pipeline_app(temp_dir.path(), &config).unwrap();

        let cargo_toml = temp_dir.path().join("infra/pipeline/Cargo.toml");
        assert!(cargo_toml.exists());
    }

    #[test]
    fn test_generate_pipeline_app_creates_main_rs() {
        let temp_dir = TempDir::new().unwrap();
        let config = create_test_config();

        generate_pipeline_app(temp_dir.path(), &config).unwrap();

        let main_rs = temp_dir.path().join("infra/pipeline/src/main.rs");
        assert!(main_rs.exists());
    }

    #[test]
    fn test_pipeline_cargo_toml_has_correct_name() {
        let temp_dir = TempDir::new().unwrap();
        let config = create_test_config();

        generate_pipeline_app(temp_dir.path(), &config).unwrap();

        let cargo_toml = temp_dir.path().join("infra/pipeline/Cargo.toml");
        let content = fs::read_to_string(cargo_toml).unwrap();

        assert!(content.contains("name = \"pipeline\""));
    }

    #[test]
    fn test_pipeline_cargo_toml_has_bin_section() {
        let temp_dir = TempDir::new().unwrap();
        let config = create_test_config();

        generate_pipeline_app(temp_dir.path(), &config).unwrap();

        let cargo_toml = temp_dir.path().join("infra/pipeline/Cargo.toml");
        let content = fs::read_to_string(cargo_toml).unwrap();

        assert!(content.contains("[[bin]]"));
        assert!(content.contains("name = \"pipeline\""));
        assert!(content.contains("path = \"src/main.rs\""));
    }

    #[test]
    fn test_pipeline_cargo_toml_has_required_dependencies() {
        let temp_dir = TempDir::new().unwrap();
        let config = create_test_config();

        generate_pipeline_app(temp_dir.path(), &config).unwrap();

        let cargo_toml = temp_dir.path().join("infra/pipeline/Cargo.toml");
        let content = fs::read_to_string(cargo_toml).unwrap();

        // Check for required dependencies
        let deps = [
            "tokio",
            "clap",
            "anyhow",
            "lmrc-pipeline",
            "lmrc-config-validator",
        ];
        for dep in &deps {
            assert!(
                content.contains(dep),
                "Pipeline Cargo.toml missing dependency: {}",
                dep
            );
        }
    }

    #[test]
    fn test_pipeline_main_has_tokio_main() {
        let temp_dir = TempDir::new().unwrap();
        let config = create_test_config();

        generate_pipeline_app(temp_dir.path(), &config).unwrap();

        let main_rs = temp_dir.path().join("infra/pipeline/src/main.rs");
        let content = fs::read_to_string(main_rs).unwrap();

        assert!(content.contains("#[tokio::main]"));
        assert!(content.contains("async fn main()"));
    }

    #[test]
    fn test_pipeline_main_has_all_commands() {
        let temp_dir = TempDir::new().unwrap();
        let config = create_test_config();

        generate_pipeline_app(temp_dir.path(), &config).unwrap();

        let main_rs = temp_dir.path().join("infra/pipeline/src/main.rs");
        let content = fs::read_to_string(main_rs).unwrap();

        // Check for all expected commands
        let commands = [
            "Check",
            "Test",
            "Build",
            "DockerBuild",
            "Provision",
            "Setup",
            "Deploy",
            "Full",
        ];

        for cmd in &commands {
            assert!(
                content.contains(cmd),
                "Pipeline main.rs missing command: {}",
                cmd
            );
        }
    }

    #[test]
    fn test_pipeline_main_uses_pipeline_library() {
        let temp_dir = TempDir::new().unwrap();
        let config = create_test_config();

        generate_pipeline_app(temp_dir.path(), &config).unwrap();

        let main_rs = temp_dir.path().join("infra/pipeline/src/main.rs");
        let content = fs::read_to_string(main_rs).unwrap();

        // Check for lmrc_pipeline imports (may include Pipeline, PipelineContext, StepRegistry)
        assert!(content.contains("use lmrc_pipeline::{"));
        assert!(content.contains("Pipeline"));
        assert!(content.contains("PipelineContext"));
        assert!(content.contains("use lmrc_pipeline::steps::*"));
        assert!(content.contains("Pipeline::new(ctx)"));
        assert!(content.contains("PipelineContext::new(config)?") || content.contains("PipelineContext::new(config.clone())?"));
    }

    #[test]
    fn test_pipeline_main_has_clap_parser() {
        let temp_dir = TempDir::new().unwrap();
        let config = create_test_config();

        generate_pipeline_app(temp_dir.path(), &config).unwrap();

        let main_rs = temp_dir.path().join("infra/pipeline/src/main.rs");
        let content = fs::read_to_string(main_rs).unwrap();

        assert!(content.contains("use clap::{Parser, Subcommand}"));
        assert!(content.contains("#[derive(Parser)]"));
        assert!(content.contains("#[derive(Subcommand)]"));
        assert!(content.contains("Cli::parse()"));
    }

    #[test]
    fn test_pipeline_main_full_command_includes_all_steps() {
        let temp_dir = TempDir::new().unwrap();
        let config = create_test_config();

        generate_pipeline_app(temp_dir.path(), &config).unwrap();

        let main_rs = temp_dir.path().join("infra/pipeline/src/main.rs");
        let content = fs::read_to_string(main_rs).unwrap();

        // Full command should use StepRegistry to dynamically build steps
        // Check for the use of registry methods
        assert!(content.contains("StepRegistry::default()") || content.contains("StepRegistry::new()"));
        assert!(content.contains("build_build_steps"));
        assert!(content.contains("build_provision_steps"));
        assert!(content.contains("build_setup_steps"));
        assert!(content.contains("build_deploy_steps"));

        // Check for explicit steps that are always present
        assert!(content.contains("DockerBuildStep::new()"));

        // Check for Commands::Full match arm
        assert!(content.contains("Commands::Full"));
    }

    #[test]
    fn test_pipeline_main_loads_config_from_file() {
        let temp_dir = TempDir::new().unwrap();
        let config = create_test_config();

        generate_pipeline_app(temp_dir.path(), &config).unwrap();

        let main_rs = temp_dir.path().join("infra/pipeline/src/main.rs");
        let content = fs::read_to_string(main_rs).unwrap();

        // Updated to match the new API
        assert!(content.contains("LmrcConfig::from_file"));
        assert!(content.contains("lmrc.toml"));
    }

    #[test]
    fn test_pipeline_main_has_valid_rust_syntax() {
        let temp_dir = TempDir::new().unwrap();
        let config = create_test_config();

        generate_pipeline_app(temp_dir.path(), &config).unwrap();

        let main_rs = temp_dir.path().join("infra/pipeline/src/main.rs");
        let content = fs::read_to_string(main_rs).unwrap();

        // Basic syntax checks
        assert!(content.contains("fn main()"));
        assert!(content.contains("Ok(())"));
        // Check that braces are balanced
        let open_braces = content.chars().filter(|&c| c == '{').count();
        let close_braces = content.chars().filter(|&c| c == '}').count();
        assert_eq!(
            open_braces, close_braces,
            "Unbalanced braces in generated main.rs"
        );
    }

    #[test]
    fn test_pipeline_workspace_dependencies() {
        let temp_dir = TempDir::new().unwrap();
        let config = create_test_config();

        generate_pipeline_app(temp_dir.path(), &config).unwrap();

        let cargo_toml = temp_dir.path().join("infra/pipeline/Cargo.toml");
        let content = fs::read_to_string(cargo_toml).unwrap();

        // Dependencies should use workspace = true
        assert!(content.contains("workspace = true"));
    }
}