dep_tree/
lib.rs

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
use std::{
  cell::RefCell,
  collections::{btree_map::Entry, BTreeMap, BTreeSet},
  rc::Rc,
};
use thiserror::Error;

pub type DepId = (u64, usize);

#[derive(Clone, Debug, Error)]
pub enum DepTreeBuilderError {
  #[error("unit `{0:?}` depends on itself")]
  SelfDependency(DepId),
  #[error("unit `{0:?}` recurses when depending on `{1:?}`, `{2}`")]
  CircularDependency(DepId, DepId, String),
}

pub type DepTreeBuilderResult<T> = Result<T, DepTreeBuilderError>;

#[derive(Clone, Debug, Default)]
pub struct DepTreeBuilder {
  inner: Rc<RefCell<Box<BTreeMap<DepId, Vec<DepId>>>>>,
}

impl DepTreeBuilder {
  pub fn new() -> Self {
    Self::default()
  }

  pub fn with_dep(&mut self, id: DepId, deps: Vec<DepId>) -> Self {
    let mut inner_lock = self.inner.try_borrow_mut().unwrap();
    match inner_lock.entry(id) {
      Entry::Vacant(entry) => {
        entry.insert(deps);
      }
      Entry::Occupied(mut entry) => {
        entry.get_mut().extend(deps);
      }
    }
    self.clone()
  }
  
  pub fn build(self) -> DepTreeBuilderResult<Box<DepTree>> {
    let inner = self.inner.try_borrow().unwrap();
    let (mut visited, mut resolved): (
      Vec<DepId>,
      BTreeMap<DepId, Vec<DepId>>,
    ) = (
      Vec::new(),
      BTreeMap::new(),
    );
    for (unit, deps) in inner.clone().into_iter() {
      if deps.contains(&unit) {
        return Err(DepTreeBuilderError::SelfDependency(unit));
      }
      let mut stack = Vec::new();
      if self.has_circular_dependency(unit, &inner, &mut visited, &mut stack) {
        return Err(DepTreeBuilderError::CircularDependency(
          *stack.first().unwrap(),
          *stack.last().unwrap(),
          stack
            .iter()
            .map(|(id, version)| format!("({id}, {version})"))
            .collect::<Vec<_>>()
            .join(" -> ")
        ));
      }
      resolved.insert(unit, deps);
    }
    Ok(Box::new(DepTree::new(Rc::new(resolved))))
  }

  fn has_circular_dependency(
    &self,
    unit: DepId,
    tree: &BTreeMap<DepId, Vec<DepId>>,
    visited: &mut Vec<DepId>,
    stack: &mut Vec<DepId>,
  ) -> bool {
    if visited.contains(&unit) {
      return false;
    }
    if stack.contains(&unit) {
      return true;
    }
    stack.push(unit);
    if let Some(deps) = tree.get(&unit) {
      for &dep in deps {
        if self.has_circular_dependency(dep, tree, visited, stack) {
          return true;
        }
      }
    }
    stack.pop();
    visited.push(unit);
    false
  }
}

#[derive(Clone, Debug, Default)]
pub struct DepTree {
  inner: Rc<BTreeMap<DepId, Vec<DepId>>>,
}

impl DepTree {
  pub fn new(inner: Rc<BTreeMap<DepId, Vec<DepId>>>) -> Self {
    Self { inner }
  }
  
  pub fn most_dependencies(&self) -> Vec<(DepId, usize)> {
    let mut dependency_counts = self.inner.keys().map(|id| {
      let count = self.count_dependencies(id, &mut BTreeSet::new());
      (*id, count)
    }).collect::<Vec<_>>();

    dependency_counts.sort_by(|a, b| b.1.cmp(&a.1));
    dependency_counts
  }

  pub fn most_dependents(&self) -> Vec<(DepId, usize)> {
    let mut dependent_counts = self.calculate_dependents();
    dependent_counts.sort_by(|a, b| b.1.cmp(&a.1));
    dependent_counts
  }

  pub fn least_dependencies(&self) -> Vec<(DepId, usize)> {
    let mut dependency_counts = self.inner.keys().map(|id| {
      let count = self.count_dependencies(id, &mut BTreeSet::new());
      (*id, count)
    }).collect::<Vec<_>>();

    dependency_counts.sort_by(|a, b| a.1.cmp(&b.1));
    dependency_counts
  }

  pub fn least_dependents(&self) -> Vec<(DepId, usize)> {
    let mut dependent_counts = self.calculate_dependents();
    dependent_counts.sort_by(|a, b| a.1.cmp(&b.1));
    dependent_counts
  }

  pub fn dependencies_of(&self, unit: DepId) -> Vec<DepId> {
    let mut visited = BTreeSet::new();
    let mut dependencies = Vec::new();
    self.collect_dependencies(&unit, &mut visited, &mut dependencies);
    dependencies
  }

  pub fn dependents_of(&self, unit: DepId) -> Vec<DepId> {
    self.inner
      .iter()
      .filter_map(|(&key, deps)| {
        if deps.contains(&unit) {
          Some(key)
        } else {
          None
        }
      })
      .collect()
  }

  fn count_dependencies(&self, id: &DepId, visited: &mut BTreeSet<DepId>) -> usize {
    if !visited.insert(*id) {
      return 0;
    }
    self.inner
      .get(id)
      .map(|deps| {
        deps
          .iter()
          .map(|dep| 1 + self.count_dependencies(dep, visited))
          .sum()
      })
      .unwrap_or(0)
  }

  fn collect_dependencies(&self, id: &DepId, visited: &mut BTreeSet<DepId>, dependencies: &mut Vec<DepId>) {
    if !visited.insert(*id) {
      return;
    }
    if let Some(deps) = self.inner.get(id) {
      for dep in deps {
        dependencies.push(*dep);
        self.collect_dependencies(dep, visited, dependencies);
      }
    }
  }

  fn calculate_dependents(&self) -> Vec<(DepId, usize)> {
    let mut dependent_map: BTreeMap<DepId, usize> = BTreeMap::new();
    
    for (&key, deps) in self.inner.iter() {
      for &dep in deps {
        *dependent_map.entry(dep).or_insert(0) += 1;
      }
      dependent_map.entry(key).or_insert(0);
    }

    dependent_map.into_iter().collect()
  }
}