Skip to main content

architecture_tests/
graph.rs

1//! Workspace package graph and dependency queries.
2
3use std::{collections::HashMap, fmt, path::Path};
4
5use guppy::{
6    graph::{DependencyDirection, PackageGraph, PackageLink, PackageMetadata},
7    MetadataCommand, PackageId,
8};
9
10/// The package graph of a Cargo workspace.
11///
12/// The graph holds every package for every feature and every platform: optional, feature-gated, and
13/// `[target.'cfg(..)']` links are all present.
14pub struct Workspace {
15    graph: PackageGraph,
16}
17
18impl Workspace {
19    /// Loads the package graph of the workspace whose root manifest is at `manifest_path`.
20    ///
21    /// # Errors
22    ///
23    /// Returns an error if `cargo metadata` fails, including when `Cargo.lock` needs an update.
24    pub fn load(manifest_path: &Path) -> Result<Self, guppy::Error> {
25        let mut command = MetadataCommand::new();
26        command.manifest_path(manifest_path).other_options(["--locked"]);
27        Ok(Self {
28            graph: command.build_graph()?,
29        })
30    }
31
32    /// Returns the workspace root directory.
33    pub fn root(&self) -> &Path {
34        self.graph.workspace().root().as_std_path()
35    }
36
37    /// Returns the workspace member named `name`.
38    ///
39    /// # Errors
40    ///
41    /// Returns an error if no workspace member has that package name.
42    pub fn member(&self, name: &str) -> Result<PackageMetadata<'_>, guppy::Error> {
43        self.graph.workspace().member_by_name(name)
44    }
45}
46
47/// Dependency kinds included by [`Dependencies`], without feature or platform filtering.
48#[derive(Clone, Copy, Debug, Eq, PartialEq)]
49pub enum Links {
50    /// Any link out of the root, including dev-dependencies, then [`Links::AsDependency`].
51    Built,
52
53    /// Normal or build entries at every hop. Cargo never builds a dependency's dev-dependencies.
54    AsDependency,
55
56    /// Links with a normal entry, at every hop.
57    Normal,
58}
59
60/// A package's direct and transitive dependencies, with one route to each.
61pub struct Dependencies<'g> {
62    via: HashMap<&'g PackageId, PackageLink<'g>>,
63}
64
65impl<'g> Dependencies<'g> {
66    /// Computes the packages `root` depends on through `links`.
67    ///
68    /// For [`Links::Built`], a package reachable without a root dev-dependency is reported through such a route,
69    /// so a failing guard names the dependency that has to change.
70    pub fn new(root: PackageMetadata<'g>, links: Links) -> Self {
71        let mut via = match links {
72            Links::Built => Self::new(root, Links::AsDependency).via,
73            Links::AsDependency | Links::Normal => HashMap::new(),
74        };
75        let root_id = root.id();
76        let query = root.to_package_query(DependencyDirection::Forward);
77        query.resolve_with_fn(|cx, link| {
78            let follow = match links {
79                Links::Built => cx.starts_from_initial(&link) || !link.dev_only(),
80                Links::AsDependency => !link.dev_only(),
81                Links::Normal => link.normal().is_present(),
82            };
83            if follow && link.to().id() != root_id {
84                via.entry(link.to().id()).or_insert(link);
85            }
86            follow
87        });
88        Self { via }
89    }
90
91    /// Returns the dependency route to `package`, or `None` for the root or a non-dependency.
92    pub fn route_to(&self, package: &PackageMetadata<'g>) -> Option<Route<'g>> {
93        let mut links = Vec::new();
94        let mut id = package.id();
95        while let Some(link) = self.via.get(id) {
96            links.push(*link);
97            id = link.from().id();
98        }
99        if links.is_empty() {
100            return None;
101        }
102        links.reverse();
103        Some(Route { links })
104    }
105
106    /// Returns workspace members the root depends on, excluding the root itself.
107    pub fn workspace_members(&self) -> impl Iterator<Item = PackageMetadata<'g>> + '_ {
108        self.via
109            .values()
110            .map(|link| link.to())
111            .filter(|package| package.in_workspace())
112    }
113}
114
115/// A chain of package links, displayed as `a -[normal]-> b -[build]-> c`.
116pub struct Route<'g> {
117    links: Vec<PackageLink<'g>>,
118}
119
120impl fmt::Display for Route<'_> {
121    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122        let Some(first) = self.links.first() else {
123            return Ok(());
124        };
125        f.write_str(first.from().name())?;
126        for link in &self.links {
127            write!(f, " -[{}]-> {}", LinkKinds(link), link.to().name())?;
128        }
129        Ok(())
130    }
131}
132
133/// The dependency sections a link appears in, displayed as `normal+dev`.
134pub struct LinkKinds<'a, 'g>(pub &'a PackageLink<'g>);
135
136impl fmt::Display for LinkKinds<'_, '_> {
137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138        let link = self.0;
139        let kinds = [
140            ("normal", link.normal().is_present()),
141            ("dev", link.dev().is_present()),
142            ("build", link.build().is_present()),
143        ];
144        let mut separator = "";
145        for (name, _) in kinds.iter().filter(|(_, present)| *present) {
146            write!(f, "{separator}{name}")?;
147            separator = "+";
148        }
149        Ok(())
150    }
151}
152
153/// Returns direct links of any kind from `from` to `target` or to packages that depend on `target`
154/// through [`Links::AsDependency`].
155pub fn direct_links_to_target_or_its_dependents<'g>(
156    from: &PackageMetadata<'g>, target: &PackageMetadata<'g>,
157) -> Vec<PackageLink<'g>> {
158    from.direct_links()
159        .filter(|link| {
160            let to = link.to();
161            to.id() == target.id() || Dependencies::new(to, Links::AsDependency).route_to(target).is_some()
162        })
163        .collect()
164}
165
166#[cfg(test)]
167mod tests {
168    use std::{collections::BTreeSet, fs, process::Command};
169
170    use super::*;
171
172    /// Exercises renames, optional target-specific links, root-only dev-dependency traversal, and a package reached
173    /// both through a root dev-dependency and through a build chain.
174    struct Fixture {
175        dir: tempfile::TempDir,
176    }
177
178    const MANIFESTS: &[(&str, &str)] = &[
179        (
180            "a",
181            r#"
182            [dependencies]
183            renamed = { package = "b", path = "../b" }
184
185            [dev-dependencies]
186            c = { path = "../c" }
187
188            [build-dependencies]
189            d = { path = "../d" }
190
191            [target.'cfg(windows)'.dependencies]
192            e = { path = "../e", optional = true }
193            "#,
194        ),
195        ("b", ""),
196        (
197            "c",
198            r#"
199            [dependencies]
200            g = { path = "../g" }
201
202            [dev-dependencies]
203            f = { path = "../f" }
204            "#,
205        ),
206        (
207            "d",
208            r#"
209            [dependencies]
210            g = { path = "../g" }
211            "#,
212        ),
213        ("e", ""),
214        ("f", ""),
215        ("g", ""),
216    ];
217
218    impl Fixture {
219        fn new() -> Self {
220            let dir = tempfile::tempdir().expect("create fixture directory");
221            let members: Vec<String> = MANIFESTS.iter().map(|(name, _)| format!("{name:?}")).collect();
222            fs::write(
223                dir.path().join("Cargo.toml"),
224                format!("[workspace]\nmembers = [{}]\nresolver = \"2\"\n", members.join(", ")),
225            )
226            .expect("write workspace manifest");
227            for (name, dependencies) in MANIFESTS {
228                let package = dir.path().join(name);
229                fs::create_dir_all(package.join("src")).expect("create package directory");
230                fs::write(package.join("src/lib.rs"), "").expect("write package source");
231                fs::write(
232                    package.join("Cargo.toml"),
233                    format!("[package]\nname = {name:?}\nversion = \"0.1.0\"\nedition = \"2021\"\n{dependencies}"),
234                )
235                .expect("write package manifest");
236            }
237            let cargo = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
238            let status = Command::new(cargo)
239                .args(["generate-lockfile", "--offline", "--manifest-path"])
240                .arg(dir.path().join("Cargo.toml"))
241                .status()
242                .expect("run cargo generate-lockfile");
243            assert!(status.success(), "cargo generate-lockfile failed");
244            Self { dir }
245        }
246
247        fn load(&self) -> Workspace {
248            Workspace::load(&self.dir.path().join("Cargo.toml")).expect("load fixture workspace")
249        }
250    }
251
252    fn member_names<'g>(packages: impl Iterator<Item = PackageMetadata<'g>>) -> BTreeSet<&'g str> {
253        packages.map(|package| package.name()).collect()
254    }
255
256    #[test]
257    fn built_dependencies_include_root_dev_links_but_not_dependency_dev_links() {
258        let fixture = Fixture::new();
259        let workspace = fixture.load();
260        let a = workspace.member("a").unwrap();
261        let dependencies = Dependencies::new(a, Links::Built);
262
263        assert_eq!(
264            member_names(dependencies.workspace_members()),
265            BTreeSet::from(["b", "c", "d", "e", "g"])
266        );
267        assert!(dependencies.route_to(&workspace.member("f").unwrap()).is_none());
268        assert_eq!(
269            dependencies
270                .route_to(&workspace.member("g").unwrap())
271                .unwrap()
272                .to_string(),
273            "a -[build]-> d -[normal]-> g"
274        );
275        assert_eq!(
276            dependencies
277                .route_to(&workspace.member("e").unwrap())
278                .unwrap()
279                .to_string(),
280            "a -[normal]-> e"
281        );
282
283        let c_dependencies = Dependencies::new(workspace.member("c").unwrap(), Links::Built);
284        assert_eq!(
285            c_dependencies
286                .route_to(&workspace.member("f").unwrap())
287                .unwrap()
288                .to_string(),
289            "c -[dev]-> f"
290        );
291    }
292
293    #[test]
294    fn normal_dependencies_follow_only_normal_links() {
295        let fixture = Fixture::new();
296        let workspace = fixture.load();
297        let dependencies = Dependencies::new(workspace.member("a").unwrap(), Links::Normal);
298
299        assert_eq!(
300            member_names(dependencies.workspace_members()),
301            BTreeSet::from(["b", "e"])
302        );
303    }
304
305    #[test]
306    fn direct_links_include_target_and_packages_depending_on_it() {
307        let fixture = Fixture::new();
308        let workspace = fixture.load();
309        let a = workspace.member("a").unwrap();
310
311        let to_b: Vec<_> = direct_links_to_target_or_its_dependents(&a, &workspace.member("b").unwrap())
312            .iter()
313            .map(|link| (link.resolved_name(), link.to().name()))
314            .collect();
315        assert_eq!(to_b, [("renamed", "b")]);
316
317        let mut to_g: Vec<_> = direct_links_to_target_or_its_dependents(&a, &workspace.member("g").unwrap())
318            .iter()
319            .map(|link| (link.resolved_name(), LinkKinds(link).to_string()))
320            .collect();
321        to_g.sort();
322        assert_eq!(to_g, [("c", "dev".to_string()), ("d", "build".to_string())]);
323
324        assert!(direct_links_to_target_or_its_dependents(&a, &workspace.member("f").unwrap()).is_empty());
325    }
326
327    #[test]
328    fn unknown_member_name_is_an_error() {
329        let fixture = Fixture::new();
330        let workspace = fixture.load();
331
332        assert!(matches!(
333            workspace.member("missing"),
334            Err(guppy::Error::UnknownWorkspaceName(name)) if name == "missing"
335        ));
336    }
337
338    #[test]
339    fn load_rejects_a_stale_lockfile() {
340        let fixture = Fixture::new();
341        fs::write(fixture.dir.path().join("Cargo.lock"), "version = 4\n").expect("truncate lockfile");
342
343        assert!(matches!(
344            Workspace::load(&fixture.dir.path().join("Cargo.toml")),
345            Err(guppy::Error::CommandError(_))
346        ));
347    }
348}