Skip to content

Commit 1cbefec

Browse files
committed
Add find_shortest_cycle to rust graph
1 parent f29fc2c commit 1cbefec

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

rust/src/graph/cycles.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
use crate::errors::GrimpResult;
2+
use crate::graph::pathfinding;
3+
use crate::graph::{ExtendWithDescendants, Graph, ModuleToken};
4+
use rustc_hash::{FxHashMap, FxHashSet};
5+
use tap::Conv;
6+
7+
impl Graph {
8+
pub fn find_shortest_cycle(
9+
&self,
10+
module: ModuleToken,
11+
as_package: bool,
12+
) -> GrimpResult<Option<Vec<ModuleToken>>> {
13+
if as_package {
14+
pathfinding::find_shortest_cycle(
15+
self,
16+
&module.conv::<FxHashSet<_>>().with_descendants(self),
17+
&FxHashSet::default(),
18+
&FxHashMap::default(),
19+
)
20+
} else {
21+
pathfinding::find_shortest_cycle(
22+
self,
23+
&module.conv::<FxHashSet<_>>(),
24+
&FxHashSet::default(),
25+
&FxHashMap::default(),
26+
)
27+
}
28+
}
29+
}

rust/src/graph/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use std::sync::RwLock;
88
use string_interner::backend::StringBackend;
99
use string_interner::{DefaultSymbol, StringInterner};
1010

11+
pub mod cycles;
1112
pub mod direct_import_queries;
1213
pub mod graph_manipulation;
1314
pub mod hierarchy_queries;

rust/src/lib.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -353,6 +353,25 @@ impl GraphWrapper {
353353
PySet::new(py, chains)
354354
}
355355

356+
#[pyo3(signature = (module, as_package=false))]
357+
pub fn find_shortest_cycle(
358+
&self,
359+
module: &str,
360+
as_package: bool,
361+
) -> PyResult<Option<Vec<String>>> {
362+
let module = self.get_visible_module_by_name(module)?.token();
363+
Ok(self
364+
._graph
365+
.find_shortest_cycle(module, as_package)?
366+
.map(|chain| {
367+
chain
368+
.iter()
369+
.into_module_iterator(&self._graph)
370+
.names()
371+
.collect()
372+
}))
373+
}
374+
356375
#[pyo3(signature = (layers, containers))]
357376
pub fn find_illegal_dependencies_for_layers<'py>(
358377
&self,

0 commit comments

Comments
 (0)