| 1 |
//! Bindings to the hg-core `matchers` module for Python consumption |
| 2 |
|
| 3 |
use hg::matchers::Matcher; |
| 4 |
use hg::utils::hg_path::HgPath; |
| 5 |
use pyo3::pyclass; |
| 6 |
use pyo3::pymethods; |
| 7 |
use pyo3::types::PyBytes; |
| 8 |
use pyo3::types::PyList; |
| 9 |
use pyo3::types::PyModule; |
| 10 |
use pyo3::types::PyModuleMethods; |
| 11 |
use pyo3::Bound; |
| 12 |
use pyo3::Py; |
| 13 |
use pyo3::PyResult; |
| 14 |
use pyo3::Python; |
| 15 |
|
| 16 |
use crate::utils::new_submodule; |
| 17 |
|
| 18 |
#[pyclass] |
| 19 |
pub struct PyMatcher { |
| 20 |
inner: Box<dyn Matcher + Send>, |
| 21 |
} |
| 22 |
|
| 23 |
impl PyMatcher { |
| 24 |
pub fn new(inner: Box<dyn Matcher + Send>) -> Self { |
| 25 |
Self { inner } |
| 26 |
} |
| 27 |
} |
| 28 |
|
| 29 |
#[pymethods] |
| 30 |
impl PyMatcher { |
| 31 |
fn __call__(&self, path: &[u8]) -> PyResult<bool> { |
| 32 |
Ok(self.inner.matches(HgPath::new(path))) |
| 33 |
} |
| 34 |
|
| 35 |
fn always(&self) -> bool { |
| 36 |
self.inner.matches_everything() |
| 37 |
} |
| 38 |
|
| 39 |
fn isexact(&self) -> bool { |
| 40 |
self.inner.is_exact() |
| 41 |
} |
| 42 |
|
| 43 |
fn prefix(&self) -> bool { |
| 44 |
// TODO might be a lie, but this is an optimization, not a guarantee |
| 45 |
false |
| 46 |
} |
| 47 |
|
| 48 |
fn files(&self, py: Python) -> PyResult<Py<PyList>> { |
| 49 |
let Some(files) = self.inner.file_set() else { |
| 50 |
return Ok(PyList::empty(py).unbind()); |
| 51 |
}; |
| 52 |
|
| 53 |
let iter = files.iter().map(|f| PyBytes::new(py, f.as_bytes())); |
| 54 |
Ok(PyList::new(py, iter)?.unbind()) |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
pub fn init_module<'py>( |
| 59 |
py: Python<'py>, |
| 60 |
package: &str, |
| 61 |
) -> PyResult<Bound<'py, PyModule>> { |
| 62 |
let m = new_submodule(py, package, "matchers")?; |
| 63 |
m.add_class::<PyMatcher>()?; |
| 64 |
Ok(m) |
| 65 |
} |