cargo-coupling 0.3.7

A coupling analysis tool for Rust projects - measuring the 'right distance' in your code
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
//! Workspace analysis using cargo metadata
//!
//! This module uses `cargo metadata` to understand the project structure,
//! including workspace members, dependencies, and module organization.

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

use cargo_metadata::{Metadata, MetadataCommand, PackageId, TargetKind};
use thiserror::Error;

/// Errors that can occur during workspace analysis
#[derive(Error, Debug)]
pub enum WorkspaceError {
    #[error("Failed to run cargo metadata: {0}")]
    MetadataError(#[from] cargo_metadata::Error),

    #[error("Package not found: {0}")]
    PackageNotFound(String),

    #[error("Invalid manifest path: {0}")]
    InvalidManifest(String),
}

/// Information about a crate in the workspace
#[derive(Debug, Clone)]
pub struct CrateInfo {
    /// Crate name
    pub name: String,
    /// Package ID for dependency resolution
    pub id: PackageId,
    /// Kept as `<manifest_dir>/src` for backward compatibility; internals use `source_roots`.
    pub src_path: PathBuf,
    /// Directories containing analyzable target roots.
    pub source_roots: Vec<PathBuf>,
    /// Target root source files, such as lib.rs or main.rs equivalents.
    pub crate_roots: Vec<PathBuf>,
    /// Path to Cargo.toml
    pub manifest_path: PathBuf,
    /// Direct dependencies (crate names)
    pub dependencies: Vec<String>,
    /// Dev dependencies
    pub dev_dependencies: Vec<String>,
    /// Is this a workspace member?
    pub is_workspace_member: bool,
}

/// Information about the entire workspace
#[derive(Debug)]
pub struct WorkspaceInfo {
    /// Root directory of the workspace
    pub root: PathBuf,
    /// All crates in the workspace
    pub crates: HashMap<String, CrateInfo>,
    /// Workspace members (crate names)
    pub members: Vec<String>,
    /// Dependency graph: crate name -> dependencies
    pub dependency_graph: HashMap<String, HashSet<String>>,
    /// Reverse dependency graph: crate name -> dependents
    pub reverse_deps: HashMap<String, HashSet<String>>,
}

impl WorkspaceInfo {
    /// Analyze a workspace from a path
    pub fn from_path(path: &Path) -> Result<Self, WorkspaceError> {
        // Find Cargo.toml
        let manifest_path = find_cargo_toml(path)?;

        // Run cargo metadata
        let metadata = MetadataCommand::new()
            .manifest_path(&manifest_path)
            .exec()?;

        Self::from_metadata(metadata)
    }

    /// Create workspace info from cargo metadata
    pub fn from_metadata(metadata: Metadata) -> Result<Self, WorkspaceError> {
        let root = metadata.workspace_root.as_std_path().to_path_buf();

        let mut crates = HashMap::new();
        let mut members = Vec::new();
        let mut dependency_graph: HashMap<String, HashSet<String>> = HashMap::new();
        let mut reverse_deps: HashMap<String, HashSet<String>> = HashMap::new();

        // Collect workspace members
        let workspace_member_ids: HashSet<_> = metadata.workspace_members.iter().collect();

        // Process all packages
        for package in &metadata.packages {
            let is_workspace_member = workspace_member_ids.contains(&package.id);
            let package_name = package.name.to_string();

            if is_workspace_member {
                members.push(package_name.clone());
            }

            let manifest_dir = package
                .manifest_path
                .parent()
                .map(|p| p.as_std_path().to_path_buf())
                .unwrap_or_default();
            let fallback_src_path = manifest_dir.join("src");
            let crate_roots = package
                .targets
                .iter()
                .filter(|target| target.kind.iter().any(is_analyzable_target_kind))
                .map(|target| target.src_path.as_std_path().to_path_buf())
                .collect::<Vec<_>>();
            let mut source_roots = crate_roots
                .iter()
                .filter_map(|src_path| src_path.parent().map(Path::to_path_buf))
                .collect::<Vec<_>>();

            source_roots = dedupe_contained_roots(source_roots);

            if source_roots.is_empty() && fallback_src_path.exists() {
                source_roots.push(fallback_src_path.clone());
            }
            let src_path = fallback_src_path.clone();

            // Collect dependencies
            let mut deps = Vec::new();
            let mut dev_deps = Vec::new();

            for dep in &package.dependencies {
                if dep.kind == cargo_metadata::DependencyKind::Development {
                    dev_deps.push(dep.name.clone());
                } else {
                    deps.push(dep.name.clone());
                }

                // Build dependency graph
                dependency_graph
                    .entry(package_name.clone())
                    .or_default()
                    .insert(dep.name.clone());

                // Build reverse dependency graph
                reverse_deps
                    .entry(dep.name.clone())
                    .or_default()
                    .insert(package_name.clone());
            }

            let crate_info = CrateInfo {
                name: package_name.clone(),
                id: package.id.clone(),
                src_path,
                source_roots,
                crate_roots: dedupe_paths(crate_roots),
                manifest_path: package.manifest_path.as_std_path().to_path_buf(),
                dependencies: deps,
                dev_dependencies: dev_deps,
                is_workspace_member,
            };

            crates.insert(package_name, crate_info);
        }

        Ok(Self {
            root,
            crates,
            members,
            dependency_graph,
            reverse_deps,
        })
    }

    /// Get a crate by name
    pub fn get_crate(&self, name: &str) -> Option<&CrateInfo> {
        self.crates.get(name)
    }

    /// Check if a crate is a workspace member
    pub fn is_workspace_member(&self, name: &str) -> bool {
        self.members.contains(&name.to_string())
    }

    /// Get direct dependencies of a crate
    pub fn get_dependencies(&self, name: &str) -> Option<&HashSet<String>> {
        self.dependency_graph.get(name)
    }

    /// Get crates that depend on this crate
    pub fn get_dependents(&self, name: &str) -> Option<&HashSet<String>> {
        self.reverse_deps.get(name)
    }

    /// Calculate the distance between two crates
    /// Returns None if there's no path, 0 if same crate, 1 for direct dep, etc.
    pub fn crate_distance(&self, from: &str, to: &str) -> Option<usize> {
        if from == to {
            return Some(0);
        }

        // Direct dependency check
        if self
            .dependency_graph
            .get(from)
            .is_some_and(|deps| deps.contains(to))
        {
            return Some(1);
        }

        // BFS for longer paths
        let mut visited = HashSet::new();
        let mut queue = vec![(from.to_string(), 0usize)];

        while let Some((current, dist)) = queue.pop() {
            if visited.contains(&current) {
                continue;
            }
            visited.insert(current.clone());

            if let Some(deps) = self.dependency_graph.get(&current) {
                for dep in deps {
                    if dep == to {
                        return Some(dist + 1);
                    }
                    if !visited.contains(dep) {
                        queue.push((dep.clone(), dist + 1));
                    }
                }
            }
        }

        None
    }

    /// Get all source files for workspace members
    pub fn get_all_source_files(&self) -> Vec<PathBuf> {
        let mut files = Vec::new();

        for member in &self.members {
            if let Some(crate_info) = self.crates.get(member) {
                for source_root in &crate_info.source_roots {
                    if !source_root.exists() {
                        continue;
                    }

                    for entry in walkdir::WalkDir::new(source_root)
                        .follow_links(true)
                        .into_iter()
                        .filter_map(|e| e.ok())
                    {
                        let path = entry.path();
                        if path.extension().is_some_and(|ext| ext == "rs") {
                            files.push(path.to_path_buf());
                        }
                    }
                }
            }
        }

        files
    }
}

fn is_analyzable_target_kind(kind: &TargetKind) -> bool {
    matches!(
        kind,
        TargetKind::Lib
            | TargetKind::RLib
            | TargetKind::DyLib
            | TargetKind::CDyLib
            | TargetKind::StaticLib
            | TargetKind::ProcMacro
            | TargetKind::Bin
    )
}

fn dedupe_paths(paths: Vec<PathBuf>) -> Vec<PathBuf> {
    let mut seen = HashSet::new();
    let mut deduped = Vec::new();

    for path in paths {
        if seen.insert(path.clone()) {
            deduped.push(path);
        }
    }

    deduped
}

fn dedupe_contained_roots(roots: Vec<PathBuf>) -> Vec<PathBuf> {
    let mut roots = dedupe_paths(roots);
    roots.sort_by_key(|root| root.components().count());

    let mut kept: Vec<PathBuf> = Vec::new();
    for root in roots {
        if kept.iter().any(|kept_root| root.starts_with(kept_root)) {
            continue;
        }
        kept.push(root);
    }

    kept
}

/// Find Cargo.toml by walking up from the given path
fn find_cargo_toml(start: &Path) -> Result<PathBuf, WorkspaceError> {
    let mut current = if start.is_file() {
        start.parent().map(|p| p.to_path_buf())
    } else {
        Some(start.to_path_buf())
    };

    while let Some(dir) = current {
        let cargo_toml = dir.join("Cargo.toml");
        if cargo_toml.exists() {
            return Ok(cargo_toml);
        }
        current = dir.parent().map(|p| p.to_path_buf());
    }

    Err(WorkspaceError::InvalidManifest(start.display().to_string()))
}

/// Resolve a module path to a crate name
/// e.g., "crate::models::user" in package "my-app" -> "my-app"
/// e.g., "serde::Serialize" -> "serde"
pub fn resolve_crate_from_path(
    use_path: &str,
    current_crate: &str,
    workspace: &WorkspaceInfo,
) -> Option<String> {
    let parts: Vec<&str> = use_path.split("::").collect();

    if parts.is_empty() {
        return None;
    }

    match parts[0] {
        "crate" | "self" | "super" => {
            // Internal reference to current crate
            Some(current_crate.to_string())
        }
        first_segment => {
            // Check if it's a known crate
            // Convert hyphens to underscores for crate names
            let normalized = first_segment.replace('-', "_");

            // Check workspace members first
            for member in &workspace.members {
                let member_normalized = member.replace('-', "_");
                if member_normalized == normalized {
                    return Some(member.clone());
                }
            }

            // Check all crates
            for name in workspace.crates.keys() {
                let name_normalized = name.replace('-', "_");
                if name_normalized == normalized {
                    return Some(name.clone());
                }
            }

            // Assume it's an external crate
            Some(first_segment.to_string())
        }
    }
}

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

    #[test]
    fn test_find_cargo_toml() {
        // Test in the current project
        let result = find_cargo_toml(Path::new("."));
        assert!(result.is_ok());
        assert!(result.unwrap().ends_with("Cargo.toml"));
    }

    #[test]
    fn test_resolve_crate_from_path() {
        let workspace = WorkspaceInfo {
            root: PathBuf::new(),
            crates: HashMap::new(),
            members: vec!["my-app".to_string(), "my-lib".to_string()],
            dependency_graph: HashMap::new(),
            reverse_deps: HashMap::new(),
        };

        // Internal reference
        assert_eq!(
            resolve_crate_from_path("crate::models::User", "my-app", &workspace),
            Some("my-app".to_string())
        );

        // Workspace member reference
        assert_eq!(
            resolve_crate_from_path("my_lib::utils", "my-app", &workspace),
            Some("my-lib".to_string())
        );

        // External crate
        assert_eq!(
            resolve_crate_from_path("serde::Serialize", "my-app", &workspace),
            Some("serde".to_string())
        );
    }
}