| 1 | #![allow(non_snake_case)] |
| 2 | |
| 3 | use vcs_graph::bfs::BfsState; |
| 4 | use vcs_graph::graph::{Graph as RsGraph, GraphError}; |
| 5 | use vcs_graph::known_graph::KnownGraph as RsKnownGraph; |
| 6 | use vcs_graph::{ |
| 7 | CachingParentsProvider as RsCachingParentsProvider, ChildMap, ParentMap, Parents, |
| 8 | ParentsProvider, RevnoVec, |
| 9 | }; |
| 10 | |
| 11 | use pyo3::import_exception; |
| 12 | use pyo3::prelude::*; |
| 13 | use pyo3::types::{PyDict, PyList, PyTuple}; |
| 14 | use pyo3::wrap_pyfunction; |
| 15 | use std::collections::{HashMap, HashSet}; |
| 16 | use std::hash::Hash; |
| 17 | |
| 18 | import_exception!(vcsgraph.errors, GraphCycleError); |
| 19 | |
| 20 | struct PyNode(Py<PyAny>); |
| 21 | |
| 22 | impl std::fmt::Debug for PyNode { |
| 23 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { |
| 24 | Python::attach(|py| { |
| 25 | let repr = self.0.bind(py).repr(); |
| 26 | if PyErr::occurred(py) { |
| 27 | return Err(std::fmt::Error); |
| 28 | } |
| 29 | if let Ok(repr) = repr { |
| 30 | write!(f, "{}", repr) |
| 31 | } else { |
| 32 | write!(f, "???") |
| 33 | } |
| 34 | }) |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | impl std::fmt::Display for PyNode { |
| 39 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { |
| 40 | Python::attach(|py| { |
| 41 | let repr = self.0.bind(py).repr(); |
| 42 | if PyErr::occurred(py) { |
| 43 | return Err(std::fmt::Error); |
| 44 | } |
| 45 | if let Ok(repr) = repr { |
| 46 | write!(f, "{}", repr) |
| 47 | } else { |
| 48 | write!(f, "???") |
| 49 | } |
| 50 | }) |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | impl Clone for PyNode { |
| 55 | fn clone(&self) -> PyNode { |
| 56 | Python::attach(|py| PyNode(self.0.clone_ref(py))) |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | impl From<Py<PyAny>> for PyNode { |
| 61 | fn from(obj: Py<PyAny>) -> PyNode { |
| 62 | PyNode(obj) |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | impl<'a> From<Bound<'a, PyAny>> for PyNode { |
| 67 | fn from(obj: Bound<'a, PyAny>) -> PyNode { |
| 68 | PyNode(obj.unbind()) |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | impl<'py> FromPyObject<'_, 'py> for PyNode { |
| 73 | type Error = PyErr; |
| 74 | |
| 75 | fn extract(obj: Borrowed<'_, 'py, PyAny>) -> Result<Self, Self::Error> { |
| 76 | Ok(PyNode(obj.to_owned().unbind())) |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | impl<'py> IntoPyObject<'py> for PyNode { |
| 81 | type Target = PyAny; |
| 82 | |
| 83 | type Output = Bound<'py, Self::Target>; |
| 84 | |
| 85 | type Error = PyErr; |
| 86 | |
| 87 | fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { |
| 88 | Ok(self.0.clone_ref(py).into_bound(py)) |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | impl Hash for PyNode { |
| 93 | fn hash<H: std::hash::Hasher>(&self, state: &mut H) { |
| 94 | Python::attach(|py| match self.0.bind(py).hash() { |
| 95 | Err(err) => err.restore(py), |
| 96 | Ok(hash) => state.write_isize(hash), |
| 97 | }); |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | impl PartialEq for PyNode { |
| 102 | fn eq(&self, other: &PyNode) -> bool { |
| 103 | Python::attach(|py| match self.0.bind(py).eq(other.0.bind(py)) { |
| 104 | Err(err) => { |
| 105 | err.restore(py); |
| 106 | false |
| 107 | } |
| 108 | Ok(b) => b, |
| 109 | }) |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | impl std::cmp::Eq for PyNode {} |
| 114 | |
| 115 | impl PartialOrd for PyNode { |
| 116 | fn partial_cmp(&self, other: &PyNode) -> Option<std::cmp::Ordering> { |
| 117 | self.cmp(other).into() |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | impl Ord for PyNode { |
| 122 | fn cmp(&self, other: &PyNode) -> std::cmp::Ordering { |
| 123 | Python::attach(|py| match self.0.bind(py).lt(other.0.bind(py)) { |
| 124 | Err(err) => { |
| 125 | err.restore(py); |
| 126 | std::cmp::Ordering::Equal |
| 127 | } |
| 128 | Ok(b) => { |
| 129 | if b { |
| 130 | std::cmp::Ordering::Less |
| 131 | } else { |
| 132 | match self.0.bind(py).gt(other.0.bind(py)) { |
| 133 | Err(err) => { |
| 134 | err.restore(py); |
| 135 | std::cmp::Ordering::Equal |
| 136 | } |
| 137 | Ok(b) => { |
| 138 | if b { |
| 139 | std::cmp::Ordering::Greater |
| 140 | } else { |
| 141 | std::cmp::Ordering::Equal |
| 142 | } |
| 143 | } |
| 144 | } |
| 145 | } |
| 146 | } |
| 147 | }) |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | /// Given a map from child => parents, create a map of parent => children |
| 152 | #[pyfunction] |
| 153 | fn invert_parent_map(parent_map: ParentMap<PyNode>) -> ChildMap<PyNode> { |
| 154 | vcs_graph::invert_parent_map::<PyNode>(&parent_map) |
| 155 | } |
| 156 | |
| 157 | /// Collapse regions of the graph that are 'linear'. |
| 158 | /// |
| 159 | /// For example:: |
| 160 | /// |
| 161 | /// A:[B], B:[C] |
| 162 | /// |
| 163 | /// can be collapsed by removing B and getting:: |
| 164 | /// |
| 165 | /// A:[C] |
| 166 | /// |
| 167 | /// :param parent_map: A dictionary mapping children to their parents |
| 168 | /// :return: Another dictionary with 'linear' chains collapsed |
| 169 | #[pyfunction] |
| 170 | fn collapse_linear_regions(parent_map: ParentMap<PyNode>) -> PyResult<ParentMap<PyNode>> { |
| 171 | Ok(vcs_graph::collapse_linear_regions::<PyNode>(&parent_map)) |
| 172 | } |
| 173 | |
| 174 | /// A parents provider for Graph objects, backed by a dict. |
| 175 | /// |
| 176 | /// Mirrors `vcsgraph.graph.DictParentsProvider`: takes a mapping of |
| 177 | /// `{key: parents_tuple}` and serves `get_parent_map` lookups from it. |
| 178 | /// The dict is consulted on every call so mutations after construction |
| 179 | /// are visible — matching the original Python implementation. |
| 180 | #[pyclass(name = "DictParentsProvider", dict)] |
| 181 | struct PyDictParentsProvider { |
| 182 | ancestry: Py<PyAny>, |
| 183 | } |
| 184 | |
| 185 | impl PyDictParentsProvider { |
| 186 | fn lookup(&self, py: Python<'_>, keys: &HashSet<PyNode>) -> ParentMap<PyNode> { |
| 187 | let ancestry = self.ancestry.bind(py); |
| 188 | let mut pm = ParentMap::new(); |
| 189 | for k in keys { |
| 190 | let key_obj = k.0.bind(py); |
| 191 | let v_obj = match ancestry.get_item(key_obj) { |
| 192 | Ok(v) => v, |
| 193 | Err(_) => continue, |
| 194 | }; |
| 195 | let Ok(iter) = v_obj.try_iter() else { |
| 196 | continue; |
| 197 | }; |
| 198 | let mut parents: Vec<PyNode> = Vec::new(); |
| 199 | let mut ok = true; |
| 200 | for p in iter { |
| 201 | match p { |
| 202 | Ok(p) => parents.push(PyNode::from(p.unbind())), |
| 203 | Err(_) => { |
| 204 | ok = false; |
| 205 | break; |
| 206 | } |
| 207 | } |
| 208 | } |
| 209 | if ok { |
| 210 | pm.insert(k.clone(), Parents::Known(parents)); |
| 211 | } |
| 212 | } |
| 213 | pm |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | #[pymethods] |
| 218 | impl PyDictParentsProvider { |
| 219 | #[new] |
| 220 | fn new(ancestry: Py<PyAny>) -> PyResult<Self> { |
| 221 | Ok(PyDictParentsProvider { ancestry }) |
| 222 | } |
| 223 | |
| 224 | /// The underlying mapping, preserved as the original Python object. |
| 225 | #[getter] |
| 226 | fn ancestry(&self, py: Python) -> Py<PyAny> { |
| 227 | self.ancestry.clone_ref(py) |
| 228 | } |
| 229 | |
| 230 | fn __repr__(&self, py: Python) -> PyResult<String> { |
| 231 | let r = self.ancestry.bind(py).repr()?; |
| 232 | Ok(format!("DictParentsProvider({})", r)) |
| 233 | } |
| 234 | |
| 235 | fn get_parent_map<'py>( |
| 236 | &self, |
| 237 | py: Python<'py>, |
| 238 | keys: Py<PyAny>, |
| 239 | ) -> PyResult<Bound<'py, PyDict>> { |
| 240 | let nodes = extract_iter_pynodes(py, &keys)?; |
| 241 | let hs: HashSet<PyNode> = nodes.into_iter().collect(); |
| 242 | let pm = self.lookup(py, &hs); |
| 243 | parent_map_to_pydict(py, pm) |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | impl ParentsProvider<PyNode> for PyDictParentsProvider { |
| 248 | fn get_parent_map(&self, keys: &HashSet<PyNode>) -> ParentMap<PyNode> { |
| 249 | Python::attach(|py| self.lookup(py, keys)) |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | /// A parents provider which stacks multiple child providers. Each child is |
| 254 | /// queried in order, matching `vcsgraph.graph.StackedParentsProvider`. |
| 255 | /// |
| 256 | /// If a child exposes `get_cached_parent_map`, that fast path is queried |
| 257 | /// first for all children before any full `get_parent_map` call — just |
| 258 | /// like the Python version. |
| 259 | /// |
| 260 | /// The provider iterable is stored as-is and re-iterated on every |
| 261 | /// `get_parent_map` call, so live mutations (e.g. appending a fallback to |
| 262 | /// the list passed in) take effect on subsequent lookups. |
| 263 | #[pyclass(name = "StackedParentsProvider")] |
| 264 | struct PyStackedParentsProvider { |
| 265 | parent_providers: Py<PyAny>, |
| 266 | } |
| 267 | |
| 268 | #[pymethods] |
| 269 | impl PyStackedParentsProvider { |
| 270 | #[new] |
| 271 | fn new(parent_providers: Py<PyAny>) -> PyResult<Self> { |
| 272 | Ok(PyStackedParentsProvider { parent_providers }) |
| 273 | } |
| 274 | |
| 275 | fn __repr__(&self, py: Python) -> PyResult<String> { |
| 276 | let r = self.parent_providers.bind(py).repr()?; |
| 277 | Ok(format!("StackedParentsProvider({})", r)) |
| 278 | } |
| 279 | |
| 280 | fn get_parent_map<'py>( |
| 281 | &self, |
| 282 | py: Python<'py>, |
| 283 | keys: Py<PyAny>, |
| 284 | ) -> PyResult<Bound<'py, PyDict>> { |
| 285 | let found = PyDict::new(py); |
| 286 | let remaining = pyo3::types::PySet::empty(py)?; |
| 287 | for k in keys.bind(py).try_iter()? { |
| 288 | remaining.add(k?.unbind())?; |
| 289 | } |
| 290 | |
| 291 | // First pass: any provider that implements get_cached_parent_map |
| 292 | // gets queried cheaply before we hit the slow path. |
| 293 | for pp in self.parent_providers.bind(py).try_iter()? { |
| 294 | if remaining.is_empty() { |
| 295 | break; |
| 296 | } |
| 297 | let pp = pp?; |
| 298 | let get_cached = pp.getattr("get_cached_parent_map"); |
| 299 | let Ok(get_cached) = get_cached else { |
| 300 | continue; |
| 301 | }; |
| 302 | if get_cached.is_none() { |
| 303 | continue; |
| 304 | } |
| 305 | let new_found = get_cached.call1((remaining.clone(),))?; |
| 306 | let new_found_dict = new_found.cast::<PyDict>()?; |
| 307 | for (k, v) in new_found_dict.iter() { |
| 308 | found.set_item(&k, v)?; |
| 309 | remaining.discard(&k)?; |
| 310 | } |
| 311 | } |
| 312 | if remaining.is_empty() { |
| 313 | return Ok(found); |
| 314 | } |
| 315 | |
| 316 | // Second pass: full get_parent_map calls, in order. |
| 317 | for pp in self.parent_providers.bind(py).try_iter()? { |
| 318 | if remaining.is_empty() { |
| 319 | break; |
| 320 | } |
| 321 | let pp = pp?; |
| 322 | let new_found = match pp.call_method1("get_parent_map", (remaining.clone(),)) { |
| 323 | Ok(r) => r, |
| 324 | Err(err) => { |
| 325 | // Match Python's behaviour of catching UnsupportedOperation |
| 326 | // and moving on. |
| 327 | if err.get_type(py).is(&py |
| 328 | .import("vcsgraph.errors")? |
| 329 | .getattr("UnsupportedOperation")?) |
| 330 | { |
| 331 | continue; |
| 332 | } |
| 333 | return Err(err); |
| 334 | } |
| 335 | }; |
| 336 | let new_found_dict = new_found.cast::<PyDict>()?; |
| 337 | for (k, v) in new_found_dict.iter() { |
| 338 | found.set_item(&k, v)?; |
| 339 | remaining.discard(&k)?; |
| 340 | } |
| 341 | } |
| 342 | Ok(found) |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | /// A parents provider that wraps any `get_parent_map`-like callable. |
| 347 | /// |
| 348 | /// Mirrors `vcsgraph.graph.CallableToParentsProviderAdapter`. |
| 349 | #[pyclass(name = "CallableToParentsProviderAdapter")] |
| 350 | struct PyCallableToParentsProviderAdapter { |
| 351 | callable: Py<PyAny>, |
| 352 | } |
| 353 | |
| 354 | #[pymethods] |
| 355 | impl PyCallableToParentsProviderAdapter { |
| 356 | #[new] |
| 357 | fn new(callable: Py<PyAny>) -> Self { |
| 358 | PyCallableToParentsProviderAdapter { callable } |
| 359 | } |
| 360 | |
| 361 | fn __repr__(&self, py: Python) -> PyResult<String> { |
| 362 | let r = self.callable.bind(py).repr()?; |
| 363 | Ok(format!("CallableToParentsProviderAdapter({})", r)) |
| 364 | } |
| 365 | |
| 366 | fn get_parent_map(&self, py: Python, keys: Py<PyAny>) -> PyResult<Py<PyAny>> { |
| 367 | Ok(self.callable.bind(py).call1((keys,))?.unbind()) |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | #[pyclass] |
| 372 | struct TopoSorter { |
| 373 | sorter: vcs_graph::tsort::TopoSorter<PyNode>, |
| 374 | } |
| 375 | |
| 376 | #[pymethods] |
| 377 | impl TopoSorter { |
| 378 | #[new] |
| 379 | fn new(py: Python, graph: Py<PyAny>) -> PyResult<TopoSorter> { |
| 380 | let iter = if graph.bind(py).is_instance_of::<PyDict>() { |
| 381 | graph |
| 382 | .cast_bound::<PyDict>(py)? |
| 383 | .call_method0("items")? |
| 384 | .try_iter()? |
| 385 | } else { |
| 386 | graph.bind(py).try_iter()? |
| 387 | }; |
| 388 | let graph = iter |
| 389 | .map(|k| k?.extract::<(Py<PyAny>, Vec<Py<PyAny>>)>()) |
| 390 | .map(|k| k.map(|(k, vs)| (PyNode::from(k), vs.into_iter().map(PyNode::from).collect()))) |
| 391 | .collect::<PyResult<Vec<(PyNode, Vec<PyNode>)>>>()?; |
| 392 | |
| 393 | let sorter = vcs_graph::tsort::TopoSorter::<PyNode>::new(graph.into_iter()); |
| 394 | Ok(TopoSorter { sorter }) |
| 395 | } |
| 396 | |
| 397 | fn __next__(&mut self, py: Python) -> PyResult<Option<Py<PyAny>>> { |
| 398 | match self.sorter.next() { |
| 399 | None => Ok(None), |
| 400 | Some(Ok(node)) => Ok(Some(node.into_pyobject(py)?.unbind())), |
| 401 | Some(Err(vcs_graph::Error::Cycle(e))) => Err(GraphCycleError::new_err(e)), |
| 402 | Some(Err(e)) => panic!("Unexpected error: {:?}", e), |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | fn __iter__(slf: PyRefMut<Self>) -> PyRefMut<Self> { |
| 407 | slf |
| 408 | } |
| 409 | |
| 410 | fn iter_topo_order(slf: PyRefMut<Self>) -> PyRefMut<Self> { |
| 411 | slf |
| 412 | } |
| 413 | |
| 414 | fn sorted(&mut self, py: Python) -> PyResult<Vec<Py<PyAny>>> { |
| 415 | let mut ret = Vec::new(); |
| 416 | while let Some(node) = self.__next__(py)? { |
| 417 | ret.push(node); |
| 418 | } |
| 419 | Ok(ret) |
| 420 | } |
| 421 | } |
| 422 | |
| 423 | fn revno_vec_to_py(py: Python, revno: RevnoVec) -> Py<PyAny> { |
| 424 | PyTuple::new(py, revno.into_iter().map(|v| v.into_pyobject(py).unwrap())) |
| 425 | .unwrap() |
| 426 | .into_any() |
| 427 | .unbind() |
| 428 | } |
| 429 | |
| 430 | #[pyclass] |
| 431 | struct MergeSorter { |
| 432 | sorter: vcs_graph::tsort::MergeSorter<PyNode>, |
| 433 | } |
| 434 | |
| 435 | fn branch_tip_is_null(py: Python, branch_tip: Py<PyAny>) -> bool { |
| 436 | if let Ok(branch_tip) = branch_tip.extract::<&[u8]>(py) { |
| 437 | branch_tip == b"null:" |
| 438 | } else if let Ok((branch_tip,)) = branch_tip.extract::<(Vec<u8>,)>(py) { |
| 439 | branch_tip.as_slice() == b"null:" |
| 440 | } else { |
| 441 | false |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | #[pymethods] |
| 446 | impl MergeSorter { |
| 447 | #[new] |
| 448 | #[pyo3(signature = (graph, branch_tip=None, mainline_revisions=None, generate_revno=false))] |
| 449 | fn new( |
| 450 | py: Python, |
| 451 | graph: Py<PyAny>, |
| 452 | mut branch_tip: Option<Py<PyAny>>, |
| 453 | mainline_revisions: Option<Py<PyAny>>, |
| 454 | generate_revno: Option<bool>, |
| 455 | ) -> PyResult<MergeSorter> { |
| 456 | let iter = if graph.bind(py).is_instance_of::<PyDict>() { |
| 457 | graph |
| 458 | .cast_bound::<PyDict>(py)? |
| 459 | .call_method0("items")? |
| 460 | .try_iter()? |
| 461 | } else { |
| 462 | graph.bind(py).try_iter()? |
| 463 | }; |
| 464 | let graph = iter |
| 465 | .map(|k| k?.extract::<(Py<PyAny>, Vec<Py<PyAny>>)>()) |
| 466 | .map(|k| k.map(|(k, vs)| (PyNode::from(k), vs.into_iter().map(PyNode::from).collect()))) |
| 467 | .collect::<PyResult<HashMap<PyNode, Vec<PyNode>>>>()?; |
| 468 | |
| 469 | let mainline_revisions = if let Some(mainline_revisions) = mainline_revisions { |
| 470 | let mainline_revisions = mainline_revisions |
| 471 | .bind(py) |
| 472 | .try_iter()? |
| 473 | .map(|k| { |
| 474 | let item = k?; |
| 475 | Ok(item.extract::<Py<PyAny>>()?) |
| 476 | }) |
| 477 | .collect::<PyResult<Vec<Py<PyAny>>>>()?; |
| 478 | Some(mainline_revisions.into_iter().map(PyNode::from).collect()) |
| 479 | } else { |
| 480 | None |
| 481 | }; |
| 482 | |
| 483 | // The null: revision doesn't exist in the graph, so don't attempt to remove it |
| 484 | if let Some(ref mut tip_obj) = branch_tip { |
| 485 | if branch_tip_is_null(py, tip_obj.clone_ref(py)) { |
| 486 | branch_tip = None; |
| 487 | } |
| 488 | } |
| 489 | |
| 490 | let sorter = vcs_graph::tsort::MergeSorter::<PyNode>::new( |
| 491 | graph, |
| 492 | branch_tip.map(PyNode::from), |
| 493 | mainline_revisions, |
| 494 | generate_revno.unwrap_or(false), |
| 495 | ); |
| 496 | Ok(MergeSorter { sorter }) |
| 497 | } |
| 498 | |
| 499 | fn __next__(&mut self, py: Python) -> PyResult<Option<Py<PyAny>>> { |
| 500 | match self.sorter.next() { |
| 501 | None => Ok(None), |
| 502 | Some(Ok((sequence_number, node, merge_depth, None, end_of_merge))) => Ok(Some( |
| 503 | ( |
| 504 | sequence_number, |
| 505 | node.into_pyobject(py)?.unbind(), |
| 506 | merge_depth, |
| 507 | end_of_merge, |
| 508 | ) |
| 509 | .into_pyobject(py)? |
| 510 | .unbind() |
| 511 | .into(), |
| 512 | )), |
| 513 | |
| 514 | Some(Ok((sequence_number, node, merge_depth, Some(revno), end_of_merge))) => Ok(Some( |
| 515 | ( |
| 516 | sequence_number, |
| 517 | node.into_pyobject(py)?.unbind(), |
| 518 | merge_depth, |
| 519 | revno_vec_to_py(py, revno), |
| 520 | end_of_merge, |
| 521 | ) |
| 522 | .into_pyobject(py)? |
| 523 | .unbind() |
| 524 | .into(), |
| 525 | )), |
| 526 | Some(Err(vcs_graph::Error::Cycle(e))) => Err(GraphCycleError::new_err(e)), |
| 527 | Some(Err(e)) => panic!("Unexpected error: {:?}", e), |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | fn __iter__(slf: PyRefMut<Self>) -> PyRefMut<Self> { |
| 532 | slf |
| 533 | } |
| 534 | |
| 535 | fn iter_topo_order(slf: PyRefMut<Self>) -> PyRefMut<Self> { |
| 536 | slf |
| 537 | } |
| 538 | |
| 539 | fn sorted<'a>(&mut self, py: Python<'a>) -> PyResult<Bound<'a, PyList>> { |
| 540 | let ret = PyList::empty(py); |
| 541 | loop { |
| 542 | let item = self.__next__(py)?; |
| 543 | if let Some(item) = item { |
| 544 | ret.append(item)?; |
| 545 | } else { |
| 546 | break; |
| 547 | } |
| 548 | } |
| 549 | Ok(ret) |
| 550 | } |
| 551 | } |
| 552 | |
| 553 | /// Topological sort a graph which groups merges. |
| 554 | /// |
| 555 | /// :param graph: sequence of pairs of node->parents_list. |
| 556 | /// :param branch_tip: the tip of the branch to graph. Revisions not |
| 557 | /// reachable from branch_tip are not included in the |
| 558 | /// output. |
| 559 | /// :param mainline_revisions: If not None this forces a mainline to be |
| 560 | /// used rather than synthesised from the graph. |
| 561 | /// This must be a valid path through some part |
| 562 | /// of the graph. If the mainline does not cover all |
| 563 | /// the revisions, output stops at the start of the |
| 564 | /// old revision listed in the mainline revisions |
| 565 | /// list. |
| 566 | /// The order for this parameter is oldest-first. |
| 567 | /// :param generate_revno: Optional parameter controlling the generation of |
| 568 | /// revision number sequences in the output. See the output description of |
| 569 | /// the MergeSorter docstring for details. |
| 570 | /// :result: See the MergeSorter docstring for details. |
| 571 | /// |
| 572 | /// Node identifiers can be any hashable object, and are typically strings. |
| 573 | #[pyfunction] |
| 574 | #[pyo3(signature = (graph, branch_tip=None, mainline_revisions=None, generate_revno=false))] |
| 575 | fn merge_sort( |
| 576 | py: Python, |
| 577 | graph: Py<PyAny>, |
| 578 | branch_tip: Option<Py<PyAny>>, |
| 579 | mainline_revisions: Option<Py<PyAny>>, |
| 580 | generate_revno: Option<bool>, |
| 581 | ) -> PyResult<Bound<PyList>> { |
| 582 | let mut sorter = MergeSorter::new(py, graph, branch_tip, mainline_revisions, generate_revno)?; |
| 583 | sorter.sorted(py) |
| 584 | } |
| 585 | |
| 586 | const NULL_REVISION: &[u8] = b"null:"; |
| 587 | |
| 588 | fn is_null_revision(py: Python, obj: &Py<PyAny>) -> bool { |
| 589 | if let Ok(b) = obj.extract::<&[u8]>(py) { |
| 590 | b == NULL_REVISION |
| 591 | } else { |
| 592 | false |
| 593 | } |
| 594 | } |
| 595 | |
| 596 | #[pyclass(name = "KnownGraph")] |
| 597 | struct PyKnownGraph { |
| 598 | inner: RsKnownGraph<PyNode>, |
| 599 | } |
| 600 | |
| 601 | fn extract_parent_map(py: Python, parent_map: Py<PyAny>) -> PyResult<Vec<(PyNode, Vec<PyNode>)>> { |
| 602 | let iter = if parent_map.bind(py).is_instance_of::<PyDict>() { |
| 603 | parent_map |
| 604 | .cast_bound::<PyDict>(py)? |
| 605 | .call_method0("items")? |
| 606 | .try_iter()? |
| 607 | } else { |
| 608 | parent_map.bind(py).try_iter()? |
| 609 | }; |
| 610 | iter.map(|k| k?.extract::<(Py<PyAny>, Vec<Py<PyAny>>)>()) |
| 611 | .map(|k| k.map(|(k, vs)| (PyNode::from(k), vs.into_iter().map(PyNode::from).collect()))) |
| 612 | .collect() |
| 613 | } |
| 614 | |
| 615 | #[pymethods] |
| 616 | impl PyKnownGraph { |
| 617 | #[new] |
| 618 | #[pyo3(signature = (parent_map, do_cache=true))] |
| 619 | fn new(py: Python, parent_map: Py<PyAny>, do_cache: Option<bool>) -> PyResult<Self> { |
| 620 | let pm = extract_parent_map(py, parent_map)?; |
| 621 | Ok(PyKnownGraph { |
| 622 | inner: RsKnownGraph::new(pm, do_cache.unwrap_or(true)), |
| 623 | }) |
| 624 | } |
| 625 | |
| 626 | /// Add a new node to the graph. If `key` was a ghost, it is filled in. |
| 627 | fn add_node( |
| 628 | &mut self, |
| 629 | py: Python, |
| 630 | key: Py<PyAny>, |
| 631 | parent_keys: Vec<Py<PyAny>>, |
| 632 | ) -> PyResult<()> { |
| 633 | let key = PyNode::from(key); |
| 634 | let parents: Vec<PyNode> = parent_keys.into_iter().map(PyNode::from).collect(); |
| 635 | self.inner |
| 636 | .add_node(key.clone(), parents) |
| 637 | .map_err(|e| match e { |
| 638 | vcs_graph::Error::ParentMismatch { |
| 639 | key, |
| 640 | expected, |
| 641 | actual, |
| 642 | } => { |
| 643 | let key_repr = format!("{:?}", key); |
| 644 | let expected_py: Vec<Py<PyAny>> = |
| 645 | expected.into_iter().map(|n| n.0.clone_ref(py)).collect(); |
| 646 | let actual_py: Vec<Py<PyAny>> = |
| 647 | actual.into_iter().map(|n| n.0.clone_ref(py)).collect(); |
| 648 | pyo3::exceptions::PyValueError::new_err(format!( |
| 649 | "Parent key mismatch, existing node {} has parents of {:?} not {:?}", |
| 650 | key_repr, expected_py, actual_py |
| 651 | )) |
| 652 | } |
| 653 | other => pyo3::exceptions::PyValueError::new_err(format!("{:?}", other)), |
| 654 | }) |
| 655 | } |
| 656 | |
| 657 | /// Return the parent keys for `key`. Returns `None` for ghosts; raises |
| 658 | /// `KeyError` if `key` is not in the graph. |
| 659 | fn get_parent_keys(&self, py: Python, key: Py<PyAny>) -> PyResult<Option<Vec<Py<PyAny>>>> { |
| 660 | let node = PyNode::from(key); |
| 661 | if !self.inner.contains(&node) { |
| 662 | return Err(pyo3::exceptions::PyKeyError::new_err(format!("{:?}", node))); |
| 663 | } |
| 664 | Ok(self |
| 665 | .inner |
| 666 | .get_parent_keys(&node) |
| 667 | .map(|ps| ps.iter().map(|n| n.0.clone_ref(py)).collect())) |
| 668 | } |
| 669 | |
| 670 | /// Return the child keys for `key`. Raises `KeyError` if `key` is not in |
| 671 | /// the graph. |
| 672 | fn get_child_keys(&self, py: Python, key: Py<PyAny>) -> PyResult<Vec<Py<PyAny>>> { |
| 673 | let node = PyNode::from(key); |
| 674 | match self.inner.get_child_keys(&node) { |
| 675 | Some(cs) => Ok(cs.iter().map(|n| n.0.clone_ref(py)).collect()), |
| 676 | None => Err(pyo3::exceptions::PyKeyError::new_err(format!("{:?}", node))), |
| 677 | } |
| 678 | } |
| 679 | |
| 680 | /// Return the heads from amongst `keys`. |
| 681 | fn heads<'py>(&mut self, py: Python<'py>, keys: Py<PyAny>) -> PyResult<Bound<'py, PyAny>> { |
| 682 | let mut candidates: Vec<Py<PyAny>> = Vec::new(); |
| 683 | let mut had_null = false; |
| 684 | for k in keys.bind(py).try_iter()? { |
| 685 | let item: Py<PyAny> = k?.extract()?; |
| 686 | if is_null_revision(py, &item) { |
| 687 | had_null = true; |
| 688 | } else { |
| 689 | candidates.push(item); |
| 690 | } |
| 691 | } |
| 692 | if candidates.is_empty() && had_null { |
| 693 | // NULL_REVISION is only a head if it's the only entry. |
| 694 | let fs = py.import("builtins")?.getattr("frozenset")?; |
| 695 | let null = pyo3::types::PyBytes::new(py, NULL_REVISION); |
| 696 | return fs.call1((vec![null.into_any()],)); |
| 697 | } |
| 698 | let nodes: Vec<PyNode> = candidates.into_iter().map(PyNode::from).collect(); |
| 699 | let heads = self.inner.heads(nodes); |
| 700 | let py_set: Vec<Py<PyAny>> = heads.into_iter().map(|n| n.0).collect(); |
| 701 | let fs = py.import("builtins")?.getattr("frozenset")?; |
| 702 | fs.call1((py_set,)) |
| 703 | } |
| 704 | |
| 705 | /// Return the nodes in topological order (parents first). |
| 706 | fn topo_sort(&self, py: Python) -> PyResult<Vec<Py<PyAny>>> { |
| 707 | match self.inner.topo_sort() { |
| 708 | Ok(v) => Ok(v.into_iter().map(|n| n.0.clone_ref(py)).collect()), |
| 709 | Err(vcs_graph::Error::Cycle(_)) => { |
| 710 | Err(GraphCycleError::new_err(("cycle in known graph",))) |
| 711 | } |
| 712 | Err(e) => Err(pyo3::exceptions::PyValueError::new_err(format!("{:?}", e))), |
| 713 | } |
| 714 | } |
| 715 | |
| 716 | /// Return a reverse topological ordering grouped by prefix. |
| 717 | /// |
| 718 | /// Mirrors the Python implementation: keys that are bytes use their first |
| 719 | /// byte as the prefix bucket; single-element keys use an empty prefix. |
| 720 | fn gc_sort(&self, py: Python) -> PyResult<Vec<Py<PyAny>>> { |
| 721 | let prefix_of = |k: &PyNode| -> Vec<u8> { |
| 722 | Python::attach(|py| { |
| 723 | let bound = k.0.bind(py); |
| 724 | if let Ok(b) = bound.extract::<&[u8]>() { |
| 725 | if b.len() == 1 { |
| 726 | Vec::new() |
| 727 | } else { |
| 728 | vec![b[0]] |
| 729 | } |
| 730 | } else if let Ok(s) = bound.extract::<&str>() { |
| 731 | if s.len() == 1 { |
| 732 | Vec::new() |
| 733 | } else { |
| 734 | vec![s.as_bytes()[0]] |
| 735 | } |
| 736 | } else if let Ok(first) = bound.get_item(0) { |
| 737 | if let Ok(b) = first.extract::<&[u8]>() { |
| 738 | b.to_vec() |
| 739 | } else if let Ok(s) = first.extract::<&str>() { |
| 740 | s.as_bytes().to_vec() |
| 741 | } else { |
| 742 | Vec::new() |
| 743 | } |
| 744 | } else { |
| 745 | Vec::new() |
| 746 | } |
| 747 | }) |
| 748 | }; |
| 749 | let v = self.inner.gc_sort(prefix_of); |
| 750 | Ok(v.into_iter().map(|n| n.0.clone_ref(py)).collect()) |
| 751 | } |
| 752 | |
| 753 | /// Compute the merge-sorted graph output starting at `tip_key`. |
| 754 | /// |
| 755 | /// If `tip_key` is `None`, `b"null:"`, or `(b"null:",)`, returns an empty |
| 756 | /// list (matches the Python null-tip semantics). |
| 757 | fn merge_sort( |
| 758 | &self, |
| 759 | py: Python, |
| 760 | tip_key: Py<PyAny>, |
| 761 | ) -> PyResult<Vec<Py<PyKnownGraphMergeSortNode>>> { |
| 762 | if tip_key.is_none(py) || branch_tip_is_null(py, tip_key.clone_ref(py)) { |
| 763 | return Ok(Vec::new()); |
| 764 | } |
| 765 | let tip = PyNode::from(tip_key); |
| 766 | if !self.inner.contains(&tip) { |
| 767 | return Ok(Vec::new()); |
| 768 | } |
| 769 | let result = self.inner.merge_sort(tip).map_err(|e| match e { |
| 770 | vcs_graph::Error::Cycle(_) => GraphCycleError::new_err(("cycle in known graph",)), |
| 771 | other => pyo3::exceptions::PyValueError::new_err(format!("{:?}", other)), |
| 772 | })?; |
| 773 | result |
| 774 | .into_iter() |
| 775 | .map(|n| { |
| 776 | let revno = revno_vec_to_py(py, n.revno); |
| 777 | Py::new( |
| 778 | py, |
| 779 | PyKnownGraphMergeSortNode { |
| 780 | key: n.key.0, |
| 781 | merge_depth: n.merge_depth, |
| 782 | revno, |
| 783 | end_of_merge: n.end_of_merge, |
| 784 | }, |
| 785 | ) |
| 786 | }) |
| 787 | .collect() |
| 788 | } |
| 789 | |
| 790 | /// Return a mapping-like view of all nodes in the graph, keyed by node |
| 791 | /// key. Each value is a `_KnownGraphNode` exposing live `key`, |
| 792 | /// `parent_keys`, `child_keys`, and `gdfo` attributes. |
| 793 | #[getter] |
| 794 | fn _nodes(slf: Py<Self>) -> PyKnownGraphNodesView { |
| 795 | PyKnownGraphNodesView { graph: slf } |
| 796 | } |
| 797 | } |
| 798 | |
| 799 | #[pyclass(name = "_KnownGraphNodesView")] |
| 800 | struct PyKnownGraphNodesView { |
| 801 | graph: Py<PyKnownGraph>, |
| 802 | } |
| 803 | |
| 804 | #[pymethods] |
| 805 | impl PyKnownGraphNodesView { |
| 806 | fn __getitem__(&self, py: Python, key: Py<PyAny>) -> PyResult<PyKnownGraphNode> { |
| 807 | let g = self.graph.borrow(py); |
| 808 | let node = PyNode::from(key.clone_ref(py)); |
| 809 | if !g.inner.contains(&node) { |
| 810 | return Err(pyo3::exceptions::PyKeyError::new_err(format!("{:?}", node))); |
| 811 | } |
| 812 | Ok(PyKnownGraphNode { |
| 813 | graph: self.graph.clone_ref(py), |
| 814 | key, |
| 815 | }) |
| 816 | } |
| 817 | |
| 818 | fn __contains__(&self, py: Python, key: Py<PyAny>) -> bool { |
| 819 | self.graph.borrow(py).inner.contains(&PyNode::from(key)) |
| 820 | } |
| 821 | |
| 822 | fn __len__(&self, py: Python) -> usize { |
| 823 | self.graph.borrow(py).inner.len() |
| 824 | } |
| 825 | |
| 826 | fn __iter__(&self, py: Python) -> PyResult<Py<PyAny>> { |
| 827 | let keys: Vec<Py<PyAny>> = self |
| 828 | .graph |
| 829 | .borrow(py) |
| 830 | .inner |
| 831 | .keys() |
| 832 | .map(|n| n.0.clone_ref(py)) |
| 833 | .collect(); |
| 834 | Ok(pyo3::types::PyList::new(py, keys)? |
| 835 | .call_method0("__iter__")? |
| 836 | .unbind()) |
| 837 | } |
| 838 | |
| 839 | fn keys(&self, py: Python) -> Vec<Py<PyAny>> { |
| 840 | self.graph |
| 841 | .borrow(py) |
| 842 | .inner |
| 843 | .keys() |
| 844 | .map(|n| n.0.clone_ref(py)) |
| 845 | .collect() |
| 846 | } |
| 847 | |
| 848 | fn values(&self, py: Python) -> Vec<PyKnownGraphNode> { |
| 849 | self.graph |
| 850 | .borrow(py) |
| 851 | .inner |
| 852 | .keys() |
| 853 | .map(|n| PyKnownGraphNode { |
| 854 | graph: self.graph.clone_ref(py), |
| 855 | key: n.0.clone_ref(py), |
| 856 | }) |
| 857 | .collect() |
| 858 | } |
| 859 | } |
| 860 | |
| 861 | #[pyclass(name = "_KnownGraphNode")] |
| 862 | struct PyKnownGraphNode { |
| 863 | graph: Py<PyKnownGraph>, |
| 864 | key: Py<PyAny>, |
| 865 | } |
| 866 | |
| 867 | #[pymethods] |
| 868 | impl PyKnownGraphNode { |
| 869 | #[getter] |
| 870 | fn key(&self, py: Python) -> Py<PyAny> { |
| 871 | self.key.clone_ref(py) |
| 872 | } |
| 873 | |
| 874 | #[getter] |
| 875 | fn gdfo(&self, py: Python) -> Option<u64> { |
| 876 | self.graph |
| 877 | .borrow(py) |
| 878 | .inner |
| 879 | .gdfo(&PyNode::from(self.key.clone_ref(py))) |
| 880 | } |
| 881 | |
| 882 | #[getter] |
| 883 | fn parent_keys(&self, py: Python) -> Option<Vec<Py<PyAny>>> { |
| 884 | self.graph |
| 885 | .borrow(py) |
| 886 | .inner |
| 887 | .get_parent_keys(&PyNode::from(self.key.clone_ref(py))) |
| 888 | .map(|ps| ps.iter().map(|n| n.0.clone_ref(py)).collect()) |
| 889 | } |
| 890 | |
| 891 | #[getter] |
| 892 | fn child_keys(&self, py: Python) -> Vec<Py<PyAny>> { |
| 893 | self.graph |
| 894 | .borrow(py) |
| 895 | .inner |
| 896 | .get_child_keys(&PyNode::from(self.key.clone_ref(py))) |
| 897 | .map(|cs| cs.iter().map(|n| n.0.clone_ref(py)).collect()) |
| 898 | .unwrap_or_default() |
| 899 | } |
| 900 | |
| 901 | fn __repr__(&self, py: Python) -> String { |
| 902 | format!( |
| 903 | "_KnownGraphNode({:?} gdfo:{:?} par:{:?} child:{:?})", |
| 904 | self.key |
| 905 | .bind(py) |
| 906 | .repr() |
| 907 | .map(|r| r.to_string()) |
| 908 | .unwrap_or_default(), |
| 909 | self.gdfo(py), |
| 910 | self.parent_keys(py), |
| 911 | self.child_keys(py), |
| 912 | ) |
| 913 | } |
| 914 | } |
| 915 | |
| 916 | #[pyclass(name = "_MergeSortNode")] |
| 917 | struct PyKnownGraphMergeSortNode { |
| 918 | #[pyo3(get, set)] |
| 919 | key: Py<PyAny>, |
| 920 | #[pyo3(get, set)] |
| 921 | merge_depth: usize, |
| 922 | #[pyo3(get, set)] |
| 923 | revno: Py<PyAny>, |
| 924 | #[pyo3(get, set)] |
| 925 | end_of_merge: bool, |
| 926 | } |
| 927 | |
| 928 | /// Sort a collection of PyNodes by hash for use as a deterministic cache |
| 929 | /// key. Collisions only hurt cache hit rate, not correctness, because two |
| 930 | /// different sets can't produce identical sorted Vecs within a process. |
| 931 | fn sort_pynodes_by_hash(items: impl IntoIterator<Item = PyNode>) -> Vec<PyNode> { |
| 932 | use std::collections::hash_map::DefaultHasher; |
| 933 | use std::hash::{Hash, Hasher}; |
| 934 | let mut v: Vec<PyNode> = items.into_iter().collect(); |
| 935 | v.sort_by_key(|n| { |
| 936 | let mut h = DefaultHasher::new(); |
| 937 | n.hash(&mut h); |
| 938 | h.finish() |
| 939 | }); |
| 940 | v |
| 941 | } |
| 942 | |
| 943 | /// Lazy iterator yielding the lefthand ancestry of a starting key. |
| 944 | /// |
| 945 | /// Mirrors the Python `Graph.iter_lefthand_ancestry` generator semantics: |
| 946 | /// each `__next__` call walks one step down the left-most parent chain. |
| 947 | /// Callers can break out of the iteration before the walk reaches a ghost |
| 948 | /// sentinel, matching Python's early-exit behaviour. |
| 949 | #[pyclass(name = "_LefthandAncestryIterator")] |
| 950 | struct PyLefthandAncestryIterator { |
| 951 | provider: Py<PyAny>, |
| 952 | next_key: Option<Py<PyAny>>, |
| 953 | stop_keys: Py<PyAny>, |
| 954 | graph_py: Py<PyAny>, |
| 955 | } |
| 956 | |
| 957 | #[pymethods] |
| 958 | impl PyLefthandAncestryIterator { |
| 959 | fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> { |
| 960 | slf |
| 961 | } |
| 962 | |
| 963 | fn __next__(&mut self, py: Python) -> PyResult<Py<PyAny>> { |
| 964 | let key = match self.next_key.take() { |
| 965 | Some(k) => k, |
| 966 | None => return Err(pyo3::exceptions::PyStopIteration::new_err(())), |
| 967 | }; |
| 968 | // Honour stop_keys (a Python container supporting `in`). |
| 969 | if self.stop_keys.bind(py).contains(&key)? { |
| 970 | return Err(pyo3::exceptions::PyStopIteration::new_err(())); |
| 971 | } |
| 972 | // Fetch the left-most parent for the next iteration. Python's |
| 973 | // generator raises RevisionNotPresent if the key is missing from |
| 974 | // the provider; mirror that exactly. |
| 975 | let key_list = pyo3::types::PyList::new(py, [key.clone_ref(py)])?; |
| 976 | let parent_map = self |
| 977 | .provider |
| 978 | .bind(py) |
| 979 | .call_method1("get_parent_map", (key_list,))?; |
| 980 | let parents = parent_map.get_item(key.clone_ref(py)); |
| 981 | match parents { |
| 982 | Ok(ps) => { |
| 983 | let ps_iter: Vec<Py<PyAny>> = { |
| 984 | let mut out = Vec::new(); |
| 985 | for item in ps.try_iter()? { |
| 986 | out.push(item?.unbind()); |
| 987 | } |
| 988 | out |
| 989 | }; |
| 990 | if ps_iter.is_empty() { |
| 991 | self.next_key = None; |
| 992 | } else { |
| 993 | self.next_key = Some(ps_iter.into_iter().next().unwrap()); |
| 994 | } |
| 995 | Ok(key) |
| 996 | } |
| 997 | Err(_) => Err(RevisionNotPresent::new_err(( |
| 998 | key, |
| 999 | self.graph_py.clone_ref(py), |
| 1000 | ))), |
| 1001 | } |
| 1002 | } |
| 1003 | } |
| 1004 | |
| 1005 | /// Adapter that wraps a graph whose keys are 1-tuples of ids. Each method |
| 1006 | /// takes ids, wraps them in tuples, delegates to the underlying graph, |
| 1007 | /// then unwraps the tuples in the response. Mirrors |
| 1008 | /// `vcsgraph.graph.GraphThunkIdsToKeys`. |
| 1009 | #[pyclass(name = "GraphThunkIdsToKeys")] |
| 1010 | struct PyGraphThunkIdsToKeys { |
| 1011 | graph: Py<PyAny>, |
| 1012 | } |
| 1013 | |
| 1014 | #[pymethods] |
| 1015 | impl PyGraphThunkIdsToKeys { |
| 1016 | #[new] |
| 1017 | fn new(graph: Py<PyAny>) -> Self { |
| 1018 | PyGraphThunkIdsToKeys { graph } |
| 1019 | } |
| 1020 | |
| 1021 | fn topo_sort(&self, py: Python) -> PyResult<Vec<Py<PyAny>>> { |
| 1022 | let result = self.graph.bind(py).call_method0("topo_sort")?; |
| 1023 | let mut out = Vec::new(); |
| 1024 | for item in result.try_iter()? { |
| 1025 | let tup = item?; |
| 1026 | out.push(tup.get_item(0)?.unbind()); |
| 1027 | } |
| 1028 | Ok(out) |
| 1029 | } |
| 1030 | |
| 1031 | fn heads<'py>( |
| 1032 | &self, |
| 1033 | py: Python<'py>, |
| 1034 | ids: Py<PyAny>, |
| 1035 | ) -> PyResult<Bound<'py, pyo3::types::PySet>> { |
| 1036 | let mut as_keys: Vec<Py<PyAny>> = Vec::new(); |
| 1037 | for item in ids.bind(py).try_iter()? { |
| 1038 | let item = item?; |
| 1039 | let tup = pyo3::types::PyTuple::new(py, [item.unbind()])?; |
| 1040 | as_keys.push(tup.into_any().unbind()); |
| 1041 | } |
| 1042 | let head_keys = self |
| 1043 | .graph |
| 1044 | .bind(py) |
| 1045 | .call_method1("heads", (pyo3::types::PyList::new(py, as_keys)?,))?; |
| 1046 | let mut out_items: Vec<Py<PyAny>> = Vec::new(); |
| 1047 | for h in head_keys.try_iter()? { |
| 1048 | let h = h?; |
| 1049 | out_items.push(h.get_item(0)?.unbind()); |
| 1050 | } |
| 1051 | pyo3::types::PySet::new(py, out_items) |
| 1052 | } |
| 1053 | |
| 1054 | fn merge_sort(&self, py: Python, tip_revision: Py<PyAny>) -> PyResult<Py<PyAny>> { |
| 1055 | let tip_tuple = pyo3::types::PyTuple::new(py, [tip_revision])?; |
| 1056 | let nodes = self |
| 1057 | .graph |
| 1058 | .bind(py) |
| 1059 | .call_method1("merge_sort", (tip_tuple,))?; |
| 1060 | for item in nodes.try_iter()? { |
| 1061 | let item = item?; |
| 1062 | let key = item.getattr("key")?; |
| 1063 | let unwrapped = key.get_item(0)?; |
| 1064 | item.setattr("key", unwrapped)?; |
| 1065 | } |
| 1066 | Ok(nodes.unbind()) |
| 1067 | } |
| 1068 | |
| 1069 | fn add_node(&self, py: Python, revision: Py<PyAny>, parents: Py<PyAny>) -> PyResult<()> { |
| 1070 | let rev_tuple = pyo3::types::PyTuple::new(py, [revision])?; |
| 1071 | let mut parent_tuples: Vec<Py<PyAny>> = Vec::new(); |
| 1072 | for p in parents.bind(py).try_iter()? { |
| 1073 | let p = p?; |
| 1074 | let tup = pyo3::types::PyTuple::new(py, [p.unbind()])?; |
| 1075 | parent_tuples.push(tup.into_any().unbind()); |
| 1076 | } |
| 1077 | self.graph.bind(py).call_method1( |
| 1078 | "add_node", |
| 1079 | (rev_tuple, pyo3::types::PyList::new(py, parent_tuples)?), |
| 1080 | )?; |
| 1081 | Ok(()) |
| 1082 | } |
| 1083 | } |
| 1084 | |
| 1085 | /// A cache of results for graph heads() calls. |
| 1086 | /// |
| 1087 | /// The cache key is the unordered set of input keys; the value is the |
| 1088 | /// `.heads()` result for that set. Every call returns a fresh mutable set |
| 1089 | /// so callers can modify the result without affecting later lookups — |
| 1090 | /// matches `vcsgraph.graph.HeadsCache`. |
| 1091 | #[pyclass(name = "HeadsCache")] |
| 1092 | struct PyHeadsCache { |
| 1093 | graph: Py<PyAny>, |
| 1094 | cache: std::sync::Mutex<std::collections::HashMap<Vec<PyNode>, Vec<PyNode>>>, |
| 1095 | } |
| 1096 | |
| 1097 | #[pymethods] |
| 1098 | impl PyHeadsCache { |
| 1099 | #[new] |
| 1100 | fn new(graph: Py<PyAny>) -> Self { |
| 1101 | PyHeadsCache { |
| 1102 | graph, |
| 1103 | cache: std::sync::Mutex::new(std::collections::HashMap::new()), |
| 1104 | } |
| 1105 | } |
| 1106 | |
| 1107 | /// The underlying graph. Exposed so Python callers can reach |
| 1108 | /// `cache.graph` just like the pure-Python version allowed. |
| 1109 | #[getter] |
| 1110 | fn graph(&self, py: Python) -> Py<PyAny> { |
| 1111 | self.graph.clone_ref(py) |
| 1112 | } |
| 1113 | |
| 1114 | /// Return the heads of `keys`. The result is a mutable Python set; |
| 1115 | /// callers may modify it without affecting future lookups. |
| 1116 | fn heads<'py>( |
| 1117 | &self, |
| 1118 | py: Python<'py>, |
| 1119 | keys: Py<PyAny>, |
| 1120 | ) -> PyResult<Bound<'py, pyo3::types::PySet>> { |
| 1121 | let nodes = extract_iter_pynodes(py, &keys)?; |
| 1122 | let key = sort_pynodes_by_hash(nodes); |
| 1123 | { |
| 1124 | let cache = self.cache.lock().unwrap(); |
| 1125 | if let Some(cached) = cache.get(&key) { |
| 1126 | return pyo3::types::PySet::new(py, cached.iter().map(|n| n.0.clone_ref(py))); |
| 1127 | } |
| 1128 | } |
| 1129 | // Cache miss: delegate to the wrapped graph. |
| 1130 | let result: Vec<PyNode> = { |
| 1131 | let heads = self.graph.bind(py).call_method1( |
| 1132 | "heads", |
| 1133 | (pyo3::types::PyList::new( |
| 1134 | py, |
| 1135 | key.iter().map(|n| n.0.clone_ref(py)), |
| 1136 | )?,), |
| 1137 | )?; |
| 1138 | let mut out = Vec::new(); |
| 1139 | for item in heads.try_iter()? { |
| 1140 | out.push(PyNode::from(item?)); |
| 1141 | } |
| 1142 | out |
| 1143 | }; |
| 1144 | let mut cache = self.cache.lock().unwrap(); |
| 1145 | cache.insert(key, result.clone()); |
| 1146 | pyo3::types::PySet::new(py, result.into_iter().map(|n| n.0)) |
| 1147 | } |
| 1148 | } |
| 1149 | |
| 1150 | /// A cache of `heads()` results that returns frozen sets. |
| 1151 | /// |
| 1152 | /// Same as [`PyHeadsCache`] but the results are immutable. Matches |
| 1153 | /// `vcsgraph.graph.FrozenHeadsCache`. |
| 1154 | #[pyclass(name = "FrozenHeadsCache")] |
| 1155 | struct PyFrozenHeadsCache { |
| 1156 | graph: Py<PyAny>, |
| 1157 | cache: std::sync::Mutex<std::collections::HashMap<Vec<PyNode>, Vec<PyNode>>>, |
| 1158 | } |
| 1159 | |
| 1160 | #[pymethods] |
| 1161 | impl PyFrozenHeadsCache { |
| 1162 | #[new] |
| 1163 | fn new(graph: Py<PyAny>) -> Self { |
| 1164 | PyFrozenHeadsCache { |
| 1165 | graph, |
| 1166 | cache: std::sync::Mutex::new(std::collections::HashMap::new()), |
| 1167 | } |
| 1168 | } |
| 1169 | |
| 1170 | #[getter] |
| 1171 | fn graph(&self, py: Python) -> Py<PyAny> { |
| 1172 | self.graph.clone_ref(py) |
| 1173 | } |
| 1174 | |
| 1175 | /// Return the heads of `keys` as a frozenset. |
| 1176 | fn heads(&self, py: Python, keys: Py<PyAny>) -> PyResult<Py<PyAny>> { |
| 1177 | let nodes = extract_iter_pynodes(py, &keys)?; |
| 1178 | let key = sort_pynodes_by_hash(nodes); |
| 1179 | { |
| 1180 | let cache = self.cache.lock().unwrap(); |
| 1181 | if let Some(cached) = cache.get(&key) { |
| 1182 | let fs = py.import("builtins")?.getattr("frozenset")?; |
| 1183 | let items: Vec<Py<PyAny>> = cached.iter().map(|n| n.0.clone_ref(py)).collect(); |
| 1184 | return Ok(fs.call1((items,))?.into_any().unbind()); |
| 1185 | } |
| 1186 | } |
| 1187 | let result: Vec<PyNode> = { |
| 1188 | let heads = self.graph.bind(py).call_method1( |
| 1189 | "heads", |
| 1190 | (pyo3::types::PyList::new( |
| 1191 | py, |
| 1192 | key.iter().map(|n| n.0.clone_ref(py)), |
| 1193 | )?,), |
| 1194 | )?; |
| 1195 | let mut out = Vec::new(); |
| 1196 | for item in heads.try_iter()? { |
| 1197 | out.push(PyNode::from(item?)); |
| 1198 | } |
| 1199 | out |
| 1200 | }; |
| 1201 | let mut cache = self.cache.lock().unwrap(); |
| 1202 | cache.insert(key, result.clone()); |
| 1203 | let fs = py.import("builtins")?.getattr("frozenset")?; |
| 1204 | let items: Vec<Py<PyAny>> = result.into_iter().map(|n| n.0).collect(); |
| 1205 | Ok(fs.call1((items,))?.into_any().unbind()) |
| 1206 | } |
| 1207 | |
| 1208 | /// Store a precomputed `(keys, heads)` pair directly in the cache. |
| 1209 | fn cache(&self, py: Python, keys: Py<PyAny>, heads: Py<PyAny>) -> PyResult<()> { |
| 1210 | let key_nodes = extract_iter_pynodes(py, &keys)?; |
| 1211 | let head_nodes = extract_iter_pynodes(py, &heads)?; |
| 1212 | let key = sort_pynodes_by_hash(key_nodes); |
| 1213 | self.cache.lock().unwrap().insert(key, head_nodes); |
| 1214 | Ok(()) |
| 1215 | } |
| 1216 | } |
| 1217 | |
| 1218 | /// Python binding for [`CachingParentsProvider`]. Wraps an inner Python |
| 1219 | /// parents provider (any object with a `get_parent_map(keys)` method) and |
| 1220 | /// caches every lookup so repeated queries don't re-hit the inner provider. |
| 1221 | /// |
| 1222 | /// Mirrors `vcsgraph.graph.CachingParentsProvider`. |
| 1223 | #[pyclass(name = "CachingParentsProvider")] |
| 1224 | struct PyCachingParentsProvider { |
| 1225 | inner: RsCachingParentsProvider<PyNode, PyParentsProviderAdapter>, |
| 1226 | real_provider_py: Py<PyAny>, |
| 1227 | /// Live Python set exposed as `.missing_keys`. Callers in breezy mutate |
| 1228 | /// it directly (e.g. `provider.missing_keys.clear()`), so it must be the |
| 1229 | /// same object across reads. We sync this with the Rust state around |
| 1230 | /// every `get_parent_map` call. |
| 1231 | missing_keys_py: Py<pyo3::types::PySet>, |
| 1232 | } |
| 1233 | |
| 1234 | impl PyCachingParentsProvider { |
| 1235 | /// Push Python set contents into Rust state. |
| 1236 | fn sync_missing_to_rust(&self, py: Python<'_>) -> PyResult<()> { |
| 1237 | let set = self.missing_keys_py.bind(py); |
| 1238 | let mut keys: HashSet<PyNode> = HashSet::new(); |
| 1239 | for item in set.try_iter()? { |
| 1240 | keys.insert(PyNode::from(item?)); |
| 1241 | } |
| 1242 | self.inner.set_missing_keys(keys); |
| 1243 | Ok(()) |
| 1244 | } |
| 1245 | |
| 1246 | /// Pull Rust state into the Python set. |
| 1247 | fn sync_missing_to_py(&self, py: Python<'_>) -> PyResult<()> { |
| 1248 | let set = self.missing_keys_py.bind(py); |
| 1249 | set.clear(); |
| 1250 | for k in self.inner.missing_keys() { |
| 1251 | set.add(k.0)?; |
| 1252 | } |
| 1253 | Ok(()) |
| 1254 | } |
| 1255 | } |
| 1256 | |
| 1257 | #[pymethods] |
| 1258 | impl PyCachingParentsProvider { |
| 1259 | /// Construct a caching wrapper around `parent_provider`, which must be |
| 1260 | /// either a Python object with a `get_parent_map` method or `None` when |
| 1261 | /// `get_parent_map` is supplied as a callable. |
| 1262 | #[new] |
| 1263 | #[pyo3(signature = (parent_provider=None, get_parent_map=None))] |
| 1264 | fn new( |
| 1265 | py: Python, |
| 1266 | parent_provider: Option<Py<PyAny>>, |
| 1267 | get_parent_map: Option<Py<PyAny>>, |
| 1268 | ) -> PyResult<Self> { |
| 1269 | let provider_obj = match (parent_provider, get_parent_map) { |
| 1270 | (Some(p), None) => p, |
| 1271 | (None, Some(cb)) => { |
| 1272 | // Wrap the callable into a tiny Python shim that exposes |
| 1273 | // a `get_parent_map` attribute, so the adapter can call it |
| 1274 | // uniformly. |
| 1275 | let builtins = py.import("builtins")?; |
| 1276 | let type_ = builtins.getattr("type")?; |
| 1277 | let ns = pyo3::types::PyDict::new(py); |
| 1278 | ns.set_item("get_parent_map", cb)?; |
| 1279 | let shim = type_.call1(("_CPPShim", (builtins.getattr("object")?,), ns))?; |
| 1280 | shim.call0()?.into_any().unbind() |
| 1281 | } |
| 1282 | (Some(_), Some(_)) => { |
| 1283 | return Err(pyo3::exceptions::PyValueError::new_err( |
| 1284 | "Pass parent_provider OR get_parent_map, not both", |
| 1285 | )) |
| 1286 | } |
| 1287 | (None, None) => { |
| 1288 | return Err(pyo3::exceptions::PyValueError::new_err( |
| 1289 | "Either parent_provider or get_parent_map must be supplied", |
| 1290 | )) |
| 1291 | } |
| 1292 | }; |
| 1293 | let adapter = PyParentsProviderAdapter::new(provider_obj.clone_ref(py)); |
| 1294 | let missing_keys_py = pyo3::types::PySet::empty(py)?.unbind(); |
| 1295 | Ok(PyCachingParentsProvider { |
| 1296 | inner: RsCachingParentsProvider::new(adapter), |
| 1297 | real_provider_py: provider_obj, |
| 1298 | missing_keys_py, |
| 1299 | }) |
| 1300 | } |
| 1301 | |
| 1302 | fn __repr__(&self, py: Python) -> PyResult<String> { |
| 1303 | let r = self.real_provider_py.bind(py).repr()?; |
| 1304 | Ok(format!("CachingParentsProvider({})", r)) |
| 1305 | } |
| 1306 | |
| 1307 | #[pyo3(signature = (cache_misses=true))] |
| 1308 | fn enable_cache(&self, py: Python<'_>, cache_misses: bool) -> PyResult<()> { |
| 1309 | self.inner |
| 1310 | .enable_cache(cache_misses) |
| 1311 | .map_err(pyo3::exceptions::PyAssertionError::new_err)?; |
| 1312 | self.missing_keys_py.bind(py).clear(); |
| 1313 | Ok(()) |
| 1314 | } |
| 1315 | |
| 1316 | fn disable_cache(&self, py: Python<'_>) { |
| 1317 | self.inner.disable_cache(); |
| 1318 | self.missing_keys_py.bind(py).clear(); |
| 1319 | } |
| 1320 | |
| 1321 | /// Return a snapshot of the cache as a Python dict, or `None` if |
| 1322 | /// disabled. |
| 1323 | fn get_cached_map<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyDict>>> { |
| 1324 | match self.inner.get_cached_map() { |
| 1325 | None => Ok(None), |
| 1326 | Some(map) => Ok(Some(cache_map_to_pydict(py, map)?)), |
| 1327 | } |
| 1328 | } |
| 1329 | |
| 1330 | /// Backward-compatible access to the raw `_cache` attribute. Returns a |
| 1331 | /// dict snapshot when the cache is enabled, `None` otherwise. The |
| 1332 | /// Python tests read this directly, so mirror Python's behaviour of |
| 1333 | /// exposing an empty dict rather than `None` for a freshly-enabled |
| 1334 | /// cache. |
| 1335 | #[getter] |
| 1336 | fn _cache<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyDict>>> { |
| 1337 | self.get_cached_map(py) |
| 1338 | } |
| 1339 | |
| 1340 | fn get_cached_parent_map<'py>( |
| 1341 | &self, |
| 1342 | py: Python<'py>, |
| 1343 | keys: Py<PyAny>, |
| 1344 | ) -> PyResult<Bound<'py, PyDict>> { |
| 1345 | let nodes = extract_iter_pynodes(py, &keys)?; |
| 1346 | let hs: HashSet<PyNode> = nodes.into_iter().collect(); |
| 1347 | let pm = self.inner.get_cached_parent_map(&hs); |
| 1348 | parent_map_to_pydict(py, pm) |
| 1349 | } |
| 1350 | |
| 1351 | fn get_parent_map<'py>( |
| 1352 | &self, |
| 1353 | py: Python<'py>, |
| 1354 | keys: Py<PyAny>, |
| 1355 | ) -> PyResult<Bound<'py, PyDict>> { |
| 1356 | let nodes = extract_iter_pynodes(py, &keys)?; |
| 1357 | let hs: HashSet<PyNode> = nodes.into_iter().collect(); |
| 1358 | self.sync_missing_to_rust(py)?; |
| 1359 | let pm = self.inner.get_parent_map(&hs); |
| 1360 | if let Some(err) = self.inner.inner().take_error() { |
| 1361 | self.sync_missing_to_py(py)?; |
| 1362 | return Err(err); |
| 1363 | } |
| 1364 | self.sync_missing_to_py(py)?; |
| 1365 | parent_map_to_pydict(py, pm) |
| 1366 | } |
| 1367 | |
| 1368 | fn note_missing_key(&self, py: Python<'_>, key: Py<PyAny>) -> PyResult<()> { |
| 1369 | let node = PyNode::from(key); |
| 1370 | self.inner.note_missing_key(node.clone()); |
| 1371 | // Mirror to the exposed Python set so callers see the new entry. |
| 1372 | if self.inner.missing_keys().contains(&node) { |
| 1373 | self.missing_keys_py.bind(py).add(node.0.clone_ref(py))?; |
| 1374 | } |
| 1375 | Ok(()) |
| 1376 | } |
| 1377 | |
| 1378 | #[getter] |
| 1379 | fn missing_keys<'py>(&self, py: Python<'py>) -> Bound<'py, pyo3::types::PySet> { |
| 1380 | self.missing_keys_py.bind(py).clone() |
| 1381 | } |
| 1382 | } |
| 1383 | |
| 1384 | /// Adapter letting a Python parents provider satisfy Rust's `ParentsProvider` |
| 1385 | /// trait. Holds a raw `Py<PyAny>` and dispatches `get_parent_map(keys)` via |
| 1386 | /// the GIL. |
| 1387 | /// |
| 1388 | /// The Python provider's `get_parent_map` must accept an iterable of keys |
| 1389 | /// and return a dict-like `{key: parents_tuple}` (missing keys are treated |
| 1390 | /// as ghosts). If the Python call raises, the error is captured in |
| 1391 | /// `last_error` and an empty map is returned; callers should drain |
| 1392 | /// `last_error` after a Rust-level operation completes and surface the error |
| 1393 | /// back to Python. |
| 1394 | struct PyParentsProviderAdapter { |
| 1395 | provider: Py<PyAny>, |
| 1396 | last_error: std::sync::Mutex<Option<PyErr>>, |
| 1397 | } |
| 1398 | |
| 1399 | impl PyParentsProviderAdapter { |
| 1400 | fn new(provider: Py<PyAny>) -> Self { |
| 1401 | Self { |
| 1402 | provider, |
| 1403 | last_error: std::sync::Mutex::new(None), |
| 1404 | } |
| 1405 | } |
| 1406 | |
| 1407 | fn take_error(&self) -> Option<PyErr> { |
| 1408 | self.last_error.lock().unwrap().take() |
| 1409 | } |
| 1410 | |
| 1411 | fn set_error(&self, err: PyErr) { |
| 1412 | let mut slot = self.last_error.lock().unwrap(); |
| 1413 | if slot.is_none() { |
| 1414 | *slot = Some(err); |
| 1415 | } |
| 1416 | } |
| 1417 | |
| 1418 | fn has_error(&self) -> bool { |
| 1419 | self.last_error.lock().unwrap().is_some() |
| 1420 | } |
| 1421 | } |
| 1422 | |
| 1423 | impl ParentsProvider<PyNode> for PyParentsProviderAdapter { |
| 1424 | fn get_parent_map(&self, keys: &HashSet<PyNode>) -> ParentMap<PyNode> { |
| 1425 | if self.has_error() { |
| 1426 | return ParentMap::new(); |
| 1427 | } |
| 1428 | Python::attach(|py| { |
| 1429 | let key_list = pyo3::types::PyList::empty(py); |
| 1430 | for k in keys { |
| 1431 | if let Err(err) = key_list.append(k.0.bind(py)) { |
| 1432 | self.set_error(err); |
| 1433 | return ParentMap::new(); |
| 1434 | } |
| 1435 | } |
| 1436 | let result = match self |
| 1437 | .provider |
| 1438 | .bind(py) |
| 1439 | .call_method1("get_parent_map", (key_list,)) |
| 1440 | { |
| 1441 | Ok(r) => r, |
| 1442 | Err(err) => { |
| 1443 | self.set_error(err); |
| 1444 | return ParentMap::new(); |
| 1445 | } |
| 1446 | }; |
| 1447 | match result.extract::<ParentMap<PyNode>>() { |
| 1448 | Ok(pm) => pm, |
| 1449 | Err(err) => { |
| 1450 | self.set_error(err); |
| 1451 | ParentMap::new() |
| 1452 | } |
| 1453 | } |
| 1454 | }) |
| 1455 | } |
| 1456 | } |
| 1457 | |
| 1458 | #[pyclass(name = "_RustGraph")] |
| 1459 | struct PyGraph { |
| 1460 | inner: RsGraph<PyNode, PyParentsProviderAdapter>, |
| 1461 | provider_py: Py<PyAny>, |
| 1462 | } |
| 1463 | |
| 1464 | impl PyGraph { |
| 1465 | fn check_error(&self) -> PyResult<()> { |
| 1466 | if let Some(err) = self.inner.parents_provider().take_error() { |
| 1467 | return Err(err); |
| 1468 | } |
| 1469 | Ok(()) |
| 1470 | } |
| 1471 | } |
| 1472 | |
| 1473 | fn extract_iter_pynodes(py: Python, obj: &Py<PyAny>) -> PyResult<Vec<PyNode>> { |
| 1474 | let mut out = Vec::new(); |
| 1475 | for item in obj.bind(py).try_iter()? { |
| 1476 | out.push(PyNode::from(item?)); |
| 1477 | } |
| 1478 | Ok(out) |
| 1479 | } |
| 1480 | |
| 1481 | fn parent_map_to_pydict<'py>( |
| 1482 | py: Python<'py>, |
| 1483 | pm: ParentMap<PyNode>, |
| 1484 | ) -> PyResult<Bound<'py, PyDict>> { |
| 1485 | let d = PyDict::new(py); |
| 1486 | for (k, v) in pm { |
| 1487 | d.set_item(k.0, v.into_pyobject(py)?)?; |
| 1488 | } |
| 1489 | Ok(d) |
| 1490 | } |
| 1491 | |
| 1492 | fn cache_map_to_pydict<'py>( |
| 1493 | py: Python<'py>, |
| 1494 | map: rustc_hash::FxHashMap<PyNode, Parents<PyNode>>, |
| 1495 | ) -> PyResult<Bound<'py, PyDict>> { |
| 1496 | let d = PyDict::new(py); |
| 1497 | for (k, v) in map { |
| 1498 | d.set_item(k.0, v.into_pyobject(py)?)?; |
| 1499 | } |
| 1500 | Ok(d) |
| 1501 | } |
| 1502 | |
| 1503 | #[pymethods] |
| 1504 | impl PyGraph { |
| 1505 | #[new] |
| 1506 | fn new(py: Python, parents_provider: Py<PyAny>) -> PyResult<Self> { |
| 1507 | let adapter = PyParentsProviderAdapter::new(parents_provider.clone_ref(py)); |
| 1508 | Ok(PyGraph { |
| 1509 | inner: RsGraph::new(adapter), |
| 1510 | provider_py: parents_provider, |
| 1511 | }) |
| 1512 | } |
| 1513 | |
| 1514 | /// Return the wrapped parents provider as given at construction time. |
| 1515 | #[getter] |
| 1516 | fn parents_provider(&self, py: Python) -> Py<PyAny> { |
| 1517 | self.provider_py.clone_ref(py) |
| 1518 | } |
| 1519 | |
| 1520 | fn get_parent_map<'py>( |
| 1521 | &self, |
| 1522 | py: Python<'py>, |
| 1523 | keys: Py<PyAny>, |
| 1524 | ) -> PyResult<Bound<'py, PyDict>> { |
| 1525 | let nodes = extract_iter_pynodes(py, &keys)?; |
| 1526 | let pm = self.inner.get_parent_map(nodes); |
| 1527 | if let Some(err) = self.inner.parents_provider().take_error() { |
| 1528 | return Err(err); |
| 1529 | } |
| 1530 | parent_map_to_pydict(py, pm) |
| 1531 | } |
| 1532 | |
| 1533 | fn get_child_map<'py>(&self, py: Python<'py>, keys: Py<PyAny>) -> PyResult<Bound<'py, PyDict>> { |
| 1534 | let nodes = extract_iter_pynodes(py, &keys)?; |
| 1535 | let cm = self.inner.get_child_map(nodes); |
| 1536 | if let Some(err) = self.inner.parents_provider().take_error() { |
| 1537 | return Err(err); |
| 1538 | } |
| 1539 | let d = PyDict::new(py); |
| 1540 | for (parent, children) in cm { |
| 1541 | let list: Vec<Py<PyAny>> = children.into_iter().map(|n| n.0).collect(); |
| 1542 | d.set_item(parent.0, list)?; |
| 1543 | } |
| 1544 | Ok(d) |
| 1545 | } |
| 1546 | |
| 1547 | fn iter_topo_order(&self, py: Python, revisions: Py<PyAny>) -> PyResult<Vec<Py<PyAny>>> { |
| 1548 | let nodes = extract_iter_pynodes(py, &revisions)?; |
| 1549 | let res = self |
| 1550 | .inner |
| 1551 | .iter_topo_order(nodes) |
| 1552 | .map(|v| v.into_iter().map(|n| n.0).collect()) |
| 1553 | .map_err(|e| match e { |
| 1554 | vcs_graph::Error::Cycle(_) => { |
| 1555 | GraphCycleError::new_err(("cycle in graph while iter_topo_order",)) |
| 1556 | } |
| 1557 | other => pyo3::exceptions::PyValueError::new_err(format!("{:?}", other)), |
| 1558 | }); |
| 1559 | self.check_error()?; |
| 1560 | res |
| 1561 | } |
| 1562 | |
| 1563 | /// Return a lazy iterator over the lefthand ancestry of `start_key`. |
| 1564 | /// |
| 1565 | /// The iterator yields revisions one at a time, walking left-most |
| 1566 | /// parents, and raises RevisionNotPresent if a key in the walk is |
| 1567 | /// missing from the provider. `stop_keys` is any container supporting |
| 1568 | /// the `in` operator; iteration stops when the current key is in it. |
| 1569 | #[pyo3(signature = (start_key, stop_keys=None))] |
| 1570 | fn iter_lefthand_ancestry( |
| 1571 | slf: PyRef<'_, Self>, |
| 1572 | py: Python, |
| 1573 | start_key: Py<PyAny>, |
| 1574 | stop_keys: Option<Py<PyAny>>, |
| 1575 | ) -> PyResult<PyLefthandAncestryIterator> { |
| 1576 | let stop_keys = match stop_keys { |
| 1577 | Some(s) => s, |
| 1578 | None => pyo3::types::PyTuple::empty(py).into_any().unbind(), |
| 1579 | }; |
| 1580 | Ok(PyLefthandAncestryIterator { |
| 1581 | provider: slf.provider_py.clone_ref(py), |
| 1582 | next_key: Some(start_key), |
| 1583 | stop_keys, |
| 1584 | graph_py: slf.into_pyobject(py)?.into_any().unbind(), |
| 1585 | }) |
| 1586 | } |
| 1587 | |
| 1588 | /// Iterate ancestry, yielding `(key, parents_tuple_or_None)` pairs. |
| 1589 | fn iter_ancestry<'py>( |
| 1590 | &self, |
| 1591 | py: Python<'py>, |
| 1592 | revision_ids: Py<PyAny>, |
| 1593 | ) -> PyResult<Vec<Bound<'py, pyo3::types::PyTuple>>> { |
| 1594 | let nodes = extract_iter_pynodes(py, &revision_ids)?; |
| 1595 | let pairs = self.inner.iter_ancestry(nodes); |
| 1596 | self.check_error()?; |
| 1597 | pairs |
| 1598 | .into_iter() |
| 1599 | .map(|(k, parents)| { |
| 1600 | let parents_obj: Py<PyAny> = match parents { |
| 1601 | Parents::Known(ps) => { |
| 1602 | let list: Vec<Py<PyAny>> = ps.into_iter().map(|n| n.0).collect(); |
| 1603 | pyo3::types::PyTuple::new(py, list)?.into_any().unbind() |
| 1604 | } |
| 1605 | Parents::Ghost => py.None(), |
| 1606 | }; |
| 1607 | pyo3::types::PyTuple::new(py, [k.0, parents_obj]) |
| 1608 | }) |
| 1609 | .collect() |
| 1610 | } |
| 1611 | |
| 1612 | fn find_distance_to_null( |
| 1613 | &self, |
| 1614 | py: Python, |
| 1615 | target_revision_id: Py<PyAny>, |
| 1616 | known_revision_ids: Py<PyAny>, |
| 1617 | ) -> PyResult<i64> { |
| 1618 | let target = PyNode::from(target_revision_id); |
| 1619 | let mut known: Vec<(PyNode, i64)> = Vec::new(); |
| 1620 | for item in known_revision_ids.bind(py).try_iter()? { |
| 1621 | let (k, d): (Py<PyAny>, i64) = item?.extract()?; |
| 1622 | known.push((PyNode::from(k), d)); |
| 1623 | } |
| 1624 | let null_bytes = pyo3::types::PyBytes::new(py, NULL_REVISION); |
| 1625 | let null = PyNode::from(null_bytes.into_any().unbind()); |
| 1626 | let res = self |
| 1627 | .inner |
| 1628 | .find_distance_to_null(target, known, null) |
| 1629 | .map_err(graph_error_to_py); |
| 1630 | self.check_error()?; |
| 1631 | res |
| 1632 | } |
| 1633 | |
| 1634 | fn find_lefthand_distances<'py>( |
| 1635 | &self, |
| 1636 | py: Python<'py>, |
| 1637 | keys: Py<PyAny>, |
| 1638 | ) -> PyResult<Bound<'py, PyDict>> { |
| 1639 | let nodes = extract_iter_pynodes(py, &keys)?; |
| 1640 | let null_bytes = pyo3::types::PyBytes::new(py, NULL_REVISION); |
| 1641 | let null = PyNode::from(null_bytes.into_any().unbind()); |
| 1642 | let result = self.inner.find_lefthand_distances(nodes, null); |
| 1643 | self.check_error()?; |
| 1644 | let d = PyDict::new(py); |
| 1645 | for (k, dist) in result { |
| 1646 | d.set_item(k.0, dist)?; |
| 1647 | } |
| 1648 | Ok(d) |
| 1649 | } |
| 1650 | |
| 1651 | /// Return the heads from amongst keys. |
| 1652 | /// |
| 1653 | /// This is done by searching the ancestries of each key. Any key that is |
| 1654 | /// reachable from another key is not returned; all the others are. |
| 1655 | /// |
| 1656 | /// This operation scales with the relative depth between any two keys. If |
| 1657 | /// any two keys are completely disconnected all ancestry of both sides |
| 1658 | /// will be retrieved. |
| 1659 | /// |
| 1660 | /// :param keys: An iterable of keys. |
| 1661 | /// :return: A set of the heads. Note that as a set there is no ordering |
| 1662 | /// information. Callers will need to filter their input to create |
| 1663 | /// order if they need it. |
| 1664 | fn heads<'py>( |
| 1665 | &self, |
| 1666 | py: Python<'py>, |
| 1667 | keys: Py<PyAny>, |
| 1668 | ) -> PyResult<Bound<'py, pyo3::types::PySet>> { |
| 1669 | let nodes = extract_iter_pynodes(py, &keys)?; |
| 1670 | let null_bytes = pyo3::types::PyBytes::new(py, NULL_REVISION); |
| 1671 | let null = PyNode::from(null_bytes.into_any().unbind()); |
| 1672 | let result = self.inner.heads_with_null(nodes, &null); |
| 1673 | self.check_error()?; |
| 1674 | pynodes_to_pyset(py, result) |
| 1675 | } |
| 1676 | |
| 1677 | /// Determine the lowest common ancestors of the provided revisions. |
| 1678 | /// |
| 1679 | /// A lowest common ancestor is a common ancestor none of whose |
| 1680 | /// descendants are common ancestors. In graphs, unlike trees, there may |
| 1681 | /// be multiple lowest common ancestors. |
| 1682 | /// |
| 1683 | /// This algorithm has two phases. Phase 1 identifies border ancestors, |
| 1684 | /// and phase 2 filters border ancestors to determine lowest common |
| 1685 | /// ancestors. |
| 1686 | /// |
| 1687 | /// In phase 1, border ancestors are identified, using a breadth-first |
| 1688 | /// search starting at the bottom of the graph. Searches are stopped |
| 1689 | /// whenever a node or one of its descendants is determined to be common |
| 1690 | /// |
| 1691 | /// In phase 2, the border ancestors are filtered to find the least |
| 1692 | /// common ancestors. This is done by searching the ancestries of each |
| 1693 | /// border ancestor. |
| 1694 | /// |
| 1695 | /// Phase 2 is perfomed on the principle that a border ancestor that is |
| 1696 | /// not an ancestor of any other border ancestor is a least common |
| 1697 | /// ancestor. |
| 1698 | /// |
| 1699 | /// Searches are stopped when they find a node that is determined to be a |
| 1700 | /// common ancestor of all border ancestors, because this shows that it |
| 1701 | /// cannot be a descendant of any border ancestor. |
| 1702 | /// |
| 1703 | /// The scaling of this operation should be proportional to: |
| 1704 | /// |
| 1705 | /// 1. The number of uncommon ancestors |
| 1706 | /// 2. The number of border ancestors |
| 1707 | /// 3. The length of the shortest path between a border ancestor and an |
| 1708 | /// ancestor of all border ancestors. |
| 1709 | fn find_lca<'py>( |
| 1710 | &self, |
| 1711 | py: Python<'py>, |
| 1712 | revisions: Py<PyAny>, |
| 1713 | ) -> PyResult<Bound<'py, pyo3::types::PySet>> { |
| 1714 | let nodes = extract_iter_pynodes(py, &revisions)?; |
| 1715 | // Match Python's `_find_border_ancestors` precondition: None is |
| 1716 | // not a valid revision id. Raise InvalidRevisionId before running |
| 1717 | // the algorithm so callers see the same error they used to. |
| 1718 | for n in &nodes { |
| 1719 | if n.0.is_none(py) { |
| 1720 | return Err(InvalidRevisionId::new_err(( |
| 1721 | py.None(), |
| 1722 | self.provider_py.clone_ref(py), |
| 1723 | ))); |
| 1724 | } |
| 1725 | } |
| 1726 | let null_bytes = pyo3::types::PyBytes::new(py, NULL_REVISION); |
| 1727 | let null = PyNode::from(null_bytes.into_any().unbind()); |
| 1728 | let result = self.inner.find_lca(nodes, &null); |
| 1729 | self.check_error()?; |
| 1730 | pynodes_to_pyset(py, result) |
| 1731 | } |
| 1732 | |
| 1733 | /// Determine whether a revision is an ancestor of another. |
| 1734 | /// |
| 1735 | /// We answer this using heads() as heads() has the logic to perform the |
| 1736 | /// smallest number of parent lookups to determine the ancestral |
| 1737 | /// relationship between N revisions. |
| 1738 | fn is_ancestor( |
| 1739 | &self, |
| 1740 | py: Python, |
| 1741 | candidate_ancestor: Py<PyAny>, |
| 1742 | candidate_descendant: Py<PyAny>, |
| 1743 | ) -> PyResult<bool> { |
| 1744 | let null_bytes = pyo3::types::PyBytes::new(py, NULL_REVISION); |
| 1745 | let null = PyNode::from(null_bytes.into_any().unbind()); |
| 1746 | let res = self.inner.is_ancestor( |
| 1747 | PyNode::from(candidate_ancestor), |
| 1748 | PyNode::from(candidate_descendant), |
| 1749 | &null, |
| 1750 | ); |
| 1751 | self.check_error()?; |
| 1752 | Ok(res) |
| 1753 | } |
| 1754 | |
| 1755 | /// Determine whether a revision is between two others. |
| 1756 | /// |
| 1757 | /// returns true if and only if: |
| 1758 | /// lower_bound_revid <= revid <= upper_bound_revid |
| 1759 | #[pyo3(signature = (revid, lower_bound_revid, upper_bound_revid))] |
| 1760 | fn is_between( |
| 1761 | &self, |
| 1762 | py: Python, |
| 1763 | revid: Py<PyAny>, |
| 1764 | lower_bound_revid: Option<Py<PyAny>>, |
| 1765 | upper_bound_revid: Option<Py<PyAny>>, |
| 1766 | ) -> PyResult<bool> { |
| 1767 | let null_bytes = pyo3::types::PyBytes::new(py, NULL_REVISION); |
| 1768 | let null = PyNode::from(null_bytes.into_any().unbind()); |
| 1769 | let res = self.inner.is_between( |
| 1770 | PyNode::from(revid), |
| 1771 | lower_bound_revid.map(PyNode::from), |
| 1772 | upper_bound_revid.map(PyNode::from), |
| 1773 | &null, |
| 1774 | ); |
| 1775 | self.check_error()?; |
| 1776 | Ok(res) |
| 1777 | } |
| 1778 | |
| 1779 | /// Find the order that each revision was merged into tip. |
| 1780 | /// |
| 1781 | /// This basically just walks backwards with a stack, and walks left-first |
| 1782 | /// until it finds a node to stop. |
| 1783 | fn find_merge_order( |
| 1784 | &self, |
| 1785 | py: Python, |
| 1786 | tip_revision_id: Py<PyAny>, |
| 1787 | lca_revision_ids: Py<PyAny>, |
| 1788 | ) -> PyResult<Vec<Py<PyAny>>> { |
| 1789 | let tip = PyNode::from(tip_revision_id); |
| 1790 | let lcas = extract_iter_pynodes(py, &lca_revision_ids)?; |
| 1791 | let result = self.inner.find_merge_order(tip, lcas); |
| 1792 | self.check_error()?; |
| 1793 | Ok(result.into_iter().map(|n| n.0).collect()) |
| 1794 | } |
| 1795 | |
| 1796 | /// Find the unique ancestors for a revision versus others. |
| 1797 | /// |
| 1798 | /// This returns the ancestry of unique_revision, excluding all revisions |
| 1799 | /// in the ancestry of common_revisions. If unique_revision is in the |
| 1800 | /// ancestry, then the empty set will be returned. |
| 1801 | /// |
| 1802 | /// :param unique_revision: The revision_id whose ancestry we are |
| 1803 | /// interested in. |
| 1804 | /// (XXX: Would this API be better if we allowed multiple revisions on |
| 1805 | /// to be searched here?) |
| 1806 | /// :param common_revisions: Revision_ids of ancestries to exclude. |
| 1807 | /// :return: A set of revisions in the ancestry of unique_revision |
| 1808 | /// |
| 1809 | /// Algorithm description: |
| 1810 | /// |
| 1811 | /// 1) Walk backwards from the unique node and all common nodes. |
| 1812 | /// 2) When a node is seen by both sides, stop searching it in the unique |
| 1813 | /// walker, include it in the common walker. |
| 1814 | /// 3) Stop searching when there are no nodes left for the unique walker. |
| 1815 | /// At this point, you have a maximal set of unique nodes. Some of |
| 1816 | /// them may actually be common, and you haven't reached them yet. |
| 1817 | /// 4) Start new searchers for the unique nodes, seeded with the |
| 1818 | /// information you have so far. |
| 1819 | /// 5) Continue searching, stopping the common searches when the search |
| 1820 | /// tip is an ancestor of all unique nodes. |
| 1821 | /// 6) Aggregate together unique searchers when they are searching the |
| 1822 | /// same tips. When all unique searchers are searching the same node, |
| 1823 | /// stop move it to a single 'all_unique_searcher'. |
| 1824 | /// 7) The 'all_unique_searcher' represents the very 'tip' of searching. |
| 1825 | /// Most of the time this produces very little important information. |
| 1826 | /// So don't step it as quickly as the other searchers. |
| 1827 | /// 8) Search is done when all common searchers have completed. |
| 1828 | fn find_unique_ancestors<'py>( |
| 1829 | &self, |
| 1830 | py: Python<'py>, |
| 1831 | unique_revision: Py<PyAny>, |
| 1832 | common_revisions: Py<PyAny>, |
| 1833 | ) -> PyResult<Bound<'py, pyo3::types::PySet>> { |
| 1834 | let unique = PyNode::from(unique_revision); |
| 1835 | let commons = extract_iter_pynodes(py, &common_revisions)?; |
| 1836 | let result = self.inner.find_unique_ancestors(unique, commons); |
| 1837 | self.check_error()?; |
| 1838 | pynodes_to_pyset(py, result) |
| 1839 | } |
| 1840 | |
| 1841 | /// Determine the graph difference between two revisions. |
| 1842 | fn find_difference<'py>( |
| 1843 | &self, |
| 1844 | py: Python<'py>, |
| 1845 | left_revision: Py<PyAny>, |
| 1846 | right_revision: Py<PyAny>, |
| 1847 | ) -> PyResult<( |
| 1848 | Bound<'py, pyo3::types::PySet>, |
| 1849 | Bound<'py, pyo3::types::PySet>, |
| 1850 | )> { |
| 1851 | let left = PyNode::from(left_revision); |
| 1852 | let right = PyNode::from(right_revision); |
| 1853 | let (l, r) = self.inner.find_difference(left, right); |
| 1854 | self.check_error()?; |
| 1855 | Ok((pynodes_to_pyset(py, l)?, pynodes_to_pyset(py, r)?)) |
| 1856 | } |
| 1857 | |
| 1858 | /// Find a unique LCA. |
| 1859 | /// |
| 1860 | /// Find lowest common ancestors. If there is no unique common |
| 1861 | /// ancestor, find the lowest common ancestors of those ancestors. |
| 1862 | /// |
| 1863 | /// Iteration stops when a unique lowest common ancestor is found. |
| 1864 | /// The graph origin is necessarily a unique lowest common ancestor. |
| 1865 | /// |
| 1866 | /// Note that None is not an acceptable substitute for NULL_REVISION. |
| 1867 | /// in the input for this method. |
| 1868 | /// |
| 1869 | /// :param count_steps: If True, the return value will be a tuple of |
| 1870 | /// (unique_lca, steps) where steps is the number of times that |
| 1871 | /// find_lca was run. If False, only unique_lca is returned. |
| 1872 | #[pyo3(signature = (left_revision, right_revision, count_steps=false))] |
| 1873 | fn find_unique_lca( |
| 1874 | &self, |
| 1875 | py: Python, |
| 1876 | left_revision: Py<PyAny>, |
| 1877 | right_revision: Py<PyAny>, |
| 1878 | count_steps: bool, |
| 1879 | ) -> PyResult<Py<PyAny>> { |
| 1880 | let left = PyNode::from(left_revision.clone_ref(py)); |
| 1881 | let right = PyNode::from(right_revision.clone_ref(py)); |
| 1882 | let null_bytes = pyo3::types::PyBytes::new(py, NULL_REVISION); |
| 1883 | let null = PyNode::from(null_bytes.into_any().unbind()); |
| 1884 | let res = self.inner.find_unique_lca(left, right, &null); |
| 1885 | self.check_error()?; |
| 1886 | match res { |
| 1887 | Some((key, steps)) => { |
| 1888 | if count_steps { |
| 1889 | Ok(pyo3::types::PyTuple::new( |
| 1890 | py, |
| 1891 | [key.0, steps.into_pyobject(py)?.into_any().unbind()], |
| 1892 | )? |
| 1893 | .into_any() |
| 1894 | .unbind()) |
| 1895 | } else { |
| 1896 | Ok(key.0) |
| 1897 | } |
| 1898 | } |
| 1899 | None => Err(NoCommonAncestor::new_err((left_revision, right_revision))), |
| 1900 | } |
| 1901 | } |
| 1902 | |
| 1903 | /// Find the first lefthand ancestor of tip_key that merged merged_key. |
| 1904 | /// |
| 1905 | /// We do this by first finding the descendants of merged_key, then |
| 1906 | /// walking through the lefthand ancestry of tip_key until we find a key |
| 1907 | /// that doesn't descend from merged_key. Its child is the key that |
| 1908 | /// merged merged_key. |
| 1909 | /// |
| 1910 | /// :return: The first lefthand ancestor of tip_key to merge merged_key. |
| 1911 | /// merged_key if it is a lefthand ancestor of tip_key. |
| 1912 | /// None if no ancestor of tip_key merged merged_key. |
| 1913 | fn find_lefthand_merger( |
| 1914 | &self, |
| 1915 | merged_key: Py<PyAny>, |
| 1916 | tip_key: Py<PyAny>, |
| 1917 | ) -> PyResult<Option<Py<PyAny>>> { |
| 1918 | let merged = PyNode::from(merged_key); |
| 1919 | let tip = PyNode::from(tip_key); |
| 1920 | let res = self.inner.find_lefthand_merger(merged, tip).map(|n| n.0); |
| 1921 | self.check_error()?; |
| 1922 | Ok(res) |
| 1923 | } |
| 1924 | |
| 1925 | /// Find descendants of `old_key` that are ancestors of `new_key`. |
| 1926 | fn find_descendants<'py>( |
| 1927 | &self, |
| 1928 | py: Python<'py>, |
| 1929 | old_key: Py<PyAny>, |
| 1930 | new_key: Py<PyAny>, |
| 1931 | ) -> PyResult<Bound<'py, pyo3::types::PySet>> { |
| 1932 | let old = PyNode::from(old_key); |
| 1933 | let new = PyNode::from(new_key); |
| 1934 | let result = self.inner.find_descendants(old, new); |
| 1935 | self.check_error()?; |
| 1936 | pynodes_to_pyset(py, result) |
| 1937 | } |
| 1938 | |
| 1939 | /// Remove revisions which are children of other ones in the set. |
| 1940 | /// |
| 1941 | /// This doesn't do any graph searching, it just checks the immediate |
| 1942 | /// parent_map to find if there are any children which can be removed. |
| 1943 | /// |
| 1944 | /// :param revisions: A set of revision_ids |
| 1945 | /// :param parent_map: A mapping `{key: parents}` — the value may be |
| 1946 | /// a list, tuple, or None (for ghosts). |
| 1947 | /// :return: A set of revision_ids with the children removed |
| 1948 | fn _remove_simple_descendants<'py>( |
| 1949 | &self, |
| 1950 | py: Python<'py>, |
| 1951 | revisions: Py<PyAny>, |
| 1952 | parent_map: Py<PyAny>, |
| 1953 | ) -> PyResult<Bound<'py, pyo3::types::PySet>> { |
| 1954 | let revs: std::collections::HashSet<PyNode> = { |
| 1955 | let mut s = std::collections::HashSet::new(); |
| 1956 | for item in revisions.bind(py).try_iter()? { |
| 1957 | s.insert(PyNode::from(item?)); |
| 1958 | } |
| 1959 | s |
| 1960 | }; |
| 1961 | // Walk parent_map.items() Python-side so we accept any dict-like |
| 1962 | // mapping, tuples or lists as the value. |
| 1963 | let items = parent_map.bind(py).call_method0("items")?; |
| 1964 | let mut simple = revs.clone(); |
| 1965 | for item in items.try_iter()? { |
| 1966 | let item = item?; |
| 1967 | let key: Py<PyAny> = item.get_item(0)?.unbind(); |
| 1968 | let parents = item.get_item(1)?; |
| 1969 | if parents.is_none() { |
| 1970 | continue; |
| 1971 | } |
| 1972 | for parent in parents.try_iter()? { |
| 1973 | let parent = parent?; |
| 1974 | let parent_node = PyNode::from(parent.unbind()); |
| 1975 | if revs.contains(&parent_node) { |
| 1976 | simple.remove(&PyNode::from(key.clone_ref(py))); |
| 1977 | break; |
| 1978 | } |
| 1979 | } |
| 1980 | } |
| 1981 | let items: Vec<Py<PyAny>> = simple.into_iter().map(|n| n.0).collect(); |
| 1982 | pyo3::types::PySet::new(py, items) |
| 1983 | } |
| 1984 | |
| 1985 | /// Find ancestors of `new_key` that may be descendants of `old_key`. |
| 1986 | fn _find_descendant_ancestors<'py>( |
| 1987 | &self, |
| 1988 | py: Python<'py>, |
| 1989 | old_key: Py<PyAny>, |
| 1990 | new_key: Py<PyAny>, |
| 1991 | ) -> PyResult<Bound<'py, pyo3::types::PySet>> { |
| 1992 | let old = PyNode::from(old_key); |
| 1993 | let new = PyNode::from(new_key); |
| 1994 | let result = self.inner.find_descendant_ancestors(old, new); |
| 1995 | self.check_error()?; |
| 1996 | pynodes_to_pyset(py, result) |
| 1997 | } |
| 1998 | |
| 1999 | fn __repr__(&self, py: Python) -> PyResult<String> { |
| 2000 | let r = self.provider_py.bind(py).repr()?; |
| 2001 | Ok(format!("Graph({})", r)) |
| 2002 | } |
| 2003 | } |
| 2004 | |
| 2005 | import_exception!(vcsgraph.errors, GhostRevisionsHaveNoRevno); |
| 2006 | import_exception!(vcsgraph.errors, InvalidRevisionId); |
| 2007 | import_exception!(vcsgraph.errors, NoCommonAncestor); |
| 2008 | import_exception!(vcsgraph.errors, RevisionNotPresent); |
| 2009 | |
| 2010 | fn graph_error_to_py(e: GraphError<PyNode>) -> PyErr { |
| 2011 | match e { |
| 2012 | GraphError::GhostRevision { target, ghost } => Python::attach(|py| { |
| 2013 | GhostRevisionsHaveNoRevno::new_err((target.0.clone_ref(py), ghost.0.clone_ref(py))) |
| 2014 | }), |
| 2015 | GraphError::RevisionNotPresent(key) => { |
| 2016 | Python::attach(|py| RevisionNotPresent::new_err((key.0.clone_ref(py),))) |
| 2017 | } |
| 2018 | GraphError::Cycle(_) => GraphCycleError::new_err(("cycle in graph",)), |
| 2019 | } |
| 2020 | } |
| 2021 | |
| 2022 | /// Helper: convert a set of PyNodes into a Python `set()`. |
| 2023 | fn pynodes_to_pyset<'py>( |
| 2024 | py: Python<'py>, |
| 2025 | set: rustc_hash::FxHashSet<PyNode>, |
| 2026 | ) -> PyResult<Bound<'py, pyo3::types::PySet>> { |
| 2027 | let items: Vec<Py<PyAny>> = set.into_iter().map(|n| n.0).collect(); |
| 2028 | pyo3::types::PySet::new(py, items) |
| 2029 | } |
| 2030 | |
| 2031 | /// Python binding for [`BfsState`]. Owns its own adapter over a Python |
| 2032 | /// parents provider and holds the Rust BFS state as sibling fields. |
| 2033 | /// |
| 2034 | /// `dict=true` gives the class a `__dict__`, which lets the existing Python |
| 2035 | /// callers in `graph.py` stash a `_label` attribute on the instance for |
| 2036 | /// debug logging. This can be removed once Phase 4 (heads / border |
| 2037 | /// ancestors) no longer relies on it. |
| 2038 | #[pyclass(name = "_BreadthFirstSearcher", dict)] |
| 2039 | struct PyBFSearcher { |
| 2040 | state: BfsState<PyNode>, |
| 2041 | adapter: PyParentsProviderAdapter, |
| 2042 | } |
| 2043 | |
| 2044 | #[pymethods] |
| 2045 | impl PyBFSearcher { |
| 2046 | #[new] |
| 2047 | fn new(py: Python, revisions: Py<PyAny>, parents_provider: Py<PyAny>) -> PyResult<Self> { |
| 2048 | let mut revs: Vec<PyNode> = Vec::new(); |
| 2049 | for item in revisions.bind(py).try_iter()? { |
| 2050 | revs.push(PyNode::from(item?)); |
| 2051 | } |
| 2052 | Ok(PyBFSearcher { |
| 2053 | state: BfsState::new(revs), |
| 2054 | adapter: PyParentsProviderAdapter::new(parents_provider), |
| 2055 | }) |
| 2056 | } |
| 2057 | |
| 2058 | /// `seen` attribute — matches the Python API. Returns a set snapshot. |
| 2059 | #[getter] |
| 2060 | fn seen<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, pyo3::types::PySet>> { |
| 2061 | pynodes_to_pyset(py, self.state.seen.clone()) |
| 2062 | } |
| 2063 | |
| 2064 | /// `_next_query` attribute — the current search frontier. |
| 2065 | /// |
| 2066 | /// Read-only snapshot. Existing callers in `graph.py` iterate and |
| 2067 | /// truth-test this attribute but do not mutate it. |
| 2068 | #[getter] |
| 2069 | fn _next_query<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, pyo3::types::PySet>> { |
| 2070 | pynodes_to_pyset(py, self.state.next_query().clone()) |
| 2071 | } |
| 2072 | |
| 2073 | /// `_iterations` attribute — number of advance steps performed. |
| 2074 | #[getter] |
| 2075 | fn _iterations(&self) -> usize { |
| 2076 | self.state.iterations() |
| 2077 | } |
| 2078 | |
| 2079 | /// `_current_present` attribute — revisions present in the most recent |
| 2080 | /// advance. Mirrors the Python API; empty before the first advance. |
| 2081 | #[getter] |
| 2082 | fn _current_present<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, pyo3::types::PySet>> { |
| 2083 | pynodes_to_pyset(py, self.state.current_present().clone()) |
| 2084 | } |
| 2085 | |
| 2086 | /// `_current_ghosts` attribute — ghost revisions encountered in the most |
| 2087 | /// recent advance. Mirrors the Python API; empty before the first advance. |
| 2088 | #[getter] |
| 2089 | fn _current_ghosts<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, pyo3::types::PySet>> { |
| 2090 | pynodes_to_pyset(py, self.state.current_ghosts().clone()) |
| 2091 | } |
| 2092 | |
| 2093 | /// `_current_parents` attribute — parent map of present revisions from |
| 2094 | /// the most recent advance. Mirrors the Python API; empty before the |
| 2095 | /// first advance. |
| 2096 | #[getter] |
| 2097 | fn _current_parents<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> { |
| 2098 | let d = PyDict::new(py); |
| 2099 | for (rev, parents) in self.state.current_parents() { |
| 2100 | let tup = pyo3::types::PyTuple::new(py, parents.iter().map(|n| n.0.clone_ref(py)))?; |
| 2101 | d.set_item(rev.0.clone_ref(py), tup)?; |
| 2102 | } |
| 2103 | Ok(d) |
| 2104 | } |
| 2105 | |
| 2106 | /// Python `step` returns the next query set, or `()` on StopIteration. |
| 2107 | fn step<'py>(&mut self, py: Python<'py>) -> PyResult<Py<PyAny>> { |
| 2108 | let next = self.state.next_set(&self.adapter); |
| 2109 | if let Some(err) = self.adapter.take_error() { |
| 2110 | return Err(err); |
| 2111 | } |
| 2112 | match next { |
| 2113 | Some(set) => Ok(pynodes_to_pyset(py, set)?.into_any().unbind()), |
| 2114 | None => Ok(pyo3::types::PyTuple::empty(py).into_any().unbind()), |
| 2115 | } |
| 2116 | } |
| 2117 | |
| 2118 | fn __next__<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, pyo3::types::PySet>> { |
| 2119 | let next = self.state.next_set(&self.adapter); |
| 2120 | if let Some(err) = self.adapter.take_error() { |
| 2121 | return Err(err); |
| 2122 | } |
| 2123 | match next { |
| 2124 | Some(set) => pynodes_to_pyset(py, set), |
| 2125 | None => Err(pyo3::exceptions::PyStopIteration::new_err(())), |
| 2126 | } |
| 2127 | } |
| 2128 | |
| 2129 | fn next<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, pyo3::types::PySet>> { |
| 2130 | self.__next__(py) |
| 2131 | } |
| 2132 | |
| 2133 | fn next_with_ghosts<'py>( |
| 2134 | &mut self, |
| 2135 | py: Python<'py>, |
| 2136 | ) -> PyResult<( |
| 2137 | Bound<'py, pyo3::types::PySet>, |
| 2138 | Bound<'py, pyo3::types::PySet>, |
| 2139 | )> { |
| 2140 | let next = self.state.next_with_ghosts(&self.adapter); |
| 2141 | if let Some(err) = self.adapter.take_error() { |
| 2142 | return Err(err); |
| 2143 | } |
| 2144 | match next { |
| 2145 | Some((present, ghosts)) => Ok(( |
| 2146 | pynodes_to_pyset(py, present)?, |
| 2147 | pynodes_to_pyset(py, ghosts)?, |
| 2148 | )), |
| 2149 | None => Err(pyo3::exceptions::PyStopIteration::new_err(())), |
| 2150 | } |
| 2151 | } |
| 2152 | |
| 2153 | fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> { |
| 2154 | slf |
| 2155 | } |
| 2156 | |
| 2157 | fn get_state<'py>( |
| 2158 | &mut self, |
| 2159 | py: Python<'py>, |
| 2160 | ) -> PyResult<( |
| 2161 | Bound<'py, pyo3::types::PySet>, |
| 2162 | Bound<'py, pyo3::types::PySet>, |
| 2163 | Bound<'py, pyo3::types::PySet>, |
| 2164 | )> { |
| 2165 | let (started, excludes, included) = self.state.get_state(&self.adapter); |
| 2166 | if let Some(err) = self.adapter.take_error() { |
| 2167 | return Err(err); |
| 2168 | } |
| 2169 | Ok(( |
| 2170 | pynodes_to_pyset(py, started)?, |
| 2171 | pynodes_to_pyset(py, excludes)?, |
| 2172 | pynodes_to_pyset(py, included)?, |
| 2173 | )) |
| 2174 | } |
| 2175 | |
| 2176 | fn find_seen_ancestors<'py>( |
| 2177 | &self, |
| 2178 | py: Python<'py>, |
| 2179 | revisions: Py<PyAny>, |
| 2180 | ) -> PyResult<Bound<'py, pyo3::types::PySet>> { |
| 2181 | let mut revs: Vec<PyNode> = Vec::new(); |
| 2182 | for item in revisions.bind(py).try_iter()? { |
| 2183 | revs.push(PyNode::from(item?)); |
| 2184 | } |
| 2185 | let result = self.state.find_seen_ancestors(revs, &self.adapter); |
| 2186 | if let Some(err) = self.adapter.take_error() { |
| 2187 | return Err(err); |
| 2188 | } |
| 2189 | pynodes_to_pyset(py, result) |
| 2190 | } |
| 2191 | |
| 2192 | fn stop_searching_any<'py>( |
| 2193 | &mut self, |
| 2194 | py: Python<'py>, |
| 2195 | revisions: Py<PyAny>, |
| 2196 | ) -> PyResult<Bound<'py, pyo3::types::PySet>> { |
| 2197 | let mut revs: Vec<PyNode> = Vec::new(); |
| 2198 | for item in revisions.bind(py).try_iter()? { |
| 2199 | revs.push(PyNode::from(item?)); |
| 2200 | } |
| 2201 | let stopped = self.state.stop_searching_any(revs); |
| 2202 | pynodes_to_pyset(py, stopped) |
| 2203 | } |
| 2204 | |
| 2205 | fn start_searching(&mut self, py: Python, revisions: Py<PyAny>) -> PyResult<Py<PyAny>> { |
| 2206 | let mut revs: Vec<PyNode> = Vec::new(); |
| 2207 | for item in revisions.bind(py).try_iter()? { |
| 2208 | revs.push(PyNode::from(item?)); |
| 2209 | } |
| 2210 | let res = self.state.start_searching(revs, &self.adapter); |
| 2211 | if let Some(err) = self.adapter.take_error() { |
| 2212 | return Err(err); |
| 2213 | } |
| 2214 | match res { |
| 2215 | Some((present, ghosts)) => { |
| 2216 | let pres = pynodes_to_pyset(py, present)?; |
| 2217 | let gh = pynodes_to_pyset(py, ghosts)?; |
| 2218 | Ok( |
| 2219 | pyo3::types::PyTuple::new(py, [pres.into_any(), gh.into_any()])? |
| 2220 | .into_any() |
| 2221 | .unbind(), |
| 2222 | ) |
| 2223 | } |
| 2224 | // In Next mode Python returns None (the function has no explicit |
| 2225 | // return), which matches our None here. |
| 2226 | None => Ok(py.None()), |
| 2227 | } |
| 2228 | } |
| 2229 | |
| 2230 | fn __repr__(&self, py: Python) -> PyResult<String> { |
| 2231 | let prefix = if self.state.iterations() > 0 { |
| 2232 | "searching" |
| 2233 | } else { |
| 2234 | "starting" |
| 2235 | }; |
| 2236 | let seen_repr = |
| 2237 | pyo3::types::PyList::new(py, self.state.seen.iter().map(|n| n.0.clone_ref(py)))? |
| 2238 | .repr()?; |
| 2239 | let next_repr = { |
| 2240 | let next_keys: Vec<Py<PyAny>> = self |
| 2241 | .state |
| 2242 | .started_keys |
| 2243 | .iter() |
| 2244 | .map(|n| n.0.clone_ref(py)) |
| 2245 | .collect(); |
| 2246 | pyo3::types::PyList::new(py, next_keys)?.repr()? |
| 2247 | }; |
| 2248 | Ok(format!( |
| 2249 | "_BreadthFirstSearcher(iterations={}, {}={}, seen={})", |
| 2250 | self.state.iterations(), |
| 2251 | prefix, |
| 2252 | next_repr, |
| 2253 | seen_repr |
| 2254 | )) |
| 2255 | } |
| 2256 | } |
| 2257 | |
| 2258 | #[pymodule] |
| 2259 | fn _graph_rs(_py: Python, m: &Bound<PyModule>) -> PyResult<()> { |
| 2260 | m.add_wrapped(wrap_pyfunction!(invert_parent_map))?; |
| 2261 | m.add_wrapped(wrap_pyfunction!(collapse_linear_regions))?; |
| 2262 | m.add_wrapped(wrap_pyfunction!(merge_sort))?; |
| 2263 | m.add_class::<TopoSorter>()?; |
| 2264 | m.add_class::<MergeSorter>()?; |
| 2265 | m.add_class::<PyKnownGraph>()?; |
| 2266 | m.add_class::<PyKnownGraphMergeSortNode>()?; |
| 2267 | m.add_class::<PyKnownGraphNode>()?; |
| 2268 | m.add_class::<PyKnownGraphNodesView>()?; |
| 2269 | m.add_class::<PyGraph>()?; |
| 2270 | m.add_class::<PyBFSearcher>()?; |
| 2271 | m.add_class::<PyCachingParentsProvider>()?; |
| 2272 | m.add_class::<PyHeadsCache>()?; |
| 2273 | m.add_class::<PyFrozenHeadsCache>()?; |
| 2274 | m.add_class::<PyGraphThunkIdsToKeys>()?; |
| 2275 | m.add_class::<PyLefthandAncestryIterator>()?; |
| 2276 | m.add_class::<PyDictParentsProvider>()?; |
| 2277 | m.add_class::<PyStackedParentsProvider>()?; |
| 2278 | m.add_class::<PyCallableToParentsProviderAdapter>()?; |
| 2279 | Ok(()) |
| 2280 | } |