1use std::collections::BTreeMap;
2use std::fmt;
3use std::path::{Path, PathBuf};
4
5use serde::{Deserialize, Serialize};
6
7use crate::paths::Name;
8
9#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
12#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
13#[serde(transparent)]
14pub struct PackageId(String);
15
16impl PackageId {
17 pub fn new(name: impl Into<String>) -> Self {
18 Self(name.into())
19 }
20
21 pub fn as_str(&self) -> &str {
22 &self.0
23 }
24}
25
26impl From<&str> for PackageId {
27 fn from(name: &str) -> Self {
28 Self::new(name)
29 }
30}
31
32impl fmt::Display for PackageId {
33 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34 f.write_str(&self.0)
35 }
36}
37
38#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
43#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
44pub struct Address {
45 package: PackageId,
46 path: Vec<Name>,
47}
48
49impl Address {
50 pub fn new(
51 package: impl Into<PackageId>,
52 path: impl IntoIterator<Item = impl Into<Name>>,
53 ) -> Self {
54 Self {
55 package: package.into(),
56 path: path.into_iter().map(Into::into).collect(),
57 }
58 }
59
60 pub fn root(package: impl Into<PackageId>) -> Self {
62 Self::new(package, std::iter::empty::<Name>())
63 }
64
65 pub fn package(&self) -> &PackageId {
66 &self.package
67 }
68
69 pub fn path(&self) -> &[Name] {
70 &self.path
71 }
72
73 pub fn is_root(&self) -> bool {
74 self.path.is_empty()
75 }
76
77 pub fn starts_with(&self, prefix: &Address) -> bool {
78 self.package == prefix.package && self.path.starts_with(&prefix.path)
79 }
80
81 pub fn parent(&self) -> Option<Address> {
83 let (_, rest) = self.path.split_last()?;
84 Some(Address::new(self.package.clone(), rest.iter().cloned()))
85 }
86
87 pub fn join(&self, segment: impl Into<Name>) -> Address {
88 let mut path = self.path.clone();
89 path.push(segment.into());
90 Address {
91 package: self.package.clone(),
92 path,
93 }
94 }
95
96 pub fn extend(&self, rest: impl IntoIterator<Item = impl Into<Name>>) -> Address {
97 let mut path = self.path.clone();
98 path.extend(rest.into_iter().map(Into::into));
99 Address {
100 package: self.package.clone(),
101 path,
102 }
103 }
104
105 pub fn rebase(&self, from: &Address, to: &Address) -> Option<Address> {
107 let rest = self.strip_prefix(from)?;
108 Some(to.extend(rest.iter().cloned()))
109 }
110
111 pub fn strip_prefix(&self, prefix: &Address) -> Option<&[Name]> {
113 (self.package == prefix.package)
114 .then(|| self.path.strip_prefix(prefix.path.as_slice()))
115 .flatten()
116 }
117
118 pub fn lowest_common_ancestor(&self, other: &Address) -> Option<Address> {
120 if self.package != other.package {
121 return None;
122 }
123 let shared = self
124 .path
125 .iter()
126 .zip(&other.path)
127 .take_while(|(a, b)| a == b)
128 .count();
129 Some(Address::new(
130 self.package.clone(),
131 self.path[..shared].iter().cloned(),
132 ))
133 }
134
135 pub fn display_with(&self, separator: &str) -> String {
137 self.path
138 .iter()
139 .map(Name::as_str)
140 .collect::<Vec<_>>()
141 .join(separator)
142 }
143}
144
145impl fmt::Display for Address {
148 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149 let mut first = self.package.as_str().is_empty();
150 if !first {
151 write!(f, "{}", self.package)?;
152 }
153 for segment in &self.path {
154 if !first {
155 f.write_str("::")?;
156 }
157 write!(f, "{segment}")?;
158 first = false;
159 }
160 Ok(())
161 }
162}
163
164#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
166#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
167pub struct Package {
168 pub id: PackageId,
170 pub name: String,
173 pub root: PathBuf,
175 #[serde(default)]
177 pub dependencies: Vec<Dependency>,
178}
179
180#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
183#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
184pub struct Dependency {
185 pub used_as: PackageId,
186 pub package: String,
187}
188
189#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
192#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
193pub struct Packages {
194 by_root: BTreeMap<PathBuf, Package>,
195}
196
197impl Packages {
198 pub fn new(packages: impl IntoIterator<Item = Package>) -> Self {
199 Self {
200 by_root: packages.into_iter().map(|p| (p.root.clone(), p)).collect(),
201 }
202 }
203
204 pub fn containing(&self, path: &Path) -> Option<&Package> {
206 path.ancestors().find_map(|dir| self.by_root.get(dir))
207 }
208
209 pub fn named(&self, id: &PackageId) -> Option<&Package> {
210 self.by_root.values().find(|p| &p.id == id)
211 }
212
213 pub fn iter(&self) -> impl Iterator<Item = &Package> {
214 self.by_root.values()
215 }
216
217 pub fn is_member(&self, id: &PackageId) -> bool {
220 self.named(id).is_some()
221 }
222
223 pub fn referent(&self, from: &PackageId, head: &PackageId) -> Option<PackageId> {
228 if self.is_member(head) {
229 return Some(head.clone());
230 }
231 let dependency = self
232 .named(from)?
233 .dependencies
234 .iter()
235 .find(|d| &d.used_as == head)?;
236 Some(
237 self.iter()
238 .find(|p| p.name == dependency.package)
239 .map_or_else(|| head.clone(), |member| member.id.clone()),
240 )
241 }
242
243 pub fn name_for(&self, from: &PackageId, target: &PackageId) -> PackageId {
246 let Some(member) = self.named(target) else {
247 return target.clone();
248 };
249 self.named(from)
250 .and_then(|p| p.dependencies.iter().find(|d| d.package == member.name))
251 .map_or_else(|| target.clone(), |d| d.used_as.clone())
252 }
253}
254
255#[cfg(test)]
256mod tests {
257 use super::*;
258
259 #[test]
260 fn rebase_replaces_prefix_only() {
261 let a = Address::new("k", ["foo", "bar", "X"]);
262 let from = Address::new("k", ["foo", "bar"]);
263 let to = Address::new("k", ["baz", "qux"]);
264 assert_eq!(
265 a.rebase(&from, &to),
266 Some(Address::new("k", ["baz", "qux", "X"]))
267 );
268 assert_eq!(a.rebase(&Address::new("k", ["nope"]), &to), None);
269 }
270
271 #[test]
272 fn nothing_holds_across_packages() {
273 let a = Address::new("a", ["m", "x"]);
274 let b = Address::new("b", ["m", "x"]);
275 assert!(!a.starts_with(&Address::root("b")));
276 assert_eq!(a.strip_prefix(&Address::root("b")), None);
277 assert_eq!(a.lowest_common_ancestor(&b), None);
278 assert_ne!(a, b);
279 }
280
281 #[test]
282 fn lowest_common_ancestor_within_a_package() {
283 let a = Address::new("k", ["grep", "types", "GrepMatch"]);
284 let b = Address::new("k", ["grep", "sink"]);
285 assert_eq!(
286 a.lowest_common_ancestor(&b),
287 Some(Address::new("k", ["grep"]))
288 );
289 assert_eq!(
290 a.lowest_common_ancestor(&Address::new("k", ["other"])),
291 Some(Address::root("k"))
292 );
293 assert_eq!(Address::root("k").parent(), None);
294 }
295
296 #[test]
297 fn packages_find_the_deepest_root() {
298 let packages = Packages::new([
299 Package {
300 id: "top".into(),
301 name: "top".into(),
302 root: PathBuf::from(""),
303 dependencies: vec![Dependency {
304 used_as: "in".into(),
305 package: "inner-pkg".into(),
306 }],
307 },
308 Package {
309 id: "inner_pkg".into(),
310 name: "inner-pkg".into(),
311 root: PathBuf::from("crates/inner"),
312 dependencies: Vec::new(),
313 },
314 ]);
315 assert_eq!(
316 packages
317 .containing(Path::new("crates/inner/src/lib.rs"))
318 .map(|p| p.id.as_str()),
319 Some("inner_pkg")
320 );
321 assert_eq!(
322 packages
323 .containing(Path::new("src/main.rs"))
324 .map(|p| p.id.as_str()),
325 Some("top")
326 );
327 assert_eq!(
328 packages
329 .named(&"inner_pkg".into())
330 .map(|p| p.root.as_path()),
331 Some(Path::new("crates/inner"))
332 );
333 }
334
335 #[test]
336 fn renamed_dependencies_refer_to_members_and_are_spelled_back() {
337 let packages = Packages::new([
338 Package {
339 id: "top".into(),
340 name: "top".into(),
341 root: PathBuf::from(""),
342 dependencies: vec![
343 Dependency {
344 used_as: "in".into(),
345 package: "inner-pkg".into(),
346 },
347 Dependency {
348 used_as: "serde".into(),
349 package: "serde".into(),
350 },
351 ],
352 },
353 Package {
354 id: "inner_pkg".into(),
355 name: "inner-pkg".into(),
356 root: PathBuf::from("crates/inner"),
357 dependencies: Vec::new(),
358 },
359 ]);
360 let top: PackageId = "top".into();
361 assert_eq!(
362 packages.referent(&top, &"in".into()),
363 Some("inner_pkg".into())
364 );
365 assert_eq!(
366 packages.referent(&top, &"inner_pkg".into()),
367 Some("inner_pkg".into())
368 );
369 assert_eq!(
370 packages.referent(&top, &"serde".into()),
371 Some("serde".into()),
372 "external, by its own name"
373 );
374 assert_eq!(packages.referent(&top, &"nope".into()), None);
375 assert_eq!(packages.name_for(&top, &"inner_pkg".into()), "in".into());
376 assert_eq!(
377 packages.name_for(&"inner_pkg".into(), &"top".into()),
378 "top".into()
379 );
380 }
381}