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
use petgraph::visit::DfsPostOrder;
use petgraph::Graph;
use std::error::Error;

/// A node of a dependency graph.
pub trait DependencyNode<T, E>
where
    T: PartialEq,
{
    fn id(&self) -> T;

    /// The dependencies of a node
    ///
    /// # Errors
    ///
    /// Will return an `Err` if the dependencies can't be accessed
    fn dependencies(&self) -> Result<Vec<T>, E>;
}

/// Create a [`Graph`] from [`DependencyNode`]s.
///
/// # Errors
///
/// Will return an `Err` if the graph contains references to missing dependencies or the
/// dependencies of a [`DependencyNode`] couldn't be gathered.
pub(crate) fn create_dependency_graph<T, I, E>(
    nodes: Vec<T>,
) -> Result<Graph<T, ()>, CreateDependencyGraphError<I, E>>
where
    T: DependencyNode<I, E>,
    I: PartialEq,
    E: Error,
{
    let mut graph = Graph::new();

    for node in nodes {
        graph.add_node(node);
    }

    for idx in graph.node_indices() {
        let node = &graph[idx];

        let dependencies = node
            .dependencies()
            .map_err(CreateDependencyGraphError::GetNodeDependenciesError)?;

        for dependency in dependencies {
            let dependency_idx = graph
                .node_indices()
                .find(|idx| graph[*idx].id() == dependency)
                .ok_or(CreateDependencyGraphError::MissingDependency(dependency))?;

            graph.add_edge(idx, dependency_idx, ());
        }
    }

    Ok(graph)
}

/// An error that occurred while creating the dependency graph.
#[derive(thiserror::Error, Debug)]
pub enum CreateDependencyGraphError<I, E: Error> {
    #[error("Error while determining dependencies of a node: {0}")]
    GetNodeDependenciesError(#[source] E),
    #[error("Node references unknown dependency {0}")]
    MissingDependency(I),
}

/// Collects all the [`DependencyNode`] values found while traversing the given dependency graph
/// using one or more `root_nodes` values as starting points for the traversal. The returned list
/// will contain the given `root_nodes` values as well as all their dependencies in topological order.
///
/// # Errors
///
/// Will return an `Err` if the graph contains references to missing dependencies.
pub fn get_dependencies<'a, T, I, E>(
    graph: &'a Graph<T, ()>,
    root_nodes: &[&T],
) -> Result<Vec<&'a T>, GetDependenciesError<I>>
where
    T: DependencyNode<I, E>,
    I: PartialEq,
{
    let mut order: Vec<&T> = Vec::new();
    let mut dfs = DfsPostOrder::empty(&graph);
    for root_node in root_nodes {
        let idx = graph
            .node_indices()
            .find(|idx| graph[*idx].id() == root_node.id())
            .ok_or(GetDependenciesError::UnknownRootNode(root_node.id()))?;

        dfs.move_to(idx);

        while let Some(visited) = dfs.next(&graph) {
            order.push(&graph[visited]);
        }
    }
    Ok(order)
}

/// An error from [`get_dependencies`]
#[derive(thiserror::Error, Debug)]
pub enum GetDependenciesError<I> {
    #[error("Root node {0} is not in the dependency graph")]
    UnknownRootNode(I),
}

#[cfg(test)]
mod tests {
    use crate::dependency_graph::{create_dependency_graph, get_dependencies, DependencyNode};
    use std::convert::Infallible;

    impl DependencyNode<String, Infallible> for (&str, Vec<&str>) {
        fn id(&self) -> String {
            self.0.to_string()
        }

        fn dependencies(&self) -> Result<Vec<String>, Infallible> {
            Ok(self
                .1
                .iter()
                .map(std::string::ToString::to_string)
                .collect())
        }
    }

    #[test]
    fn test_get_dependencies_one_level_deep() {
        let a = ("a", Vec::new());
        let b = ("b", Vec::new());
        let c = ("c", vec!["a", "b"]);

        let graph = create_dependency_graph(vec![a.clone(), b.clone(), c.clone()]).unwrap();

        assert_eq!(get_dependencies(&graph, &[&a]).unwrap(), &[&a]);

        assert_eq!(get_dependencies(&graph, &[&b]).unwrap(), &[&b]);

        assert_eq!(get_dependencies(&graph, &[&c]).unwrap(), &[&a, &b, &c]);

        assert_eq!(
            &get_dependencies(&graph, &[&b, &c, &a]).unwrap(),
            &[&b, &a, &c]
        );
    }

    #[test]
    fn test_get_dependencies_two_levels_deep() {
        let a = ("a", Vec::new());
        let b = ("b", vec!["a"]);
        let c = ("c", vec!["b"]);

        let graph = create_dependency_graph(vec![a.clone(), b.clone(), c.clone()]).unwrap();

        assert_eq!(get_dependencies(&graph, &[&a]).unwrap(), &[&a]);

        assert_eq!(get_dependencies(&graph, &[&b]).unwrap(), &[&a, &b]);

        assert_eq!(get_dependencies(&graph, &[&c]).unwrap(), &[&a, &b, &c]);

        assert_eq!(
            &get_dependencies(&graph, &[&b, &c, &a]).unwrap(),
            &[&a, &b, &c]
        );
    }

    #[test]
    #[allow(clippy::many_single_char_names)]
    fn test_get_dependencies_with_overlap() {
        let a = ("a", Vec::new());
        let b = ("b", Vec::new());
        let c = ("c", Vec::new());
        let d = ("d", vec!["a", "b"]);
        let e = ("e", vec!["b", "c"]);

        let graph =
            create_dependency_graph(vec![a.clone(), b.clone(), c.clone(), d.clone(), e.clone()])
                .unwrap();

        assert_eq!(
            get_dependencies(&graph, &[&d, &e, &a]).unwrap(),
            &[&a, &b, &d, &c, &e]
        );

        assert_eq!(
            get_dependencies(&graph, &[&e, &d, &a]).unwrap(),
            &[&b, &c, &e, &a, &d]
        );
    }
}