cargo-arc 0.2.1

Visualize crate and module dependencies in Cargo workspaces
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
//! Workspace analysis using cargo metadata.

use super::filtering::{DepInfo, collect_reachable_crates, find_seed_crates};
use super::hir::FeatureConfig;
use crate::model::{CrateInfo, WorkspaceCrates, normalize_crate_name};
use anyhow::{Context, Result};
use cargo_metadata::MetadataCommand;
use std::collections::HashSet;
use std::path::Path;
use tracing::debug;

// ============================================================================
// Workspace Analysis Helpers
// ============================================================================

/// Context built from cargo metadata for workspace analysis.
struct WorkspaceContext<'a> {
    pkg_id_to_name: std::collections::HashMap<&'a str, &'a str>,
    workspace_member_ids: HashSet<&'a str>,
    workspace_member_names: WorkspaceCrates,
}

/// Runs cargo metadata with the given feature configuration.
fn run_cargo_metadata(
    manifest_path: &Path,
    feature_config: &FeatureConfig,
) -> Result<cargo_metadata::Metadata> {
    let mut cmd = MetadataCommand::new();
    cmd.manifest_path(manifest_path);

    if feature_config.all_features {
        cmd.features(cargo_metadata::CargoOpt::AllFeatures);
    } else if !feature_config.features.is_empty() {
        cmd.features(cargo_metadata::CargoOpt::SomeFeatures(
            feature_config.features.clone(),
        ));
    }
    if feature_config.no_default_features {
        cmd.features(cargo_metadata::CargoOpt::NoDefaultFeatures);
    }

    cmd.exec().context("Failed to run cargo metadata")
}

/// Builds workspace context from cargo metadata.
fn build_workspace_context(metadata: &cargo_metadata::Metadata) -> WorkspaceContext<'_> {
    let pkg_id_to_name = metadata
        .packages
        .iter()
        .map(|p| (p.id.repr.as_str(), p.name.as_str()))
        .collect();

    let workspace_member_ids = metadata
        .workspace_members
        .iter()
        .map(|id| id.repr.as_str())
        .collect();

    let workspace_member_names: WorkspaceCrates = metadata
        .workspace_packages()
        .iter()
        .map(|p| p.name.as_str())
        .collect();

    WorkspaceContext {
        pkg_id_to_name,
        workspace_member_ids,
        workspace_member_names,
    }
}

type DepsMap = std::collections::HashMap<String, Vec<String>>;

/// Builds resolved dependencies maps from cargo metadata resolve section.
/// Returns (production deps, dev deps) as separate maps.
fn build_resolved_deps(
    resolve: &cargo_metadata::Resolve,
    ctx: &WorkspaceContext<'_>,
) -> (DepsMap, DepsMap) {
    let mut prod_deps = std::collections::HashMap::new();
    let mut dev_deps = std::collections::HashMap::new();

    debug!(workspace_members = ?ctx.workspace_member_names, "building resolved_deps");

    for node in &resolve.nodes {
        let node_id = node.id.repr.as_str();
        if !ctx.workspace_member_ids.contains(node_id) {
            continue;
        }

        let pkg_name = ctx.pkg_id_to_name.get(node_id).copied().unwrap_or("?");
        debug!(pkg = pkg_name, "processing deps");

        let mut prod: Vec<String> = Vec::new();
        let mut dev: Vec<String> = Vec::new();

        for dep in &node.deps {
            let info = DepInfo::from_node_dep(dep, &ctx.workspace_member_names);
            debug!(name = info.name, kind = ?info.kind, scope = ?info.scope);
            if info.is_included() {
                prod.push(info.name.to_string());
            } else if info.is_dev_workspace() {
                dev.push(info.name.to_string());
            }
        }

        if let Some(pkg_name) = ctx.pkg_id_to_name.get(node_id) {
            let normalized_name = normalize_crate_name(pkg_name);
            prod_deps.insert(normalized_name.clone(), prod);
            dev_deps.insert(normalized_name, dev);
        }
    }

    (prod_deps, dev_deps)
}

/// Determines if a crate should be included based on feature config and reachability.
fn should_include_crate(
    pkg: &cargo_metadata::Package,
    reachable: &HashSet<String>,
    feature_config: &FeatureConfig,
) -> bool {
    let features_empty = feature_config.features.is_empty();
    let all_features = feature_config.all_features;
    let in_reachable = reachable.contains(&normalize_crate_name(&pkg.name));
    let include = features_empty || all_features || in_reachable;

    debug!(
        crate_name = %pkg.name,
        features_empty,
        all_features,
        in_reachable,
        include
    );

    include
}

/// Builds a `CrateInfo` from a package and its resolved dependencies.
fn build_crate_info(
    pkg: &cargo_metadata::Package,
    prod_deps: &DepsMap,
    dev_deps: &DepsMap,
) -> CrateInfo {
    let normalized_name = normalize_crate_name(&pkg.name);
    let dependencies = prod_deps.get(&normalized_name).cloned().unwrap_or_default();
    let dev_dependencies = dev_deps.get(&normalized_name).cloned().unwrap_or_default();

    CrateInfo {
        name: pkg.name.to_string(),
        path: pkg.manifest_path.parent().unwrap().into(),
        dependencies,
        dev_dependencies,
    }
}

/// Filters and builds `CrateInfo` list from workspace packages.
fn build_filtered_crates(
    metadata: &cargo_metadata::Metadata,
    prod_deps: &DepsMap,
    dev_deps: &DepsMap,
    feature_config: &FeatureConfig,
    workspace_member_names: &WorkspaceCrates,
) -> Vec<CrateInfo> {
    let seeds = find_seed_crates(metadata, feature_config, workspace_member_names);

    if seeds.is_empty() && !feature_config.features.is_empty() {
        eprintln!(
            "warning: No workspace crates define feature(s): {}",
            feature_config.features.join(", ")
        );
    }

    let reachable = collect_reachable_crates(seeds, prod_deps, workspace_member_names);

    debug!(
        features_empty = feature_config.features.is_empty(),
        all_features = feature_config.all_features,
        "final crate filtering"
    );

    // Without --include-tests, dev-dependencies should not produce graph edges.
    // Pass an empty map so CrateInfo.dev_dependencies stays empty.
    let empty_dev_deps = DepsMap::new();
    let effective_dev_deps = if feature_config.include_tests {
        dev_deps
    } else {
        &empty_dev_deps
    };

    let crates: Vec<CrateInfo> = metadata
        .workspace_packages()
        .into_iter()
        .filter(|pkg| should_include_crate(pkg, &reachable, feature_config))
        .map(|pkg| build_crate_info(pkg, prod_deps, effective_dev_deps))
        .collect();

    debug!(crate_count = crates.len(), "final result");
    for c in &crates {
        debug!(crate_name = %c.name, deps = ?c.dependencies);
    }

    crates
}

/// Analyzes a workspace and returns all member crates.
/// `manifest_path` should point to a Cargo.toml.
/// `feature_config` controls which features are activated for dependency resolution.
#[allow(clippy::missing_errors_doc)]
pub fn analyze_workspace(
    manifest_path: &Path,
    feature_config: &FeatureConfig,
) -> Result<Vec<CrateInfo>> {
    let metadata = run_cargo_metadata(manifest_path, feature_config)?;

    let resolve = metadata
        .resolve
        .as_ref()
        .context("No resolve section in cargo metadata")?;

    let ctx = build_workspace_context(&metadata);
    let (prod_deps, dev_deps) = build_resolved_deps(resolve, &ctx);
    let crates = build_filtered_crates(
        &metadata,
        &prod_deps,
        &dev_deps,
        feature_config,
        &ctx.workspace_member_names,
    );

    Ok(crates)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::Path;

    mod integration_tests {
        use super::*;

        /// Resolved dependency from cargo metadata's resolve section (test-only).
        #[derive(Debug, Clone)]
        struct ResolvedDependency {
            name: String,
            #[allow(dead_code)]
            pkg_id: String,
            dep_kinds: Vec<ResolvedDepKind>,
        }

        /// Dependency kind info from resolve section (test-only).
        #[derive(Debug, Clone)]
        struct ResolvedDepKind {
            kind: Option<String>,
            #[allow(dead_code)]
            target: Option<String>,
        }

        #[test]
        fn test_resolved_dependency_construction() {
            let dep = ResolvedDependency {
                name: "core".to_string(),
                pkg_id: "core 0.1.0 (path+file:///workspace/core)".to_string(),
                dep_kinds: vec![ResolvedDepKind {
                    kind: None,
                    target: None,
                }],
            };
            assert_eq!(dep.name, "core");
            assert_eq!(dep.dep_kinds.len(), 1);
            assert!(dep.dep_kinds[0].kind.is_none());
        }

        #[test]
        fn test_analyze_workspace_self() {
            let manifest = Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
            let crates =
                analyze_workspace(&manifest, &FeatureConfig::default()).expect("should analyze");

            assert!(!crates.is_empty());
            let cargo_arc = crates.iter().find(|c| c.name == "cargo-arc");
            assert!(cargo_arc.is_some(), "should find cargo-arc");
        }

        #[test]
        fn test_crate_info_fields() {
            let manifest = Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
            let crates =
                analyze_workspace(&manifest, &FeatureConfig::default()).expect("should analyze");

            let cargo_arc = crates.iter().find(|c| c.name == "cargo-arc").unwrap();
            assert!(cargo_arc.path.exists(), "path should exist");
        }
    }

    mod feature_tests {
        use super::*;

        fn feature_test_manifest() -> std::path::PathBuf {
            Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("tests/fixtures/feature_test_workspace/Cargo.toml")
        }

        #[test]
        fn test_feature_filtering_shows_all_crates() {
            let manifest = feature_test_manifest();
            let crates =
                analyze_workspace(&manifest, &FeatureConfig::default()).expect("should analyze");

            let names: Vec<&str> = crates.iter().map(|c| c.name.as_str()).collect();
            assert!(names.contains(&"core"), "should have core");
            assert!(names.contains(&"core-utils"), "should have core-utils");
            assert!(names.contains(&"server-utils"), "should have server-utils");
            assert!(names.contains(&"web-utils"), "should have web-utils");
        }

        #[test]
        fn test_feature_filtering_core_utils_depends_on_core() {
            let manifest = feature_test_manifest();
            let crates =
                analyze_workspace(&manifest, &FeatureConfig::default()).expect("should analyze");

            let core_utils = crates.iter().find(|c| c.name == "core-utils").unwrap();
            assert!(
                core_utils.dependencies.contains(&"core".to_string()),
                "core-utils should depend on core, got: {:?}",
                core_utils.dependencies
            );
        }

        #[test]
        fn test_feature_filtering_server_without_feature() {
            let manifest = feature_test_manifest();
            let crates =
                analyze_workspace(&manifest, &FeatureConfig::default()).expect("should analyze");

            let server_utils = crates.iter().find(|c| c.name == "server-utils").unwrap();
            assert!(
                !server_utils.dependencies.contains(&"core".to_string()),
                "server-utils should NOT depend on core without feature, got: {:?}",
                server_utils.dependencies
            );
        }

        #[test]
        fn test_feature_filtering_server_with_feature() {
            let manifest = feature_test_manifest();
            let config = FeatureConfig {
                features: vec!["server-utils/server".to_string()],
                ..Default::default()
            };
            let crates = analyze_workspace(&manifest, &config).expect("should analyze");

            let server_utils = crates.iter().find(|c| c.name == "server-utils").unwrap();
            assert!(
                server_utils.dependencies.contains(&"core".to_string()),
                "server-utils SHOULD depend on core with server feature, got: {:?}",
                server_utils.dependencies
            );
        }

        #[test]
        fn test_feature_filtering_web_with_feature() {
            let manifest = feature_test_manifest();
            let config = FeatureConfig {
                features: vec!["web-utils/web".to_string()],
                ..Default::default()
            };
            let crates = analyze_workspace(&manifest, &config).expect("should analyze");

            let web_utils = crates.iter().find(|c| c.name == "web-utils").unwrap();
            assert!(
                web_utils.dependencies.contains(&"core".to_string()),
                "web-utils SHOULD depend on core with web feature, got: {:?}",
                web_utils.dependencies
            );
        }

        #[test]
        fn test_node_id_matching_substring_names() {
            let manifest = feature_test_manifest();
            let crates =
                analyze_workspace(&manifest, &FeatureConfig::default()).expect("should analyze");

            let core = crates.iter().find(|c| c.name == "core").unwrap();
            let core_utils = crates.iter().find(|c| c.name == "core-utils").unwrap();

            assert!(
                core.dependencies.is_empty(),
                "core should have no deps, got: {:?}",
                core.dependencies
            );

            assert!(
                core_utils.dependencies.contains(&"core".to_string()),
                "core-utils should depend on core, got: {:?}",
                core_utils.dependencies
            );
            assert!(
                core_utils.dependencies.contains(&"shared_lib".to_string()),
                "core-utils should depend on shared-lib (normalized: shared_lib), got: {:?}",
                core_utils.dependencies
            );
            assert_eq!(
                core_utils.dependencies.len(),
                2,
                "core-utils should have exactly 2 deps"
            );
        }

        #[test]
        fn test_feature_filtering_web_only_filters_crates() {
            let manifest = feature_test_manifest();
            let config = FeatureConfig {
                features: vec!["web".to_string()],
                ..Default::default()
            };
            let crates = analyze_workspace(&manifest, &config).expect("should analyze");

            let names: Vec<&str> = crates.iter().map(|c| c.name.as_str()).collect();
            assert!(
                names.contains(&"web-utils"),
                "should have web-utils, got: {names:?}"
            );
            assert!(
                names.contains(&"core"),
                "should have core (dependency), got: {names:?}"
            );
            assert!(
                names.contains(&"testlib"),
                "should have testlib (normal dep of web-utils), got: {names:?}"
            );
            assert!(
                !names.contains(&"server-utils"),
                "should NOT have server-utils, got: {names:?}"
            );
            assert!(
                !names.contains(&"core-utils"),
                "should NOT have core-utils, got: {names:?}"
            );
            assert_eq!(names.len(), 3, "expected 3 crates, got: {names:?}");
        }

        #[test]
        fn test_feature_filtering_server_only_filters_crates() {
            let manifest = feature_test_manifest();
            let config = FeatureConfig {
                features: vec!["server".to_string()],
                ..Default::default()
            };
            let crates = analyze_workspace(&manifest, &config).expect("should analyze");

            let names: Vec<&str> = crates.iter().map(|c| c.name.as_str()).collect();
            assert!(
                names.contains(&"server-utils"),
                "should have server-utils, got: {names:?}"
            );
            assert!(
                names.contains(&"core"),
                "should have core (dependency), got: {names:?}"
            );
            assert!(
                !names.contains(&"web-utils"),
                "should NOT have web-utils, got: {names:?}"
            );
            assert!(
                !names.contains(&"core-utils"),
                "should NOT have core-utils, got: {names:?}"
            );
            assert_eq!(names.len(), 2, "expected 2 crates, got: {names:?}");
        }

        #[test]
        fn test_feature_filtering_unknown_feature_returns_error() {
            let manifest = feature_test_manifest();
            let config = FeatureConfig {
                features: vec!["nonexistent".to_string()],
                ..Default::default()
            };
            let result = analyze_workspace(&manifest, &config);

            assert!(
                result.is_err(),
                "unknown feature should cause cargo metadata to fail"
            );
        }

        #[test]
        fn test_feature_filtering_all_features_shows_all() {
            let manifest = feature_test_manifest();
            let config = FeatureConfig {
                all_features: true,
                ..Default::default()
            };
            let crates = analyze_workspace(&manifest, &config).expect("should analyze");

            let names: Vec<&str> = crates.iter().map(|c| c.name.as_str()).collect();
            assert!(names.contains(&"core"), "should have core");
            assert!(names.contains(&"core-utils"), "should have core-utils");
            assert!(names.contains(&"server-utils"), "should have server-utils");
            assert!(names.contains(&"web-utils"), "should have web-utils");
            assert!(names.contains(&"testlib"), "should have testlib");
            assert!(names.contains(&"shared-lib"), "should have shared-lib");
            assert!(names.contains(&"build-helper"), "should have build-helper");
            assert_eq!(names.len(), 7, "expected all 7 crates, got: {names:?}");
        }
    }
}