svccat 0.17.0

Detect drift between your declared service catalog and what actually lives in the repo.
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
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
use anyhow::Result;
use clap::{CommandFactory, Parser};
use clap_complete::generate;
use std::io;
use std::process;
use svccat::cli::{Cli, Commands, AuditFormat, CiFormat, DepsFormat, DiffFormat, ExportFormat, GraphFormat, HookKind, ImportSource, OutputFormat, PolicyFormat, ReportFormat, SnapshotAction, TagAction};
use svccat::{
    audit, ci, config, deps, diff, discovery, drift, fix, hooks, import, init, lint, manifest,
    output, ping, policy, report, search, serve, since, snapshot, stats, tag, watch,
};

fn main() {
    match run() {
        Ok(code) => process::exit(code),
        Err(e) => {
            eprintln!("error: {e:#}");
            process::exit(2);
        }
    }
}

fn run() -> Result<i32> {
    let cli = Cli::parse();
    let root = cli.root.unwrap_or_else(|| std::path::PathBuf::from("."));

    // Load workspace config (svccat.toml), falling back to defaults.
    let cfg = config::SvccatConfig::load(&root)?;

    match cli.command {
        Commands::Check {
            manifest: manifest_path,
            format,
            fail_on_drift,
            ping: do_ping,
            ignore: cli_ignore,
            team,
            since,
            fail_on_new_drift,
            depth,
            baseline,
            output: output_path,
        } => {
            // When running inside GitHub Actions and no explicit format was chosen,
            // default to github-annotation so drift items appear as inline PR comments.
            let format = if format == OutputFormat::Terminal
                && std::env::var("GITHUB_ACTIONS").as_deref() == Ok("true")
            {
                OutputFormat::GithubAnnotation
            } else {
                format
            };
            let path = manifest_path.unwrap_or_else(|| manifest::find_default(&root));
            let full_m = manifest::Manifest::load(&path)?;

            // Build the working manifest, applying team filter when requested.
            let mut m = full_m.clone();
            if let Some(ref t) = team {
                m.services.retain(|s| {
                    s.team
                        .as_deref()
                        .map(|v| v.eq_ignore_ascii_case(t))
                        .unwrap_or(false)
                });
            }

            // Merge config ignore + CLI ignore patterns.
            let mut ignore: Vec<String> = cfg.ignore.clone();
            ignore.extend(cli_ignore);

            let discovered_all = discovery::discover_services_with_opts(&root, &full_m, &ignore, depth);

            // When a team filter is active, exclude discovered services that are known to
            // belong to other teams so they don't show up as UndeclaredInRepo noise.
            let in_scope_names: std::collections::HashSet<&str> =
                m.services.iter().map(|s| s.name.as_str()).collect();
            let other_declared_names: std::collections::HashSet<&str> = full_m
                .services
                .iter()
                .filter(|s| !in_scope_names.contains(s.name.as_str()))
                .map(|s| s.name.as_str())
                .collect();
            let discovered: Vec<_> = discovered_all
                .into_iter()
                .filter(|d| !other_declared_names.contains(d.name.as_str()))
                .collect();

            let mut report = drift::analyze(&m, &discovered, &root);
            report.manifest = path.display().to_string();

            // --baseline: filter drift to only items absent from the saved baseline snapshot.
            if let Some(ref baseline_path) = baseline {
                use std::collections::HashSet;

                #[derive(serde::Deserialize)]
                struct BaselineFile {
                    drift: Vec<drift::DriftItem>,
                }

                let text = std::fs::read_to_string(baseline_path)
                    .map_err(|e| anyhow::anyhow!("cannot read baseline {}: {e}", baseline_path.display()))?;
                let snap: BaselineFile = serde_json::from_str(&text)
                    .map_err(|e| anyhow::anyhow!("cannot parse baseline JSON: {e}"))?;

                let baseline_keys: HashSet<String> = snap.drift.iter()
                    .map(|d| format!("{:?}|{}|{}", d.kind, d.service, d.detail.as_deref().unwrap_or("")))
                    .collect();

                report.drifts.retain(|d| {
                    !baseline_keys.contains(&format!(
                        "{:?}|{}|{}",
                        d.kind,
                        d.service,
                        d.detail.as_deref().unwrap_or("")
                    ))
                });
            }

            let ping_results = if do_ping {
                ping::ping_services(&m)
            } else {
                vec![]
            };

            // --since: load the old manifest at the given git ref and diff.
            if let Some(ref git_ref) = since {
                let old_m = since::load_at_ref(&root, &path, git_ref)?;
                let mut old_report = drift::analyze(&old_m, &discovered, &root);
                old_report.manifest = path.display().to_string();

                let new_count = match format {
                    OutputFormat::Markdown => {
                        let md = output::markdown::render_since_diff_markdown(
                            &old_report,
                            &report,
                            git_ref,
                        );
                        print!("{}", md);
                        // Count new items for exit code
                        use std::collections::HashSet;
                        let old_keys: HashSet<String> = old_report
                            .drifts
                            .iter()
                            .map(|d| {
                                format!(
                                    "{:?}|{}|{}",
                                    d.kind,
                                    d.service,
                                    d.detail.as_deref().unwrap_or("")
                                )
                            })
                            .collect();
                        report
                            .drifts
                            .iter()
                            .filter(|d| {
                                let k = format!(
                                    "{:?}|{}|{}",
                                    d.kind,
                                    d.service,
                                    d.detail.as_deref().unwrap_or("")
                                );
                                !old_keys.contains(&k)
                            })
                            .count()
                    }
                    OutputFormat::GithubAnnotation => {
                        output::github_annotation::render_since_annotations(&old_report, &report)
                    }
                    OutputFormat::Junit => {
                        output::junit::render_since(&old_report, &report, git_ref)
                    }
                    _ => {
                        let (new_count, _) =
                            output::terminal::render_since_diff(&old_report, &report, git_ref);
                        new_count
                    }
                };

                if fail_on_new_drift && new_count > 0 {
                    return Ok(1);
                }
            } else {
                // For Json and Markdown formats, capture to string so we can write to --output.
                let maybe_string: Option<String> = match &format {
                    OutputFormat::Json => {
                        Some(output::json::render_check_to_string(&report, &ping_results)?)
                    }
                    OutputFormat::Markdown => {
                        Some(output::markdown::render_check_markdown(&report, &ping_results))
                    }
                    _ => None,
                };

                if let Some(content) = maybe_string {
                    if let Some(ref out_path) = output_path {
                        std::fs::write(out_path, &content)?;
                        eprintln!("wrote output to {}", out_path.display());
                    } else {
                        print!("{}", content);
                    }
                } else {
                    match format {
                        OutputFormat::Terminal => {
                            output::terminal::render_check(&report, &ping_results)
                        }
                        OutputFormat::Compact => {
                            output::terminal::render_compact(&m, &report);
                        }
                        OutputFormat::Sarif => {
                            output::sarif::render_check(&report, &ping_results)?
                        }
                        OutputFormat::Junit => {
                            output::junit::render_check(&report, &ping_results)?
                        }
                        OutputFormat::GithubAnnotation => {
                            output::github_annotation::render_check(&report);
                        }
                        OutputFormat::Csv => output::csv::render_check(&report),
                        OutputFormat::Slack => output::slack::render_check(&report)?,
                        OutputFormat::Teams => output::teams::render_check(&report)?,
                        OutputFormat::Datadog => output::datadog::render_check(&report)?,
                        // Already handled above:
                        OutputFormat::Json | OutputFormat::Markdown => unreachable!(),
                    }
                }
            }

            let should_fail = fail_on_drift || cfg.fail_on_drift;
            if should_fail && !report.drifts.is_empty() {
                Ok(1)
            } else {
                Ok(0)
            }
        }

        Commands::Graph {
            manifest: manifest_path,
            format,
            team,
            filter,
            output: output_path,
        } => {
            let path = manifest_path.unwrap_or_else(|| manifest::find_default(&root));
            let mut m = manifest::Manifest::load(&path)?;

            // Apply --filter: keep only services whose name contains the substring.
            if let Some(ref pat) = filter {
                let pat_lower = pat.to_lowercase();
                m.services.retain(|s| s.name.to_lowercase().contains(&pat_lower));
            }

            let content = match format {
                GraphFormat::Mermaid => {
                    output::mermaid::render_graph_filtered_string(&m, team.as_deref())
                }
                GraphFormat::Markdown => output::mermaid::render_markdown_table_string(&m),
                GraphFormat::Dot => output::mermaid::render_dot_string(&m, team.as_deref()),
                GraphFormat::Plantuml => {
                    output::mermaid::render_plantuml_string(&m, team.as_deref())
                }
            };

            if let Some(out_path) = output_path {
                std::fs::write(&out_path, &content)?;
                eprintln!("wrote graph to {}", out_path.display());
            } else {
                print!("{}", content);
            }
            Ok(0)
        }

        Commands::Export {
            manifest: manifest_path,
            format,
            ignore: cli_ignore,
            depth,
            since: since_ref,
        } => {
            let path = manifest_path.unwrap_or_else(|| manifest::find_default(&root));
            let mut m = manifest::Manifest::load(&path)?;

            let mut ignore: Vec<String> = cfg.ignore.clone();
            ignore.extend(cli_ignore);

            let discovered = discovery::discover_services_with_opts(&root, &m, &ignore, depth);
            let mut report = drift::analyze(&m, &discovered, &root);
            report.manifest = path.display().to_string();

            // Filter to services that changed since the given git ref
            if let Some(ref git_ref) = since_ref {
                if let Ok(old_m) = since::load_at_ref(&root, &path, git_ref) {
                    let old_map: std::collections::HashMap<String, &manifest::ServiceEntry> =
                        old_m.services.iter().map(|s| (s.name.clone(), s)).collect();
                    m.services.retain(|svc| {
                        if let Some(old_svc) = old_map.get(&svc.name) {
                            svc != *old_svc
                        } else {
                            true // new service
                        }
                    });
                    // Rebuild report with the filtered manifest
                    let discovered2 = discovery::discover_services_with_opts(&root, &m, &ignore, depth);
                    report = drift::analyze(&m, &discovered2, &root);
                    report.manifest = path.display().to_string();
                }
            }

            match format {
                ExportFormat::Json => output::json::render_export(&m, &report)?,
                ExportFormat::Markdown => output::mermaid::render_export_markdown(&m, &report),
                ExportFormat::Csv => output::csv::render_export(&m),
            }
            Ok(0)
        }

        Commands::Init { output, force } => {
            let output_path = output.unwrap_or_else(|| root.join("services.yaml"));
            init::run(&root, output_path, force)?;
            Ok(0)
        }

        Commands::Diff { before, after, format } => {
            let report = diff::diff_snapshots(&before, &after)?;
            match format {
                DiffFormat::Terminal => diff::render_diff(&report),
                DiffFormat::Markdown => diff::render_diff_markdown(&report),
            }
            Ok(0)
        }

        Commands::Watch {
            manifest: manifest_path,
            fail_on_drift,
            team,
            ignore: cli_ignore,
            depth,
            since: watch_since,
            notify,
            interval,
        } => {
            let path = manifest_path.unwrap_or_else(|| manifest::find_default(&root));
            let mut ignore: Vec<String> = cfg.ignore.clone();
            ignore.extend(cli_ignore);

            let initial_errors = watch::run(&path, &root, &ignore, team.as_deref(), depth, watch_since.as_deref(), notify, interval)?;

            let should_fail = fail_on_drift || cfg.fail_on_drift;
            if should_fail && initial_errors > 0 {
                Ok(1)
            } else {
                Ok(0)
            }
        }

        Commands::Report {
            manifest: manifest_path,
            format,
            output: output_path,
            ignore: cli_ignore,
            history,
            badge,
        } => {
            let path = manifest_path.unwrap_or_else(|| manifest::find_default(&root));
            let m = manifest::Manifest::load(&path)?;

            let mut ignore: Vec<String> = cfg.ignore.clone();
            ignore.extend(cli_ignore);

            let discovered = discovery::discover_services_with_ignore(&root, &m, &ignore);
            let mut drift_report = drift::analyze(&m, &discovered, &root);
            drift_report.manifest = path.display().to_string();

            // --badge takes priority: emit a Markdown badge snippet and exit.
            if badge {
                println!("{}", report::render_badge(&drift_report));
                return Ok(0);
            }

            let content = if let Some(n) = history {
                report::render_history_markdown(&root, &path, &discovered, n)?
            } else {
                match format {
                    ReportFormat::Markdown => report::render_markdown(&m, &drift_report),
                    ReportFormat::Html => report::render_html(&m, &drift_report),
                    ReportFormat::Json => report::render_json(&m, &drift_report)?,
                }
            };

            if let Some(out_path) = output_path {
                std::fs::write(&out_path, &content)?;
                eprintln!("wrote report to {}", out_path.display());
            } else {
                print!("{}", content);
            }
            Ok(0)
        }

        Commands::Lint {
            manifest: manifest_path,
        } => {
            let path = manifest_path.unwrap_or_else(|| manifest::find_default(&root));
            let m = manifest::Manifest::load(&path)?;
            let result = lint::run(&m);
            lint::render(&result);
            if result.error_count() > 0 {
                Ok(1)
            } else {
                Ok(0)
            }
        }

        Commands::Import {
            from,
            output: output_path,
            force,
        } => {
            let out = output_path.unwrap_or_else(|| root.join("services.yaml"));
            match from {
                ImportSource::Backstage => import::run_backstage(&root, out, force)?,
                ImportSource::DockerCompose => import::run_docker_compose(&root, out, force)?,
                ImportSource::Openapi => import::run_openapi(&root, out, force)?,
            }
            Ok(0)
        }

        Commands::Fix {
            manifest: manifest_path,
            prune,
            dry_run,
            ignore: cli_ignore,
            depth,
        } => {
            let path = manifest_path.unwrap_or_else(|| manifest::find_default(&root));
            let mut ignore: Vec<String> = cfg.ignore.clone();
            ignore.extend(cli_ignore);
            fix::run(&path, &root, &ignore, depth, prune, dry_run)?;
            Ok(0)
        }

        Commands::InstallHooks { hook, fail_on_drift } => {
            let hook_name = match hook {
                HookKind::PreCommit => "pre-commit",
                HookKind::PrePush => "pre-push",
            };
            hooks::install(&root, hook_name, fail_on_drift)?;
            Ok(0)
        }

        Commands::Policy {
            manifest: manifest_path,
            format,
            fail_on_violations,
        } => {
            let path = manifest_path.unwrap_or_else(|| manifest::find_default(&root));
            let m = manifest::Manifest::load(&path)?;
            let policy_cfg = policy::PolicyConfig::load(&root).unwrap_or_default();
            if policy_cfg.is_empty() {
                eprintln!(
                    "No policy file found. Create .svccat/policy.yaml to define required/recommended fields."
                );
                return Ok(0);
            }
            let result = policy::check(&m, &policy_cfg);
            match format {
                PolicyFormat::Terminal => policy::render_terminal(&result, &policy_cfg),
                PolicyFormat::Json => policy::render_json(&result)?,
            }
            if fail_on_violations && !result.passed() {
                Ok(1)
            } else {
                Ok(0)
            }
        }

        Commands::Snapshot { action } => match action {
            SnapshotAction::Save {
                name,
                manifest: manifest_path,
                ignore: cli_ignore,
                depth,
            } => {
                let path = manifest_path.unwrap_or_else(|| manifest::find_default(&root));
                let m = manifest::Manifest::load(&path)?;
                let mut ignore: Vec<String> = cfg.ignore.clone();
                ignore.extend(cli_ignore);
                let discovered = discovery::discover_services_with_opts(&root, &m, &ignore, depth);
                let mut drift_report = drift::analyze(&m, &discovered, &root);
                drift_report.manifest = path.display().to_string();
                snapshot::save(&root, &name, &m, &drift_report)?;
                Ok(0)
            }
            SnapshotAction::List => {
                let snaps = snapshot::list(&root)?;
                snapshot::render_list(&snaps);
                Ok(0)
            }
            SnapshotAction::Delete { name } => {
                snapshot::delete(&root, &name)?;
                Ok(0)
            }
            SnapshotAction::Diff {
                name,
                ignore: cli_ignore,
                depth,
                format,
            } => {
                // Load the named snapshot as the "before" baseline.
                let snap = snapshot::load(&root, &name)?;

                // Build the current state as the "after" payload.
                let manifest_path = manifest::find_default(&root);
                let m = manifest::Manifest::load(&manifest_path)?;
                let mut ignore: Vec<String> = cfg.ignore.clone();
                ignore.extend(cli_ignore);
                let discovered = discovery::discover_services_with_opts(&root, &m, &ignore, depth);
                let mut current_report = drift::analyze(&m, &discovered, &root);
                current_report.manifest = manifest_path.display().to_string();

                let after_payload = serde_json::json!({
                    "services": m.services,
                    "drift": current_report.drifts,
                });

                let diff_report = diff::diff_from_json(
                    &snap.payload,
                    &after_payload,
                    &name,
                    "current",
                )?;

                match format {
                    DiffFormat::Terminal => diff::render_diff(&diff_report),
                    DiffFormat::Markdown => diff::render_diff_markdown(&diff_report),
                }
                Ok(0)
            }
        },

        Commands::Audit {
            manifest: manifest_path,
            format,
            ping: do_ping,
            ignore: cli_ignore,
            depth,
        } => {
            let path = manifest_path.unwrap_or_else(|| manifest::find_default(&root));
            let mut ignore: Vec<String> = cfg.ignore.clone();
            ignore.extend(cli_ignore);
            let (result, lint_result, drift_report, ping_results) =
                audit::run(&path, &root, &ignore, depth, do_ping)?;
            match format {
                AuditFormat::Terminal => audit::render_terminal(&result, &lint_result, &drift_report, &ping_results),
                AuditFormat::Json => audit::render_json(&result)?,
            }
            if result.passed {
                Ok(0)
            } else {
                Ok(1)
            }
        }

        Commands::Ci {
            manifest: manifest_path,
            ignore: cli_ignore,
            depth,
            format,
        } => {
            let path = manifest_path.unwrap_or_else(|| manifest::find_default(&root));
            let m = manifest::Manifest::load(&path)?;
            let mut ignore: Vec<String> = cfg.ignore.clone();
            ignore.extend(cli_ignore);
            let result = ci::run(&m, &root, &ignore, depth);
            match format {
                CiFormat::Terminal => ci::render_terminal(&result),
                CiFormat::Json => ci::render_json(&result)?,
            }
            if result.passed() { Ok(0) } else { Ok(1) }
        }

        Commands::Search {
            query: query_raw,
            manifest: manifest_path,
        } => {
            let path = manifest_path.unwrap_or_else(|| manifest::find_default(&root));
            let m = manifest::Manifest::load(&path)?;
            let total = m.services.len();
            let q = search::Query::parse(&query_raw);
            let matches = search::run(&m, &q);
            search::render(&matches, &query_raw, total);
            Ok(0)
        }

        Commands::Deps {
            manifest: manifest_path,
            format,
        } => {
            let path = manifest_path.unwrap_or_else(|| manifest::find_default(&root));
            let m = manifest::Manifest::load(&path)?;
            let report = deps::analyze(&m);
            match format {
                DepsFormat::Terminal => deps::render_terminal(&report),
                DepsFormat::Mermaid => deps::render_mermaid(&report),
                DepsFormat::Json => deps::render_json(&report)?,
            }
            if report.has_errors() { Ok(1) } else { Ok(0) }
        }

        Commands::Tag { action } => match action {
            TagAction::Add { service, tag, manifest: manifest_path } => {
                let path = manifest_path.unwrap_or_else(|| manifest::find_default(&root));
                tag::add(&path, &service, &tag)?;
                Ok(0)
            }
            TagAction::Remove { service, tag, manifest: manifest_path } => {
                let path = manifest_path.unwrap_or_else(|| manifest::find_default(&root));
                tag::remove(&path, &service, &tag)?;
                Ok(0)
            }
        },

        Commands::Stats {
            manifest: manifest_path,
        } => {
            let path = manifest_path.unwrap_or_else(|| manifest::find_default(&root));
            let m = manifest::Manifest::load(&path)?;
            stats::run(&m);
            Ok(0)
        }

        Commands::Serve {
            manifest: _manifest_path,
            port,
            refresh,
        } => {
            serve::serve(&root, port, refresh)?;
            Ok(0)
        }

        Commands::Completions { shell } => {
            let mut cmd = Cli::command();
            generate(shell, &mut cmd, "svccat", &mut io::stdout());
            Ok(0)
        }
    }
}