cargo_critpath/metadata.rs
1//! Attributing a source path to a package, exactly, using `cargo metadata`.
2//!
3//! A `rustc` invocation identifies its unit by a source path. For a registry crate that path
4//! contains `name-version/` and says which package it is. For a workspace-local crate it does not,
5//! and guessing from the directory name is wrong often enough to matter: `bevy` keeps several
6//! distinct procedural-macro packages in directories all named `macros`, and naming them after
7//! their directory collapses six units onto one key.
8//!
9//! `cargo metadata --format-version 1` gives every package's `manifest_path`. A source path belongs
10//! to the package whose manifest directory is its longest matching prefix, which is exact and needs
11//! no heuristic at all.
12
13use serde_json::Value;
14
15use crate::error::ParseError;
16
17/// Every package a workspace contains, indexed by the directory its manifest lives in.
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct PackageIndex {
20 /// The workspace root, used to make a relative source path absolute. Cargo writes a
21 /// workspace-local target's source path relative to it.
22 workspace_root: String,
23 /// `(manifest directory, package name, package version)`, longest directory first, so the first
24 /// match is the longest one.
25 packages: Vec<(String, String, String)>,
26}
27
28impl PackageIndex {
29 /// How many packages the index holds.
30 #[must_use]
31 pub fn len(&self) -> usize {
32 self.packages.len()
33 }
34
35 /// Whether the index holds no packages.
36 #[must_use]
37 pub fn is_empty(&self) -> bool {
38 self.packages.is_empty()
39 }
40
41 /// The package a source path belongs to, by longest-prefix match on the manifest directories.
42 ///
43 /// ```
44 /// # use cargo_critpath::parse_cargo_metadata;
45 /// let metadata = r#"{"workspace_root":"/w","packages":[
46 /// {"name":"app","version":"0.1.0","manifest_path":"/w/app/Cargo.toml"},
47 /// {"name":"leaf","version":"0.1.0","manifest_path":"/w/leaf/Cargo.toml"}]}"#;
48 /// let index = parse_cargo_metadata(metadata)?;
49 /// assert_eq!(index.package_at("app/src/main.rs"), Some(("app", "0.1.0")));
50 /// assert_eq!(index.package_at("/w/leaf/build.rs"), Some(("leaf", "0.1.0")));
51 /// assert_eq!(index.package_at("elsewhere/src/lib.rs"), None);
52 /// assert_eq!(index.package_at(""), None);
53 /// # Ok::<(), cargo_critpath::ParseError>(())
54 /// ```
55 #[must_use]
56 pub fn package_at(&self, source_path: &str) -> Option<(&str, &str)> {
57 // An empty path is not the workspace root; a build-script execution has no source file, and
58 // attributing it to whichever package sits at the root would be a confident wrong answer.
59 if source_path.is_empty() {
60 return None;
61 }
62 let normalised = normalise(source_path);
63 let absolute = if is_absolute(&normalised) {
64 normalised
65 } else {
66 let root = normalise(&self.workspace_root);
67 format!("{}/{}", root.trim_end_matches('/'), normalised)
68 };
69 self.packages
70 .iter()
71 .find(|(directory, _, _)| under(&absolute, directory))
72 .map(|(_, name, version)| (name.as_str(), version.as_str()))
73 }
74}
75
76/// Reads `cargo metadata --format-version 1` output.
77///
78/// Only `workspace_root` and each package's `name`, `version` and `manifest_path` are read; every
79/// other field is ignored, so a newer Cargo does not break this.
80///
81/// # Errors
82///
83/// [`ParseError::Metadata`] if the text is not JSON, or does not have the shape `cargo metadata`
84/// produces.
85pub fn parse(text: &str) -> Result<PackageIndex, ParseError> {
86 let value: Value = serde_json::from_str(text).map_err(|e| ParseError::Metadata {
87 detail: e.to_string(),
88 })?;
89 let packages = value
90 .get("packages")
91 .and_then(Value::as_array)
92 .ok_or_else(|| ParseError::Metadata {
93 detail: "there is no `packages` array".to_owned(),
94 })?;
95
96 let mut entries: Vec<(String, String, String)> = Vec::with_capacity(packages.len());
97 for package in packages {
98 let (Some(name), Some(version), Some(manifest)) = (
99 package.get("name").and_then(Value::as_str),
100 package.get("version").and_then(Value::as_str),
101 package.get("manifest_path").and_then(Value::as_str),
102 ) else {
103 continue;
104 };
105 entries.push((
106 normalise(parent_of(manifest)),
107 name.to_owned(),
108 version.to_owned(),
109 ));
110 }
111 if entries.is_empty() {
112 return Err(ParseError::Metadata {
113 detail: "the `packages` array names no package with a manifest path".to_owned(),
114 });
115 }
116 // Longest directory first, so that a package nested inside another wins over its parent. Ties
117 // are broken by name and version so the order does not depend on the input's.
118 entries.sort_by(|a, b| {
119 b.0.len()
120 .cmp(&a.0.len())
121 .then_with(|| a.1.cmp(&b.1))
122 .then_with(|| a.2.cmp(&b.2))
123 });
124
125 Ok(PackageIndex {
126 workspace_root: value
127 .get("workspace_root")
128 .and_then(Value::as_str)
129 .unwrap_or_default()
130 .to_owned(),
131 packages: entries,
132 })
133}
134
135fn normalise(path: &str) -> String {
136 path.replace('\\', "/")
137}
138
139fn is_absolute(path: &str) -> bool {
140 if path.starts_with('/') {
141 return true;
142 }
143 // A Windows path: a drive letter, a colon, and a separator.
144 let mut chars = path.chars();
145 matches!(
146 (chars.next(), chars.next(), chars.next()),
147 (Some(letter), Some(':'), Some('/')) if letter.is_ascii_alphabetic()
148 )
149}
150
151fn under(path: &str, directory: &str) -> bool {
152 let directory = directory.trim_end_matches('/');
153 match path.strip_prefix(directory) {
154 Some(rest) => rest.is_empty() || rest.starts_with('/'),
155 None => false,
156 }
157}
158
159fn parent_of(path: &str) -> &str {
160 match path.rfind(['/', '\\']) {
161 Some(at) => path.get(..at).unwrap_or(""),
162 None => "",
163 }
164}