Debian Codegraph @

rust/hg-pyo3/src/ancestors.rs

raw
1 // ancestors.rs
2 //
3 // Copyright 2024 Georges Racinet <[email protected]>
4 //
5 // This software may be used and distributed according to the terms of the
6 // GNU General Public License version 2 or any later version.
7
8 //! Bindings for the `hg::ancestors` module provided by the
9 //! `hg-core` crate. From Python, this will be seen as `pyo3_rustext.ancestor`
10 //! and can be used as replacement for the the pure `ancestor` Python module.
11 use std::collections::HashSet;
12
13 use hg::MissingAncestors as CoreMissing;
14 use pyo3::prelude::*;
15 use pyo3::types::PyTuple;
16 use pyo3_sharedref::SharedByPyObject;
17 use vcsgraph::lazy_ancestors::AncestorsIterator as VCGAncestorsIterator;
18 use vcsgraph::lazy_ancestors::LazyAncestors as VCGLazyAncestors;
19
20 use crate::exceptions::GraphError;
21 use crate::revision::rev_pyiter_collect_with_py_index;
22 use crate::revision::PyRevision;
23 use crate::revlog::PySharedIndex;
24 use crate::utils::new_submodule;
25 use crate::utils::py_rust_index_to_graph;
26 use crate::utils::py_shared_or_map_err;
27
28 #[pyclass]
29 struct AncestorsIterator {
30 inner: SharedByPyObject<VCGAncestorsIterator<PySharedIndex>>,
31 }
32
33 #[pymethods]
34 impl AncestorsIterator {
35 #[new]
36 fn new(
37 index_proxy: &Bound<'_, PyAny>,
38 initrevs: &Bound<'_, PyAny>,
39 stoprev: PyRevision,
40 inclusive: bool,
41 ) -> PyResult<Self> {
42 let py = index_proxy.py();
43 let initvec: Vec<_> =
44 rev_pyiter_collect_with_py_index(initrevs, index_proxy)?;
45 let shared_idx = py_rust_index_to_graph(index_proxy)?;
46 let res_ait = unsafe {
47 shared_idx.map(py, |idx| {
48 VCGAncestorsIterator::new(
49 idx,
50 initvec.into_iter().map(|r| r.0),
51 stoprev.0,
52 inclusive,
53 )
54 })
55 };
56 let inner =
57 py_shared_or_map_err(py, res_ait, GraphError::from_vcsgraph)?;
58 Ok(Self { inner })
59 }
60
61 fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {
62 slf
63 }
64
65 fn __next__(mut slf: PyRefMut<'_, Self>) -> PyResult<Option<PyRevision>> {
66 let py = slf.py();
67 // Safety: we don't leak the inner 'static ref out of SharedByPyObject
68 let mut inner = unsafe { slf.inner.try_borrow_mut(py) }?;
69 match inner.next() {
70 Some(Err(e)) => Err(GraphError::from_vcsgraph(e)),
71 None => Ok(None),
72 Some(Ok(r)) => Ok(Some(PyRevision(r))),
73 }
74 }
75 }
76
77 #[pyclass(sequence)]
78 struct LazyAncestors {
79 inner: SharedByPyObject<VCGLazyAncestors<PySharedIndex>>,
80 proxy_index: Py<PyAny>,
81 initrevs: Py<PyAny>,
82 stoprev: PyRevision,
83 inclusive: bool,
84 }
85
86 #[pymethods]
87 impl LazyAncestors {
88 #[new]
89 fn new(
90 py: Python<'_>,
91 index_proxy: &Bound<'_, PyAny>,
92 initrevs: &Bound<'_, PyAny>,
93 stoprev: PyRevision,
94 inclusive: bool,
95 ) -> PyResult<Self> {
96 let cloned_proxy = index_proxy.clone().unbind();
97 let initvec: Vec<_> =
98 rev_pyiter_collect_with_py_index(initrevs, index_proxy)?;
99 let shared_idx = py_rust_index_to_graph(index_proxy)?;
100 // Safety: we don't leak the "faked" reference out of
101 // `SharedByPyObject`
102 let res_lazy = unsafe {
103 shared_idx.map(py, |idx| {
104 VCGLazyAncestors::new(
105 idx,
106 initvec.into_iter().map(|r| r.0),
107 stoprev.0,
108 inclusive,
109 )
110 })
111 };
112 let inner =
113 py_shared_or_map_err(py, res_lazy, GraphError::from_vcsgraph)?;
114 Ok(Self {
115 inner,
116 proxy_index: cloned_proxy,
117 initrevs: initrevs.clone().unbind(),
118 stoprev,
119 inclusive,
120 })
121 }
122
123 fn __bool__(slf: PyRef<'_, Self>, py: Python<'_>) -> PyResult<bool> {
124 // Safety: we don't leak the "faked" reference out of
125 // `SharedByPyObject`
126 let inner = unsafe { slf.inner.try_borrow(py) }?;
127 Ok(!inner.is_empty())
128 }
129
130 fn __contains__(
131 mut slf: PyRefMut<'_, Self>,
132 obj: &Bound<'_, PyAny>,
133 ) -> PyResult<bool> {
134 PyRevision::extract(obj.into()).map_or(Ok(false), |rev| {
135 // Safety: we don't leak the "faked" reference out of
136 // `SharedByPyObject`
137 let mut inner = unsafe { slf.inner.try_borrow_mut(obj.py()) }?;
138 inner.contains(rev.0).map_err(GraphError::from_vcsgraph)
139 })
140 }
141
142 fn __iter__(slf: PyRef<'_, Self>) -> PyResult<AncestorsIterator> {
143 let py = slf.py();
144 AncestorsIterator::new(
145 slf.proxy_index.clone_ref(py).bind(py),
146 slf.initrevs.clone_ref(py).bind(py),
147 slf.stoprev,
148 slf.inclusive,
149 )
150 }
151 }
152
153 #[pyclass]
154 struct MissingAncestors {
155 inner: SharedByPyObject<CoreMissing<PySharedIndex>>,
156 proxy_index: Py<PyAny>,
157 }
158
159 #[pymethods]
160 impl MissingAncestors {
161 #[new]
162 fn new(
163 index_proxy: &Bound<'_, PyAny>,
164 bases: &Bound<'_, PyAny>,
165 ) -> PyResult<Self> {
166 let cloned_proxy = index_proxy.clone().unbind();
167 let bases_vec: Vec<_> =
168 rev_pyiter_collect_with_py_index(bases, index_proxy)?;
169 let shared_idx = py_rust_index_to_graph(index_proxy)?;
170
171 // Safety: we don't leak the "faked" reference out of
172 // `SharedByPyObject`
173 let inner = unsafe {
174 shared_idx
175 .map(index_proxy.py(), |idx| CoreMissing::new(idx, bases_vec))
176 };
177 Ok(Self { inner, proxy_index: cloned_proxy })
178 }
179
180 fn hasbases(slf: PyRef<'_, Self>) -> PyResult<bool> {
181 // Safety: we don't leak the "faked" reference out of
182 // `SharedByPyObject`
183 let inner = unsafe { slf.inner.try_borrow(slf.py()) }?;
184 Ok(inner.has_bases())
185 }
186
187 fn addbases(
188 mut slf: PyRefMut<'_, Self>,
189 bases: &Bound<'_, PyAny>,
190 ) -> PyResult<()> {
191 let py = slf.py();
192 let index_proxy = slf.proxy_index.bind(py);
193 let bases_vec: Vec<_> =
194 rev_pyiter_collect_with_py_index(bases, index_proxy)?;
195
196 // Safety: we don't leak the "faked" reference out of
197 // `SharedByPyObject`
198 let mut inner = unsafe { slf.inner.try_borrow_mut(py) }?;
199 inner.add_bases(bases_vec);
200 Ok(())
201 }
202
203 fn bases(slf: PyRef<'_, Self>) -> PyResult<HashSet<PyRevision>> {
204 // Safety: we don't leak the "faked" reference out of
205 // `SharedByPyObject`
206 let inner = unsafe { slf.inner.try_borrow(slf.py()) }?;
207 Ok(inner.get_bases().iter().map(|r| PyRevision(r.0)).collect())
208 }
209
210 fn basesheads(slf: PyRef<'_, Self>) -> PyResult<HashSet<PyRevision>> {
211 // Safety: we don't leak the "faked" reference out of
212 // `SharedByPyObject`
213 let inner = unsafe { slf.inner.try_borrow(slf.py()) }?;
214 Ok(inner
215 .bases_heads()
216 .map_err(GraphError::from_hg)?
217 .iter()
218 .map(|r| PyRevision(r.0))
219 .collect())
220 }
221
222 fn removeancestorsfrom(
223 mut slf: PyRefMut<'_, Self>,
224 revs: &Bound<'_, PyAny>,
225 ) -> PyResult<()> {
226 // Original comment from the now extinct hg-cpython:
227 // this is very lame: we convert to a Rust set, update it in place
228 // and then convert back to Python, only to have Python remove the
229 // excess (thankfully, Python is happy with a list or even an
230 // iterator)
231 // Leads to improve this:
232 // - have the CoreMissing instead do something emit revisions to
233 // discard
234 // - define a trait for sets of revisions in the core and implement
235 // it for a Python set rewrapped with the GIL marker
236 // PyO3 additional comment: the trait approach would probably be
237 // simpler because we can implement it without a Py wrappper, just
238 // on &Bound<'py, PySet>
239 let py = slf.py();
240 let index_proxy = slf.proxy_index.bind(py);
241 let mut revs_set: HashSet<_> =
242 rev_pyiter_collect_with_py_index(revs, index_proxy)?;
243
244 // Safety: we don't leak the "faked" reference out of
245 // `SharedByPyObject`
246 let mut inner = unsafe { slf.inner.try_borrow_mut(py) }?;
247
248 inner
249 .remove_ancestors_from(&mut revs_set)
250 .map_err(GraphError::from_hg)?;
251 // convert as Python tuple and discard from original `revs`
252 let remaining_tuple =
253 PyTuple::new(py, revs_set.iter().map(|r| PyRevision(r.0)))?;
254 revs.call_method("intersection_update", (remaining_tuple,), None)?;
255 Ok(())
256 }
257
258 fn missingancestors(
259 mut slf: PyRefMut<'_, Self>,
260 bases: &Bound<'_, PyAny>,
261 ) -> PyResult<Vec<PyRevision>> {
262 let py = slf.py();
263 let index_proxy = slf.proxy_index.bind(py);
264 let revs_vec: Vec<_> =
265 rev_pyiter_collect_with_py_index(bases, index_proxy)?;
266
267 // Safety: we don't leak the "faked" reference out of
268 // `SharedByPyObject`
269 let mut inner = unsafe { slf.inner.try_borrow_mut(py) }?;
270
271 let missing_vec =
272 inner.missing_ancestors(revs_vec).map_err(GraphError::from_hg)?;
273 Ok(missing_vec.iter().map(|r| PyRevision(r.0)).collect())
274 }
275 }
276
277 pub fn init_module<'py>(
278 py: Python<'py>,
279 package: &str,
280 ) -> PyResult<Bound<'py, PyModule>> {
281 let m = new_submodule(py, package, "ancestor")?;
282 m.add_class::<AncestorsIterator>()?;
283 m.add_class::<LazyAncestors>()?;
284 m.add_class::<MissingAncestors>()?;
285 Ok(m)
286 }