|
| 1 | +use indexmap::IndexMap; |
| 2 | +use pep508_rs::Requirement; |
| 3 | +use std::ops::Deref; |
| 4 | +use thiserror::Error; |
| 5 | + |
| 6 | +/// A trait that resolves recursions for groups of requirements that can be mapped to `IndexMap<String, Vec<T>>` |
| 7 | +/// where T is a type that can be mapped to either a Requirement or a reference to other groups of requirements. |
| 8 | +pub trait HasRecursion<T>: Deref<Target = IndexMap<String, Vec<T>>> |
| 9 | +where |
| 10 | + T: RecursionItem, |
| 11 | +{ |
| 12 | + /// Resolve the groups into lists of requirements. |
| 13 | + /// |
| 14 | + /// This function will recursively resolve all groups, including those that |
| 15 | + /// reference other groups. It will return an error if there is a cycle in the |
| 16 | + /// groups or if a group references another group that does not exist. |
| 17 | + fn resolve(&self) -> Result<IndexMap<String, Vec<Requirement>>, RecursionResolutionError> { |
| 18 | + self.resolve_all(None) |
| 19 | + } |
| 20 | + |
| 21 | + /// Resolves the groups of requirements into flat lists of requirements. |
| 22 | + fn resolve_all( |
| 23 | + &self, |
| 24 | + name: Option<&str>, |
| 25 | + ) -> Result<IndexMap<String, Vec<Requirement>>, RecursionResolutionError> { |
| 26 | + // Helper function to resolve a single group |
| 27 | + fn resolve_single<'a, T: RecursionItem>( |
| 28 | + groups: &'a IndexMap<String, Vec<T>>, |
| 29 | + group: &'a str, |
| 30 | + resolved: &mut IndexMap<String, Vec<Requirement>>, |
| 31 | + parents: &mut Vec<&'a str>, |
| 32 | + name: Option<&'a str>, |
| 33 | + ) -> Result<(), RecursionResolutionError> { |
| 34 | + let Some(items) = groups.get(group) else { |
| 35 | + // If the group included in another group does not exist, return an error |
| 36 | + let parent = parents.iter().last().expect("should have a parent"); |
| 37 | + return Err(RecursionResolutionError::GroupNotFound( |
| 38 | + T::group_name(), |
| 39 | + group.to_string(), |
| 40 | + parent.to_string(), |
| 41 | + )); |
| 42 | + }; |
| 43 | + // If there is a cycle in dependency groups, return an error |
| 44 | + if parents.contains(&group) { |
| 45 | + return Err(RecursionResolutionError::DependencyGroupCycle( |
| 46 | + T::table_name(), |
| 47 | + Cycle(parents.iter().map(|s| s.to_string()).collect()), |
| 48 | + )); |
| 49 | + } |
| 50 | + // If the group has already been resolved, exit early |
| 51 | + if resolved.get(group).is_some() { |
| 52 | + return Ok(()); |
| 53 | + } |
| 54 | + // Otherwise, perform recursion, as required, on the dependency group's specifiers |
| 55 | + parents.push(group); |
| 56 | + let mut requirements = Vec::with_capacity(items.len()); |
| 57 | + for spec in items.iter() { |
| 58 | + match spec.parse(name) { |
| 59 | + // It's a requirement. Just add it to the Vec of resolved requirements |
| 60 | + Item::Requirement(requirement) => requirements.push(requirement.clone()), |
| 61 | + // It's a reference to other groups. Recurse into them |
| 62 | + Item::Groups(inner_groups) => { |
| 63 | + for group in inner_groups { |
| 64 | + resolve_single(groups, group, resolved, parents, name)?; |
| 65 | + requirements.extend(resolved.get(group).into_iter().flatten().cloned()); |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + // Add the resolved group to IndexMap |
| 71 | + resolved.insert(group.to_string(), requirements.clone()); |
| 72 | + parents.pop(); |
| 73 | + Ok(()) |
| 74 | + } |
| 75 | + |
| 76 | + let mut resolved = IndexMap::new(); |
| 77 | + for group in self.keys() { |
| 78 | + resolve_single(self, group, &mut resolved, &mut Vec::new(), name)?; |
| 79 | + } |
| 80 | + Ok(resolved) |
| 81 | + } |
| 82 | +} |
| 83 | +/// A trait that defines how to parse a recursion item. |
| 84 | +pub trait RecursionItem { |
| 85 | + /// Parse the item into a requirement or a reference to other groups. |
| 86 | + fn parse<'a>(&'a self, name: Option<&str>) -> Item<'a>; |
| 87 | + /// The name of the group in the TOML file. |
| 88 | + fn group_name() -> String; |
| 89 | + /// The name of the table in the TOML file. |
| 90 | + fn table_name() -> String; |
| 91 | +} |
| 92 | + |
| 93 | +pub enum Item<'a> { |
| 94 | + Requirement(Requirement), |
| 95 | + Groups(Vec<&'a str>), |
| 96 | +} |
| 97 | + |
| 98 | +#[derive(Debug, Error)] |
| 99 | +pub enum RecursionResolutionError { |
| 100 | + #[error("Failed to find {0} `{1}` included by `{2}`")] |
| 101 | + GroupNotFound(String, String, String), |
| 102 | + #[error("Detected a cycle in `{0}`: {1}")] |
| 103 | + DependencyGroupCycle(String, Cycle), |
| 104 | +} |
| 105 | + |
| 106 | +/// A cycle in the recursion. |
| 107 | +#[derive(Debug)] |
| 108 | +pub struct Cycle(Vec<String>); |
| 109 | + |
| 110 | +/// Display a cycle, e.g., `a -> b -> c -> a`. |
| 111 | +impl std::fmt::Display for Cycle { |
| 112 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 113 | + let [first, rest @ ..] = self.0.as_slice() else { |
| 114 | + return Ok(()); |
| 115 | + }; |
| 116 | + write!(f, "`{first}`")?; |
| 117 | + for group in rest { |
| 118 | + write!(f, " -> `{group}`")?; |
| 119 | + } |
| 120 | + write!(f, " -> `{first}`")?; |
| 121 | + Ok(()) |
| 122 | + } |
| 123 | +} |
0 commit comments