Debian Codegraph @

rust/hg-pyo3/src/path.rs

raw
1 // path.rs
2 //
3 // Copyright 2019 Raphaël Gomès <[email protected]>
4 // 2025 Georges Racinet <[email protected]>
5 //
6 // This software may be used and distributed according to the terms of the
7 // GNU General Public License version 2 or any later version.
8 //! Utilities about `HgPath` and related objects provided by the `hg-core`
9 //! package.
10
11 use std::convert::Infallible;
12
13 use hg::dirstate::on_disk::DirstateV2ParseError;
14 use hg::utils::hg_path::HgPath;
15 use hg::utils::hg_path::HgPathBuf;
16 use pyo3::prelude::*;
17 use pyo3::types::PyBytes;
18 use pyo3::types::PyList;
19
20 use crate::exceptions::dirstate_v2_error;
21
22 #[derive(Eq, Ord, PartialEq, PartialOrd, Hash, derive_more::From)]
23 pub struct PyHgPathRef<'a>(pub &'a HgPath);
24
25 impl<'py> IntoPyObject<'py> for PyHgPathRef<'_> {
26 type Target = PyBytes;
27 type Output = Bound<'py, Self::Target>;
28 type Error = Infallible;
29
30 fn into_pyobject(
31 self,
32 py: Python<'py>,
33 ) -> Result<Self::Output, Self::Error> {
34 Ok(PyBytes::new(py, self.0.as_bytes()))
35 }
36 }
37
38 #[derive(Eq, Ord, PartialEq, PartialOrd, Hash, derive_more::From)]
39 pub struct PyHgPathBuf(pub HgPathBuf);
40
41 // This is for now equivalent to taking a ref as `HgPath` and using
42 // `HgPathRef`. One day, perhaps, this variant for owned data could be
43 // implemented without allocation.
44 impl<'py> IntoPyObject<'py> for PyHgPathBuf {
45 type Target = PyBytes;
46 type Output = Bound<'py, Self::Target>;
47 type Error = Infallible;
48
49 fn into_pyobject(
50 self,
51 py: Python<'py>,
52 ) -> Result<Self::Output, Self::Error> {
53 Ok(PyBytes::new(py, self.0.as_bytes()))
54 }
55 }
56
57 pub struct PyHgPathDirstateV2Result<'a>(
58 pub Result<&'a HgPath, DirstateV2ParseError>,
59 );
60
61 impl<'py> IntoPyObject<'py> for PyHgPathDirstateV2Result<'_> {
62 type Target = PyBytes;
63 type Output = Bound<'py, Self::Target>;
64 type Error = PyErr;
65
66 fn into_pyobject(
67 self,
68 py: Python<'py>,
69 ) -> Result<Self::Output, Self::Error> {
70 Ok(PyBytes::new(py, self.0.map_err(dirstate_v2_error)?.as_bytes()))
71 }
72 }
73
74 pub fn paths_py_list<I, U>(
75 py: Python<'_>,
76 paths: impl IntoIterator<Item = I, IntoIter = U>,
77 ) -> PyResult<Py<PyList>>
78 where
79 I: AsRef<HgPath>,
80 U: ExactSizeIterator<Item = I>,
81 {
82 Ok(PyList::new(
83 py,
84 paths.into_iter().map(|p| PyBytes::new(py, p.as_ref().as_bytes())),
85 )?
86 .unbind())
87 }
88
89 pub fn paths_pyiter_collect<C>(paths: &Bound<'_, PyAny>) -> PyResult<C>
90 where
91 C: FromIterator<HgPathBuf>,
92 {
93 paths
94 .try_iter()?
95 .map(|p| {
96 let path = p?;
97 Ok(HgPathBuf::from_bytes(path.cast::<PyBytes>()?.as_bytes()))
98 })
99 .collect()
100 }