svccat 1.6.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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
use crate::deps_graph;
use crate::discovery;
use crate::drift;
use crate::manifest::Manifest;
use crate::reporting::ReportingConfig;
use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

// ── Configuration ──────────────────────────────────────────────────────────

/// Configuration for a single repository in a workspace.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RepositoryConfig {
    /// Human-readable name for the repository.
    pub name: String,

    /// Path to the repository root (relative to workspace config location).
    pub path: PathBuf,

    /// Path to the manifest file within the repo (relative to repo root).
    #[serde(default = "default_manifest_path")]
    pub manifest: PathBuf,

    /// Whether to include this repo in checks (default: true).
    #[serde(default = "default_enabled")]
    pub enabled: bool,
}

fn default_manifest_path() -> PathBuf {
    PathBuf::from("services.yaml")
}

fn default_enabled() -> bool {
    true
}

/// Workspace configuration containing multiple repositories.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct WorkspaceConfig {
    /// Optional human-readable name for the workspace.
    #[serde(default)]
    pub name: Option<String>,

    /// Optional description of the workspace.
    #[serde(default)]
    pub description: Option<String>,

    /// List of repositories in this workspace.
    pub repos: Vec<RepositoryConfig>,

    /// Reporting defaults from the `[reporting]` section: default output
    /// format, the cross-repo dependency toggle, and discovery exclude globs.
    /// See [`crate::reporting`] for the precedence rules.
    #[serde(default)]
    pub reporting: ReportingConfig,
}

// ── Analysis Results ───────────────────────────────────────────────────────

/// Result of analyzing a single repository.
#[derive(Debug, Clone, Serialize)]
pub struct RepositoryAnalysis {
    pub name: String,
    pub path: PathBuf,
    pub drift: drift::DriftReport,
}

/// Aggregated workspace drift report combining results from all repos.
#[derive(Debug, Clone, Serialize)]
pub struct WorkspaceDriftReport {
    /// Workspace name from the config, when one is set.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workspace_name: Option<String>,

    /// Analyses for each repository (repo_name, analysis).
    pub repos: Vec<RepositoryAnalysis>,

    /// Total declared services across all repos.
    pub total_declared: usize,

    /// Total discovered services across all repos.
    pub total_discovered: usize,

    /// Total errors across all repos.
    pub total_errors: usize,

    /// Total warnings across all repos.
    pub total_warnings: usize,

    /// Dependency graph summary and analysis.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dependency_summary: Option<deps_graph::DependencySummary>,

    /// Circular dependencies detected in the workspace.
    #[serde(default)]
    pub circular_dependencies: Vec<deps_graph::CircularDependency>,

    /// Unresolvable dependencies detected in the workspace.
    #[serde(default)]
    pub unresolvable_dependencies: Vec<deps_graph::UnresolvableDependency>,

    /// The built cross-repo dependency graph's nodes, kept alongside the
    /// summary so renderers (the HTML report's D3 graph) can draw the actual
    /// topology without reloading every manifest and rebuilding the graph a
    /// second time. Empty when `include_cross_repo_deps` is off, matching
    /// [`Self::dependency_summary`]'s "no summary" state.
    #[serde(default)]
    pub dependency_graph_nodes: Vec<deps_graph::GraphNode>,
}

impl WorkspaceDriftReport {
    /// Check if any errors were found across all repos.
    pub fn has_errors(&self) -> bool {
        self.total_errors > 0
    }

    /// Check if any warnings were found across all repos.
    pub fn has_warnings(&self) -> bool {
        self.total_warnings > 0
    }
}

// ── Workspace Context ──────────────────────────────────────────────────────

/// Runtime context for workspace operations.
pub struct WorkspaceContext {
    /// Workspace configuration.
    pub config: WorkspaceConfig,

    /// Root directory where workspace config is located.
    pub workspace_root: PathBuf,

    /// Per-repo manifests and discovered services.
    pub analyses: Vec<RepositoryAnalysis>,
}

// ── Loading & Analysis ────────────────────────────────────────────────────

/// Load workspace configuration from a TOML file.
pub fn load_workspace_config(config_path: &Path) -> Result<(WorkspaceConfig, PathBuf)> {
    let workspace_root = config_path
        .parent()
        .ok_or_else(|| anyhow!("cannot determine workspace root from config path"))?
        .to_path_buf();

    let content = std::fs::read_to_string(config_path).map_err(|e| {
        anyhow!(
            "cannot read workspace config {}: {}",
            config_path.display(),
            e
        )
    })?;

    // Parse TOML and extract workspace section
    let toml: toml::Value =
        toml::from_str(&content).map_err(|e| anyhow!("cannot parse workspace config: {}", e))?;

    let workspace = toml
        .get("workspace")
        .ok_or_else(|| anyhow!("no [workspace] section in config"))?;

    let name = workspace
        .get("name")
        .and_then(|v| v.as_str())
        .map(String::from);

    let description = workspace
        .get("description")
        .and_then(|v| v.as_str())
        .map(String::from);

    let repos: Vec<RepositoryConfig> = workspace
        .get("repos")
        .and_then(|r| r.as_array())
        .ok_or_else(|| anyhow!("workspace.repos must be an array of tables"))?
        .iter()
        .enumerate()
        .map(|(idx, repo)| {
            let repo_table = repo
                .as_table()
                .ok_or_else(|| anyhow!("workspace.repos[{}] must be a table", idx))?;

            let name = repo_table
                .get("name")
                .and_then(|v| v.as_str())
                .ok_or_else(|| anyhow!("workspace.repos[{}].name is required", idx))?
                .to_string();

            let path = repo_table
                .get("path")
                .and_then(|v| v.as_str())
                .ok_or_else(|| anyhow!("workspace.repos[{}].path is required", idx))
                .map(PathBuf::from)?;

            let manifest = repo_table
                .get("manifest")
                .and_then(|v| v.as_str())
                .map(PathBuf::from)
                .unwrap_or_else(default_manifest_path);

            let enabled = repo_table
                .get("enabled")
                .and_then(|v| v.as_bool())
                .unwrap_or_else(default_enabled);

            Ok(RepositoryConfig {
                name,
                path,
                manifest,
                enabled,
            })
        })
        .collect::<Result<Vec<_>>>()?;

    if repos.is_empty() {
        return Err(anyhow!("workspace must have at least one repository"));
    }

    // Parse the optional [reporting] defaults. Validation lives in the
    // `reporting` module so the CLI and the config agree on accepted values.
    let reporting = crate::reporting::parse(toml.get("reporting"))?;

    Ok((
        WorkspaceConfig {
            name,
            description,
            repos,
            reporting,
        },
        workspace_root,
    ))
}

/// Restrict a workspace configuration to the repositories named in a
/// comma-separated filter, as passed to `workspace check --filter`.
///
/// Names are matched exactly after trimming surrounding whitespace, and empty
/// segments are ignored. Naming a repository that does not exist in the config
/// is an error, so a typo cannot silently shrink the workspace. Filtering only
/// selects among configured repos; a repo with `enabled = false` is still
/// skipped by analysis even when named here.
pub fn filter_repos(config: &WorkspaceConfig, filter: &str) -> Result<WorkspaceConfig> {
    let requested: Vec<&str> = filter
        .split(',')
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .collect();

    if requested.is_empty() {
        return Err(anyhow!(
            "--filter must name at least one repository (comma-separated names)"
        ));
    }

    let unknown: Vec<&str> = requested
        .iter()
        .copied()
        .filter(|name| !config.repos.iter().any(|r| r.name == *name))
        .collect();

    if !unknown.is_empty() {
        let available: Vec<&str> = config.repos.iter().map(|r| r.name.as_str()).collect();
        return Err(anyhow!(
            "unknown repository name(s) in --filter: {} (available: {})",
            unknown.join(", "),
            available.join(", ")
        ));
    }

    let repos = config
        .repos
        .iter()
        .filter(|r| requested.contains(&r.name.as_str()))
        .cloned()
        .collect();

    Ok(WorkspaceConfig {
        name: config.name.clone(),
        description: config.description.clone(),
        repos,
        reporting: config.reporting.clone(),
    })
}

/// Analyze a single repository.
fn analyze_repository(
    repo_config: &RepositoryConfig,
    workspace_root: &Path,
    extra_ignore: &[String],
    depth: u32,
) -> Result<RepositoryAnalysis> {
    // Resolve repo path relative to workspace root
    let repo_root = if repo_config.path.is_absolute() {
        repo_config.path.clone()
    } else {
        workspace_root.join(&repo_config.path)
    };

    if !repo_root.exists() {
        return Err(anyhow!(
            "repository '{}' path does not exist: {}",
            repo_config.name,
            repo_root.display()
        ));
    }

    // Resolve manifest path relative to repo root
    let manifest_path = repo_root.join(&repo_config.manifest);

    // Load manifest
    let manifest = Manifest::load(&manifest_path).map_err(|e| {
        anyhow!(
            "failed to load manifest for repository '{}': {}",
            repo_config.name,
            e
        )
    })?;

    // Discover services
    let discovered =
        discovery::discover_services_with_opts(&repo_root, &manifest, extra_ignore, depth);

    // Analyze drift
    let mut drift_report = drift::analyze(&manifest, &discovered, &repo_root);
    drift_report.manifest = manifest_path.display().to_string();

    Ok(RepositoryAnalysis {
        name: repo_config.name.clone(),
        path: repo_root,
        drift: drift_report,
    })
}

/// Outcome of cross-repo dependency analysis, or its absence.
///
/// [`CrossRepoAnalysis::default()`] is the "no dependency analysis ran" state:
/// no summary, no circular or unresolvable dependencies. It is what the toggle
/// leaves behind when cross-repo analysis is switched off.
#[derive(Default)]
struct CrossRepoAnalysis {
    summary: Option<deps_graph::DependencySummary>,
    circular: Vec<deps_graph::CircularDependency>,
    unresolvable: Vec<deps_graph::UnresolvableDependency>,
    nodes: Vec<deps_graph::GraphNode>,
}

/// Reload each enabled repo's manifest and run the cross-repo dependency graph.
///
/// This is where the `include_cross_repo_deps` toggle earns its keep: the
/// caller only invokes this function when the toggle is on, so when it is off
/// the manifest reloads *and* the graph build below never happen. The toggle
/// removes work rather than hiding output; the alternative (build the graph,
/// then drop it before rendering) would pay the full cost for nothing, which
/// defeats the point of a cost knob.
fn analyze_cross_repo_dependencies(
    config: &WorkspaceConfig,
    workspace_root: &Path,
) -> CrossRepoAnalysis {
    // The manifests are reloaded here (rather than threaded out of the per-repo
    // drift pass) so this whole block is self-contained and trivially skippable.
    let manifests: Vec<(String, Manifest)> = config
        .repos
        .iter()
        .filter(|repo| repo.enabled)
        .filter_map(|repo| {
            let manifest_path = workspace_root.join(&repo.path).join(&repo.manifest);
            Manifest::load(&manifest_path)
                .ok()
                .map(|manifest| (repo.name.clone(), manifest))
        })
        .collect();

    if manifests.is_empty() {
        return CrossRepoAnalysis::default();
    }

    let manifest_refs: Vec<(String, &Manifest)> = manifests
        .iter()
        .map(|(name, manifest)| (name.clone(), manifest))
        .collect();

    match deps_graph::DependencyGraph::build(manifest_refs) {
        Ok(graph) => CrossRepoAnalysis {
            summary: Some(graph.summary()),
            circular: graph.circular_dependencies.clone(),
            unresolvable: graph.validate_all_dependencies(),
            nodes: graph.nodes.values().cloned().collect(),
        },
        Err(e) => {
            eprintln!("⚠️  Warning: Failed to analyze dependencies: {}", e);
            CrossRepoAnalysis::default()
        }
    }
}

/// Load and analyze all repositories in a workspace.
pub fn analyze_workspace(
    config: &WorkspaceConfig,
    workspace_root: &Path,
    extra_ignore: &[String],
    depth: u32,
) -> Result<WorkspaceDriftReport> {
    let mut analyses = Vec::new();
    let mut total_declared = 0;
    let mut total_discovered = 0;
    let mut total_errors = 0;
    let mut total_warnings = 0;

    // Merge the reporting `exclude_patterns` into the discovery ignore globs.
    // This reuses the existing glob machinery in `discovery`: the merged list
    // is compiled there alongside each manifest's own `discovery.ignore`, so an
    // exclude pattern behaves exactly like a `--ignore` flag.
    let effective_ignore = config.reporting.merged_ignore(extra_ignore);

    // Analyze each enabled repository.
    for repo_config in &config.repos {
        if !repo_config.enabled {
            eprintln!("⏭️  Skipping disabled repository: {}", repo_config.name);
            continue;
        }

        match analyze_repository(repo_config, workspace_root, &effective_ignore, depth) {
            Ok(analysis) => {
                total_declared += analysis.drift.declared;
                total_discovered += analysis.drift.discovered;
                total_errors += analysis.drift.error_count();
                total_warnings += analysis.drift.warning_count();
                analyses.push(analysis);
            }
            Err(e) => {
                eprintln!(
                    "❌ Error analyzing repository '{}': {}",
                    repo_config.name, e
                );
                return Err(e);
            }
        }
    }

    // Cross-repo dependency analysis is only started when the toggle is on, so
    // switching it off skips the manifest reloads and graph build entirely.
    let deps = if config.reporting.include_cross_repo_deps {
        analyze_cross_repo_dependencies(config, workspace_root)
    } else {
        CrossRepoAnalysis::default()
    };

    Ok(WorkspaceDriftReport {
        workspace_name: config.name.clone(),
        repos: analyses,
        total_declared,
        total_discovered,
        total_errors,
        total_warnings,
        dependency_summary: deps.summary,
        circular_dependencies: deps.circular,
        unresolvable_dependencies: deps.unresolvable,
        dependency_graph_nodes: deps.nodes,
    })
}

// ── Utilities ──────────────────────────────────────────────────────────────

/// Find workspace configuration starting from a given directory.
/// Searches for svccat.toml and checks if it contains a [workspace] section.
pub fn find_workspace_config(root: &Path) -> Option<PathBuf> {
    let config_file = root.join("svccat.toml");

    if config_file.exists() {
        if let Ok(content) = std::fs::read_to_string(&config_file) {
            if let Ok(toml) = content.parse::<toml::Value>() {
                if toml.get("workspace").is_some() {
                    return Some(config_file);
                }
            }
        }
    }

    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::OutputFormat;
    use tempfile::TempDir;

    fn repo(name: &str) -> RepositoryConfig {
        RepositoryConfig {
            name: name.to_string(),
            path: PathBuf::from(name),
            manifest: PathBuf::from("services.yaml"),
            enabled: true,
        }
    }

    fn sample_config() -> WorkspaceConfig {
        WorkspaceConfig {
            name: Some("Platform".to_string()),
            description: Some("Multi-service platform".to_string()),
            repos: vec![repo("alpha"), repo("beta")],
            reporting: ReportingConfig::default(),
        }
    }

    fn write_config(dir: &TempDir, content: &str) -> PathBuf {
        let path = dir.path().join("svccat.toml");
        std::fs::write(&path, content).unwrap();
        path
    }

    #[test]
    fn load_parses_workspace_name_and_description() {
        let dir = TempDir::new().unwrap();
        let path = write_config(
            &dir,
            r#"
[workspace]
name = "Platform Engineering"
description = "Multi-service platform"
repos = [{ name = "api", path = "api-repo" }]
"#,
        );

        let (config, root) = load_workspace_config(&path).unwrap();
        assert_eq!(config.name.as_deref(), Some("Platform Engineering"));
        assert_eq!(
            config.description.as_deref(),
            Some("Multi-service platform")
        );
        assert_eq!(config.repos.len(), 1);
        assert_eq!(root, dir.path());
    }

    #[test]
    fn load_defaults_name_and_description_to_none() {
        let dir = TempDir::new().unwrap();
        let path = write_config(
            &dir,
            r#"
[workspace]
repos = [{ name = "api", path = "api-repo" }]
"#,
        );

        let (config, _) = load_workspace_config(&path).unwrap();
        assert_eq!(config.name, None);
        assert_eq!(config.description, None);
    }

    #[test]
    fn filter_selects_single_repo() {
        let filtered = filter_repos(&sample_config(), "beta").unwrap();
        assert_eq!(filtered.repos.len(), 1);
        assert_eq!(filtered.repos[0].name, "beta");
        // Workspace metadata is preserved through filtering.
        assert_eq!(filtered.name.as_deref(), Some("Platform"));
    }

    #[test]
    fn filter_trims_whitespace_and_keeps_config_order() {
        // Requested in reverse order with stray whitespace; config order wins.
        let filtered = filter_repos(&sample_config(), " beta , alpha ").unwrap();
        let names: Vec<&str> = filtered.repos.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(names, vec!["alpha", "beta"]);
    }

    #[test]
    fn filter_ignores_duplicate_names() {
        let filtered = filter_repos(&sample_config(), "alpha,alpha").unwrap();
        assert_eq!(filtered.repos.len(), 1);
        assert_eq!(filtered.repos[0].name, "alpha");
    }

    #[test]
    fn filter_rejects_unknown_repo_names() {
        let err = filter_repos(&sample_config(), "alpha,nope").unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("nope"),
            "message should name the unknown repo: {msg}"
        );
        assert!(
            msg.contains("alpha") && msg.contains("beta"),
            "message should list available repos: {msg}"
        );
    }

    #[test]
    fn filter_rejects_empty_filter() {
        assert!(filter_repos(&sample_config(), "").is_err());
        assert!(filter_repos(&sample_config(), " , ").is_err());
    }

    // The exhaustive parsing, validation, precedence, and glob-merge tests for
    // [reporting] live in `crate::reporting`. The tests here only confirm the
    // section is wired through `load_workspace_config` and survives filtering.

    #[test]
    fn load_defaults_reporting_when_section_absent() {
        let dir = TempDir::new().unwrap();
        let path = write_config(
            &dir,
            r#"
[workspace]
repos = [{ name = "api", path = "api-repo" }]
"#,
        );

        let (config, _) = load_workspace_config(&path).unwrap();
        assert_eq!(config.reporting, ReportingConfig::default());
    }

    #[test]
    fn load_wires_reporting_section_into_config() {
        let dir = TempDir::new().unwrap();
        let path = write_config(
            &dir,
            r#"
[workspace]
repos = [{ name = "api", path = "api-repo" }]

[reporting]
format = "json"
include_cross_repo_deps = false
exclude_patterns = ["examples/*", "vendor"]
"#,
        );

        let (config, _) = load_workspace_config(&path).unwrap();
        assert_eq!(config.reporting.format, Some(OutputFormat::Json));
        assert!(!config.reporting.include_cross_repo_deps);
        assert_eq!(
            config.reporting.exclude_patterns,
            vec!["examples/*".to_string(), "vendor".to_string()]
        );
    }

    #[test]
    fn load_rejects_bad_reporting_value() {
        // Validation happens during load, so a mistyped format fails the whole
        // config load rather than silently producing the wrong output later.
        let dir = TempDir::new().unwrap();
        let path = write_config(
            &dir,
            r#"
[workspace]
repos = [{ name = "api", path = "api-repo" }]

[reporting]
format = "jsonn"
"#,
        );

        assert!(load_workspace_config(&path).is_err());
    }

    #[test]
    fn filter_repos_preserves_reporting() {
        let mut config = sample_config();
        config.reporting = ReportingConfig {
            format: Some(OutputFormat::Json),
            include_cross_repo_deps: false,
            exclude_patterns: vec!["vendor".to_string()],
        };

        let filtered = filter_repos(&config, "alpha").unwrap();
        assert_eq!(filtered.reporting, config.reporting);
    }
}