syncable-cli 0.37.1

A Rust-based CLI that analyzes code repositories and generates Infrastructure as Code configurations
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
use crate::{analyzer::analyze_monorepo, generator};

pub fn handle_generate(
    path: std::path::PathBuf,
    _output: Option<std::path::PathBuf>,
    dockerfile: bool,
    compose: bool,
    terraform: bool,
    all: bool,
    dry_run: bool,
    _force: bool,
) -> crate::Result<()> {
    println!("🔍 Analyzing project for generation: {}", path.display());

    let monorepo_analysis = analyze_monorepo(&path)?;

    println!("✅ Analysis complete. Generating IaC files...");

    if monorepo_analysis.is_monorepo {
        println!(
            "📦 Detected monorepo with {} projects",
            monorepo_analysis.projects.len()
        );
        println!(
            "🚧 Monorepo IaC generation is coming soon! For now, generating for the overall structure."
        );
        println!(
            "💡 Tip: You can run generate commands on individual project directories for now."
        );
    }

    // For now, use the first/main project for generation
    // TODO: Implement proper monorepo IaC generation
    let main_project = &monorepo_analysis.projects[0];

    let generate_all = all || (!dockerfile && !compose && !terraform);

    if generate_all || dockerfile {
        println!("\n🐳 Generating Dockerfile...");
        let dockerfile_content = generator::generate_dockerfile(&main_project.analysis)?;

        if dry_run {
            println!("--- Dockerfile (dry run) ---");
            println!("{}", dockerfile_content);
        } else {
            std::fs::write("Dockerfile", dockerfile_content)?;
            println!("✅ Dockerfile generated successfully!");
        }
    }

    if generate_all || compose {
        println!("\n🐙 Generating Docker Compose file...");
        let compose_content = generator::generate_compose(&main_project.analysis)?;

        if dry_run {
            println!("--- docker-compose.yml (dry run) ---");
            println!("{}", compose_content);
        } else {
            std::fs::write("docker-compose.yml", compose_content)?;
            println!("✅ Docker Compose file generated successfully!");
        }
    }

    if generate_all || terraform {
        println!("\n🏗️  Generating Terraform configuration...");
        let terraform_content = generator::generate_terraform(&main_project.analysis)?;

        if dry_run {
            println!("--- main.tf (dry run) ---");
            println!("{}", terraform_content);
        } else {
            std::fs::write("main.tf", terraform_content)?;
            println!("✅ Terraform configuration generated successfully!");
        }
    }

    if !dry_run {
        println!("\n🎉 Generation complete! IaC files have been created in the current directory.");

        if monorepo_analysis.is_monorepo {
            println!("🔧 Note: Generated files are based on the main project structure.");
            println!("   Advanced monorepo support with per-project generation is coming soon!");
        }
    }

    Ok(())
}

pub fn handle_validate(
    path: std::path::PathBuf,
    types: Option<Vec<String>>,
    fix: bool,
    quiet: bool,
) -> crate::Result<String> {
    use crate::analyzer::{dclint, hadolint, helmlint, kubelint};
    use std::path::Path;

    let project_path = path.canonicalize().unwrap_or_else(|_| path.clone());

    if !quiet {
        println!("🔍 Validating IaC files in: {}", project_path.display());
    }

    let type_filter: Option<Vec<String>> = types.map(|t| {
        t.iter()
            .flat_map(|s| s.split(','))
            .map(|s| s.trim().to_lowercase())
            .collect()
    });
    let check_all = type_filter.is_none();
    let should_check = |name: &str| {
        check_all
            || type_filter
                .as_ref()
                .map_or(false, |f| f.iter().any(|t| t == name))
    };

    let mut all_results: Vec<serde_json::Value> = Vec::new();
    let mut total_errors = 0usize;
    let mut total_warnings = 0usize;
    let mut total_info = 0usize;
    let mut files_checked = 0usize;

    // --- Dockerfiles (hadolint) ---
    if should_check("dockerfile") {
        let dockerfiles = find_dockerfiles(&project_path);
        if !dockerfiles.is_empty() {
            if !quiet {
                println!("\n🐳 Checking {} Dockerfile(s)...", dockerfiles.len());
            }
            let config = hadolint::HadolintConfig::default();
            for df in &dockerfiles {
                let result = hadolint::lint_file(df, &config);
                files_checked += 1;
                let rel = df.strip_prefix(&project_path).unwrap_or(df);
                let (e, w, i) = count_severities_hadolint(&result);
                total_errors += e;
                total_warnings += w;
                total_info += i;
                if !quiet && result.has_failures() {
                    println!("  {}{} error(s), {} warning(s)", rel.display(), e, w);
                }
                for f in &result.failures {
                    all_results.push(serde_json::json!({
                        "type": "dockerfile",
                        "file": rel.display().to_string(),
                        "line": f.line,
                        "code": f.code.to_string(),
                        "severity": format!("{:?}", f.severity),
                        "message": f.message,
                    }));
                }
            }
        }
    }

    // --- Docker Compose (dclint) ---
    if should_check("compose") {
        let compose_files = find_compose_files(&project_path);
        if !compose_files.is_empty() {
            if !quiet {
                println!("\n🐙 Checking {} Compose file(s)...", compose_files.len());
            }
            let config = dclint::DclintConfig::default();
            for cf in &compose_files {
                let result = dclint::lint_file(cf, &config);
                files_checked += 1;
                let rel = cf.strip_prefix(&project_path).unwrap_or(cf);
                let (e, w, i) = count_severities_dclint(&result);
                total_errors += e;
                total_warnings += w;
                total_info += i;
                if !quiet && result.has_failures() {
                    println!("  {}{} error(s), {} warning(s)", rel.display(), e, w);
                }
                for f in &result.failures {
                    all_results.push(serde_json::json!({
                        "type": "compose",
                        "file": rel.display().to_string(),
                        "line": f.line,
                        "code": f.code.to_string(),
                        "severity": format!("{:?}", f.severity),
                        "message": f.message,
                    }));
                }

                // Auto-fix if requested
                if fix {
                    if let Ok(Some(fixed)) = dclint::fix_file(cf, &config, false) {
                        if !quiet {
                            println!("    ✅ Auto-fixed {}", rel.display());
                        }
                        let _ = fixed; // fix_file already writes when dry_run=false
                    }
                }
            }
        }
    }

    // --- Kubernetes manifests (kubelint) ---
    if should_check("kubernetes") || should_check("k8s") {
        let k8s_dirs = find_k8s_dirs(&project_path);
        if !k8s_dirs.is_empty() {
            if !quiet {
                println!(
                    "\n☸️  Checking {} K8s manifest location(s)...",
                    k8s_dirs.len()
                );
            }
            let config = kubelint::KubelintConfig::default();
            for dir in &k8s_dirs {
                let result = kubelint::lint(dir, &config);
                let rel = dir.strip_prefix(&project_path).unwrap_or(dir);
                files_checked += result.summary.objects_analyzed;
                let (e, w, i) = count_severities_kubelint(&result);
                total_errors += e;
                total_warnings += w;
                total_info += i;
                if !quiet && result.has_failures() {
                    println!("  {}{} error(s), {} warning(s)", rel.display(), e, w);
                }
                for f in &result.failures {
                    all_results.push(serde_json::json!({
                        "type": "kubernetes",
                        "object": format!("{}/{}", f.object_kind, f.object_name),
                        "file": f.file_path.display().to_string(),
                        "code": f.code.to_string(),
                        "severity": format!("{:?}", f.severity),
                        "message": f.message,
                        "remediation": f.remediation,
                    }));
                }
            }
        }
    }

    // --- Helm charts (helmlint) ---
    if should_check("helm") {
        let helm_charts = find_helm_charts_validate(&project_path);
        if !helm_charts.is_empty() {
            if !quiet {
                println!("\n⎈ Checking {} Helm chart(s)...", helm_charts.len());
            }
            let config = helmlint::HelmlintConfig::default();
            for chart in &helm_charts {
                let result = helmlint::lint_chart(chart, &config);
                files_checked += result.files_checked;
                let rel = chart.strip_prefix(&project_path).unwrap_or(chart);
                let (e, w, i) = count_severities_helmlint(&result);
                total_errors += e;
                total_warnings += w;
                total_info += i;
                if !quiet && result.has_failures() {
                    println!("  {}{} error(s), {} warning(s)", rel.display(), e, w);
                }
                for f in &result.failures {
                    all_results.push(serde_json::json!({
                        "type": "helm",
                        "file": f.file.display().to_string(),
                        "line": f.line,
                        "code": f.code.to_string(),
                        "severity": format!("{:?}", f.severity),
                        "message": f.message,
                    }));
                }
            }
        }
    }

    if files_checked == 0 {
        if !quiet {
            println!("\n⚠️  No IaC files found to validate.");
        }
        let output = serde_json::json!({
            "status": "NO_FILES",
            "message": "No IaC files found. Use sync-ctl analyze to check what IaC exists.",
            "files_checked": 0,
            "violations": []
        });
        return Ok(serde_json::to_string_pretty(&output)?);
    }

    // Summary
    if !quiet {
        println!("\n{}", "".repeat(60));
        println!(
            "📊 {} file(s) checked — {} error(s), {} warning(s), {} info",
            files_checked, total_errors, total_warnings, total_info
        );
        if total_errors == 0 && total_warnings == 0 {
            println!("✅ All checks passed!");
        }
    }

    let output = serde_json::json!({
        "files_checked": files_checked,
        "total_errors": total_errors,
        "total_warnings": total_warnings,
        "total_info": total_info,
        "violations": all_results,
    });

    Ok(serde_json::to_string_pretty(&output)?)
}

// --- File discovery helpers ---

fn find_dockerfiles(root: &std::path::Path) -> Vec<std::path::PathBuf> {
    let mut files = Vec::new();
    let names = ["Dockerfile", "dockerfile", "Containerfile"];
    walk_for_files(root, 0, 4, &mut files, &|name| {
        names
            .iter()
            .any(|n| name == *n || name.starts_with(&format!("{}.", n)))
    });
    files
}

fn find_compose_files(root: &std::path::Path) -> Vec<std::path::PathBuf> {
    let mut files = Vec::new();
    walk_for_files(root, 0, 4, &mut files, &|name| {
        let n = name.to_lowercase();
        n == "docker-compose.yml"
            || n == "docker-compose.yaml"
            || n == "compose.yml"
            || n == "compose.yaml"
    });
    files
}

fn find_k8s_dirs(root: &std::path::Path) -> Vec<std::path::PathBuf> {
    // Look for directories containing K8s YAML files (with kind: field)
    let k8s_dir_names = [
        "k8s",
        "kubernetes",
        "manifests",
        "deploy",
        "deployments",
        "kube",
    ];
    let mut dirs = Vec::new();
    if let Ok(entries) = std::fs::read_dir(root) {
        for entry in entries.flatten() {
            let p = entry.path();
            if p.is_dir() {
                let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("");
                if k8s_dir_names.contains(&name.to_lowercase().as_str()) {
                    dirs.push(p);
                }
            }
        }
    }
    // Also check root for K8s files
    if has_k8s_files(root) && dirs.is_empty() {
        dirs.push(root.to_path_buf());
    }
    dirs
}

fn has_k8s_files(dir: &std::path::Path) -> bool {
    if let Ok(entries) = std::fs::read_dir(dir) {
        for entry in entries.flatten() {
            let p = entry.path();
            if let Some(ext) = p.extension().and_then(|e| e.to_str()) {
                if (ext == "yml" || ext == "yaml") && !is_compose_file(&p) {
                    if let Ok(content) = std::fs::read_to_string(&p) {
                        if content.contains("apiVersion:") && content.contains("kind:") {
                            return true;
                        }
                    }
                }
            }
        }
    }
    false
}

fn is_compose_file(p: &std::path::Path) -> bool {
    let name = p
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("")
        .to_lowercase();
    name.contains("compose") || name.contains("docker-compose")
}

fn find_helm_charts_validate(root: &std::path::Path) -> Vec<std::path::PathBuf> {
    let mut charts = Vec::new();
    if root.join("Chart.yaml").exists() {
        charts.push(root.to_path_buf());
        return charts;
    }
    walk_for_dirs(root, 0, 3, &mut charts, &|dir| {
        dir.join("Chart.yaml").exists()
    });
    charts
}

fn walk_for_files(
    dir: &std::path::Path,
    depth: usize,
    max_depth: usize,
    out: &mut Vec<std::path::PathBuf>,
    matcher: &dyn Fn(&str) -> bool,
) {
    if depth >= max_depth {
        return;
    }
    let skip = [
        "node_modules",
        "target",
        ".git",
        "vendor",
        "dist",
        "build",
        "__pycache__",
    ];
    let entries = match std::fs::read_dir(dir) {
        Ok(e) => e,
        Err(_) => return,
    };
    for entry in entries.flatten() {
        let p = entry.path();
        if p.is_file() {
            if let Some(name) = p.file_name().and_then(|n| n.to_str()) {
                if matcher(name) {
                    out.push(p);
                }
            }
        } else if p.is_dir() {
            let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("");
            if !name.starts_with('.') && !skip.contains(&name) {
                walk_for_files(&p, depth + 1, max_depth, out, matcher);
            }
        }
    }
}

fn walk_for_dirs(
    dir: &std::path::Path,
    depth: usize,
    max_depth: usize,
    out: &mut Vec<std::path::PathBuf>,
    matcher: &dyn Fn(&std::path::Path) -> bool,
) {
    if depth >= max_depth {
        return;
    }
    let skip = ["node_modules", "target", ".git", "vendor"];
    let entries = match std::fs::read_dir(dir) {
        Ok(e) => e,
        Err(_) => return,
    };
    for entry in entries.flatten() {
        let p = entry.path();
        if p.is_dir() {
            let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("");
            if !name.starts_with('.') && !skip.contains(&name) {
                if matcher(&p) {
                    out.push(p.clone());
                }
                walk_for_dirs(&p, depth + 1, max_depth, out, matcher);
            }
        }
    }
}

// --- Severity counting helpers (each linter has its own types) ---

fn count_severities_hadolint(
    result: &crate::analyzer::hadolint::LintResult,
) -> (usize, usize, usize) {
    use crate::analyzer::hadolint::Severity;
    let (mut e, mut w, mut i) = (0, 0, 0);
    for f in &result.failures {
        match f.severity {
            Severity::Error => e += 1,
            Severity::Warning => w += 1,
            Severity::Info | Severity::Style | Severity::Ignore => i += 1,
        }
    }
    (e, w, i)
}

fn count_severities_dclint(result: &crate::analyzer::dclint::LintResult) -> (usize, usize, usize) {
    use crate::analyzer::dclint::Severity;
    let (mut e, mut w, mut i) = (0, 0, 0);
    for f in &result.failures {
        match f.severity {
            Severity::Error => e += 1,
            Severity::Warning => w += 1,
            Severity::Info | Severity::Style => i += 1,
        }
    }
    (e, w, i)
}

fn count_severities_kubelint(
    result: &crate::analyzer::kubelint::LintResult,
) -> (usize, usize, usize) {
    use crate::analyzer::kubelint::Severity;
    let (mut e, mut w, mut i) = (0, 0, 0);
    for f in &result.failures {
        match f.severity {
            Severity::Error => e += 1,
            Severity::Warning => w += 1,
            Severity::Info => i += 1,
        }
    }
    (e, w, i)
}

fn count_severities_helmlint(
    result: &crate::analyzer::helmlint::LintResult,
) -> (usize, usize, usize) {
    use crate::analyzer::helmlint::Severity;
    let (mut e, mut w, mut i) = (0, 0, 0);
    for f in &result.failures {
        match f.severity {
            Severity::Error => e += 1,
            Severity::Warning => w += 1,
            Severity::Info | Severity::Style | Severity::Ignore => i += 1,
        }
    }
    (e, w, i)
}