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
use petgraph::{stable_graph::StableDiGraph, Direction};
/// Must be implemented by the type you wish
/// to build a dependency graph for. See the README.md for an example
pub trait Node {
/// Encodes a dependency relationship. In a Package Manager dependency graph for intance, this might be a (package name, version) tuple.
/// It might also just be the exact same type as the one that implements the Node trait, in which case `Node::matches` can be implemented through simple equality.
type DependencyType;
/// Returns a slice of dependencies for this Node
fn dependencies(&self) -> &[Self::DependencyType];
/// Returns true if the `dependency` can be met by us.
fn matches(&self, dependency: &Self::DependencyType) -> bool;
}
/// Wrapper around dependency graph nodes.
/// Since a graph might have dependencies that cannot be resolved internally,
/// this wrapper is necessary to differentiate between internally resolved and
/// externally (unresolved) dependencies.
/// An Unresolved dependency does not necessarily mean that it *cannot* be resolved,
/// only that no Node within the graph fulfills it.
pub enum Step<'a, N: Node> {
Resolved(&'a N),
Unresolved(&'a N::DependencyType),
}
impl<'a, N: Node> Step<'a, N> {
pub fn is_resolved(&self) -> bool {
match self {
Step::Resolved(_) => true,
Step::Unresolved(_) => false,
}
}
pub fn as_resolved(&self) -> Option<&N> {
match self {
Step::Resolved(node) => Some(node),
Step::Unresolved(_) => None,
}
}
pub fn as_unresolved(&self) -> Option<&N::DependencyType> {
match self {
Step::Resolved(_) => None,
Step::Unresolved(dependency) => Some(dependency),
}
}
}
/// The [`DependencyGraph`] structure builds an internal [Directed Graph](`petgraph::stable_graph::StableDiGraph`), which can then be traversed
/// in an order which ensures that dependent Nodes are visited before their parents.
pub struct DependencyGraph<'a, N: Node> {
graph: StableDiGraph<Step<'a, N>, &'a N::DependencyType>,
}
/// The only way to build a [`DependencyGraph`] is from a slice of objects implementing [`Node`].
/// The graph references the original items, meaning the objects cannot be modified while
/// the [`DependencyGraph`] holds a reference to them.
impl<'a, N> From<&'a [N]> for DependencyGraph<'a, N>
where
N: Node,
{
fn from(nodes: &'a [N]) -> Self {
let mut graph = StableDiGraph::<Step<'a, N>, &'a N::DependencyType>::new();
// Insert the input nodes into the graph, and record their positions.
// We'll be adding the edges next, and filling in any unresolved
// steps we find along the way.
let nodes: Vec<(_, _)> = nodes
.iter()
.map(|node| (node, graph.add_node(Step::Resolved(node))))
.collect();
for (node, index) in nodes.iter() {
for dependency in node.dependencies() {
// Check to see if we can resolve this dependency internally.
if let Some((_, dependent)) = nodes.iter().find(|(dep, _)| dep.matches(dependency))
{
// If we can, just add an edge between the two nodes.
graph.add_edge(*index, *dependent, dependency);
} else {
// If not, create a new "Unresolved" node, and create an edge to that.
let unresolved = graph.add_node(Step::Unresolved(dependency));
graph.add_edge(*index, unresolved, dependency);
}
}
}
Self { graph }
}
}
impl<'a, N> DependencyGraph<'a, N>
where
N: Node,
{
/// True if all graph [`Node`]s have only references to other internal [`Node`]s.
/// That is, there are no unresolved dependencies between nodes.
pub fn is_internally_resolvable(&self) -> bool {
self.graph.node_weights().all(Step::is_resolved)
}
/// Get an iterator over unresolved dependencies, without traversing the whole graph.
/// Useful for doing pre-validation or pre-fetching of external dependencies before
/// starting to resolve internal dependencies.
pub fn unresolved_dependencies(&self) -> impl Iterator<Item = &N::DependencyType> {
self.graph.node_weights().filter_map(Step::as_unresolved)
}
}
/// Iterate over the DependencyGraph in an order which ensures dependencies are resolved before each Node is visited.
/// Note: If a `Step::Unresolved` node is returned, it is the caller's responsibility to ensure the dependency is resolved
/// before continuing.
impl<'a, N> Iterator for DependencyGraph<'a, N>
where
N: Node,
{
type Item = Step<'a, N>;
fn next(&mut self) -> Option<Self::Item> {
// Returns the first node, which does not have any Outgoing
// edges, which means it is terminal.
for index in self.graph.node_indices().rev() {
if self
.graph
.neighbors_directed(index, Direction::Outgoing)
.count()
== 0
{
return self.graph.remove_node(index);
}
}
None
}
}
#[cfg(test)]
mod tests {
use super::{DependencyGraph, Node, Step};
use semver::{BuildMetadata, Prerelease, Version, VersionReq};
#[derive(Debug)]
struct Package {
name: &'static str,
version: Version,
dependencies: Vec<Dependency>,
}
#[derive(Debug)]
struct Dependency {
name: &'static str,
version: VersionReq,
}
impl Node for Package {
type DependencyType = Dependency;
fn dependencies(&self) -> &[Self::DependencyType] {
&self.dependencies[..]
}
fn matches(&self, dependency: &Self::DependencyType) -> bool {
self.name == dependency.name && dependency.version.matches(&self.version)
}
}
#[test]
fn test_dependencies_synchronous() {
let build = build_test_graph();
let graph = DependencyGraph::from(&build[..]);
assert!(!graph.is_internally_resolvable());
for node in graph {
match node {
Step::Resolved(build) => println!("build: {:?}", build.name),
Step::Unresolved(lookup) => println!("lookup: {:?}", lookup.name),
}
}
}
#[test]
fn test_unresolved_dependencies() {
let build = build_test_graph();
let graph = DependencyGraph::from(&build[..]);
assert!(!graph.is_internally_resolvable());
let unresolved_dependencies: Vec<_> = graph
.unresolved_dependencies()
.map(|dep| dep.name)
.collect();
assert_eq!(
unresolved_dependencies,
vec!["@scope/unknown", "@scope/remote"]
);
}
#[test]
fn test_generate_dependency_graph() {
let _ = DependencyGraph::from(&build_test_graph()[..]);
}
fn build_test_graph() -> Vec<Package> {
vec![
Package {
name: "@scope/package-a",
version: semver::Version {
major: 1,
minor: 2,
patch: 3,
pre: Prerelease::new("").unwrap(),
build: BuildMetadata::EMPTY,
},
dependencies: vec![],
},
Package {
name: "@scope/package-b",
version: semver::Version {
major: 1,
minor: 2,
patch: 3,
pre: Prerelease::new("").unwrap(),
build: BuildMetadata::EMPTY,
},
dependencies: vec![Dependency {
name: "@scope/package-a",
version: ">=1.0.0".parse().unwrap(),
}],
},
Package {
name: "@scope/package-c",
version: semver::Version {
major: 1,
minor: 2,
patch: 3,
pre: Prerelease::new("").unwrap(),
build: BuildMetadata::EMPTY,
},
dependencies: vec![Dependency {
name: "@scope/package-b",
version: ">=1.0.0".parse().unwrap(),
}],
},
Package {
name: "@scope/package-d",
version: semver::Version {
major: 1,
minor: 2,
patch: 3,
pre: Prerelease::new("").unwrap(),
build: BuildMetadata::EMPTY,
},
dependencies: vec![
Dependency {
name: "@scope/package-a",
version: ">=1.0.0".parse().unwrap(),
},
Dependency {
name: "@scope/package-b",
version: ">=1.0.0".parse().unwrap(),
},
],
},
Package {
name: "@scope/package-e",
version: semver::Version {
major: 1,
minor: 2,
patch: 3,
pre: Prerelease::new("").unwrap(),
build: BuildMetadata::EMPTY,
},
dependencies: vec![],
},
Package {
name: "@scope/package-f",
version: semver::Version {
major: 1,
minor: 2,
patch: 3,
pre: Prerelease::new("").unwrap(),
build: BuildMetadata::EMPTY,
},
dependencies: vec![
Dependency {
name: "@scope/unknown",
version: ">=1.0.0".parse().unwrap(),
},
Dependency {
name: "@scope/remote",
version: "=3.0.0".parse().unwrap(),
},
],
},
]
}
#[test]
fn test_internally_resolved() {
let packages = vec![
Package {
name: "@scope/package-a",
version: semver::Version {
major: 1,
minor: 2,
patch: 3,
pre: Prerelease::new("").unwrap(),
build: BuildMetadata::EMPTY,
},
dependencies: vec![],
},
Package {
name: "@scope/package-b",
version: semver::Version {
major: 3,
minor: 2,
patch: 0,
pre: Prerelease::new("").unwrap(),
build: BuildMetadata::EMPTY,
},
dependencies: vec![Dependency {
name: "@scope/package-a",
version: "=1.2.3".parse().unwrap(),
}],
},
Package {
name: "@scope/package-c",
version: semver::Version {
major: 11,
minor: 2,
patch: 4,
pre: Prerelease::new("").unwrap(),
build: BuildMetadata::EMPTY,
},
dependencies: vec![Dependency {
name: "@scope/package-b",
version: ">=3.0.0".parse().unwrap(),
}],
},
];
let graph = DependencyGraph::from(&packages[..]);
for package in graph {
match package {
// Print out the package name so we can verify the order ourselves
Step::Resolved(package) => println!("Building {}!", package.name),
// Since we know that all our Packages only have internal references to each other,
// we can safely ignore any Unresolved steps in the graph.
//
// If for example `second_order` required some unknown package `external_package`,
// iterating over our graph would yield that as a Step::Unresolved *before*
// the `second_order` package.
Step::Unresolved(_) => unreachable!(),
}
}
}
}