Debian Codegraph @

rust/hg-pyo3/src/shape.rs

raw
1 //! Bindings to the hg-core `narrow::shape` module for Python consumption
2
3 use std::path::Path;
4
5 use hg::file_patterns::parse_one_pattern;
6 use hg::file_patterns::FilePattern;
7 use hg::file_patterns::PatternSyntax;
8 use hg::narrow::shape::Shape;
9 use hg::narrow::shape::ShardTreeNode;
10 use hg::narrow::shape::StoreShards;
11 use hg::utils::strings::SliceExt;
12 use pyo3::prelude::*;
13 use pyo3::types::PyBytes;
14 use pyo3::types::PyList;
15 use pyo3::types::PyModule;
16 use pyo3::types::PySet;
17 use pyo3::Bound;
18 use pyo3::PyResult;
19 use pyo3::Python;
20
21 use crate::matchers::PyMatcher;
22 use crate::repo::repo_from_path;
23 use crate::utils::new_submodule;
24 use crate::utils::HgPyErrExt;
25
26 /// A Rust-backed Shape object that corresponds to a shard marked as a shape
27 /// in the `.hg/store/server-shapes` config.
28 #[pyclass(frozen, name = "Shape")]
29 pub struct PyShape {
30 inner: Shape,
31 }
32
33 #[pymethods]
34 impl PyShape {
35 /// The name of this shape as a UTF-8 string
36 pub fn name(&self) -> String {
37 self.inner.name().to_string()
38 }
39
40 /// The fingerprint of this shape as hexadecimal bytes
41 pub fn fingerprint(&self) -> Vec<u8> {
42 self.inner.store_fingerprint().to_hex_bytes()
43 }
44
45 /// A matcher for the files that this shape covers
46 pub fn matcher(&self) -> PyMatcher {
47 PyMatcher::new(Box::new(self.inner.matcher()))
48 }
49
50 /// The patterns as expected by legacy narrow code, i.e. a tuple of lists
51 /// of file patterns.
52 pub fn patterns(&self, py: Python) -> (Vec<Py<PyBytes>>, Vec<Py<PyBytes>>) {
53 let (includes, excludes) = self.inner.patterns();
54 (
55 includes
56 .iter()
57 .map(|path| PyBytes::new(py, path.as_bytes()).unbind())
58 .collect(),
59 excludes
60 .iter()
61 .map(|path| PyBytes::new(py, path.as_bytes()).unbind())
62 .collect(),
63 )
64 }
65 }
66
67 /// A useful object to query the shapes for this repo's store
68 #[pyclass(frozen, name = "StoreShards")]
69 pub struct PyStoreShards {
70 inner: StoreShards,
71 }
72
73 #[pymethods]
74 impl PyStoreShards {
75 /// Return the shape of name `name`, or `None` if it doesn't exist
76 pub fn shape(&self, py: Python, name: &str) -> PyResult<Option<PyShape>> {
77 self.inner
78 .shape(name)
79 .into_pyerr(py)
80 .map(|shape| shape.map(|inner| PyShape { inner }))
81 }
82
83 /// Return a list of all known shapes
84 pub fn all_shapes(&self, py: Python) -> PyResult<Py<PyList>> {
85 let shapes_iter = self
86 .inner
87 .all_shapes()
88 .into_pyerr(py)?
89 .into_iter()
90 .map(|shape| PyShape { inner: shape });
91 Ok(PyList::new(py, shapes_iter)?.unbind())
92 }
93 }
94
95 /// Return an object useful for querying shapes and shards for this repository
96 #[pyfunction]
97 pub fn get_store_shards(repo_path: &Bound<PyBytes>) -> PyResult<PyStoreShards> {
98 let repo = repo_from_path(repo_path)?;
99 let inner =
100 StoreShards::from_repo_config(&repo).into_pyerr(repo_path.py())?;
101 Ok(PyStoreShards { inner })
102 }
103
104 /// Return the fingerprint for the given include and exclude patterns. Returns
105 /// `None` if we're unable to get a fingerprint.
106 #[pyfunction]
107 fn fingerprint_for_patterns(
108 include_pats: &Bound<'_, PySet>,
109 exclude_pats: &Bound<'_, PySet>,
110 ) -> PyResult<Option<Vec<u8>>> {
111 let transform = |pat: Bound<'_, PyAny>| {
112 let pat = pat
113 .extract::<&[u8]>()
114 .expect("should be bytes")
115 .strip_prefix(b"path:");
116 if let Some(pat) = pat {
117 Ok(parse_one_pattern(
118 pat,
119 Path::new(""),
120 PatternSyntax::Path,
121 false,
122 ))
123 } else {
124 Err(())
125 }
126 };
127 let includes: Result<Vec<FilePattern>, ()> =
128 include_pats.iter().map(transform).collect();
129 let excludes: Result<Vec<FilePattern>, ()> =
130 exclude_pats.iter().map(transform).collect();
131 let (Ok(includes), Ok(excludes)) = (includes, excludes) else {
132 return Ok(None);
133 };
134 // Any error means we can't get a fingerprint for these patterns
135 let maybe_node = ShardTreeNode::from_patterns(&includes, &excludes).ok();
136 Ok(maybe_node.map(|node| node.fingerprint().to_hex_bytes()))
137 }
138
139 pub fn init_module<'py>(
140 py: Python<'py>,
141 package: &str,
142 ) -> PyResult<Bound<'py, PyModule>> {
143 let m = new_submodule(py, package, "shape")?;
144 m.add_class::<PyShape>()?;
145 m.add_class::<PyStoreShards>()?;
146 m.add_function(wrap_pyfunction!(get_store_shards, &m)?)?;
147 m.add_function(wrap_pyfunction!(fingerprint_for_patterns, &m)?)?;
148
149 Ok(m)
150 }