use std::path::Path;
use pyo3::exceptions::PyKeyError;
use pyo3::prelude::*;
use pyo3::types::{PyIterator, PyList, PyString};
use crate::domain;
use super::to_py;
#[pyclass(frozen, name = "Document", module = "matra")]
pub(super) struct PyDocument {
inner: domain::Document,
}
const KEYS: [&str; 4] = ["provenance", "sections", "metrics", "skipped"];
impl PyDocument {
pub(super) fn new(inner: domain::Document) -> Self {
Self { inner }
}
pub(super) fn inner(&self) -> &domain::Document {
&self.inner
}
fn field<'py>(&self, py: Python<'py>, key: &str) -> PyResult<Option<Bound<'py, PyAny>>> {
let domain::Document {
provenance,
sections,
metrics,
skipped,
} = &self.inner;
Ok(Some(match key {
"provenance" => provenance_dict(py, provenance)?,
"sections" => to_py(py, sections)?,
"metrics" => to_py(py, metrics)?,
"skipped" => to_py(py, skipped)?,
_ => return Ok(None),
}))
}
}
#[pymethods]
impl PyDocument {
fn __getitem__<'py>(
&self,
py: Python<'py>,
key: &Bound<'py, PyAny>,
) -> PyResult<Bound<'py, PyAny>> {
let found = match key.extract::<String>() {
Ok(name) => self.field(py, &name)?,
Err(_) => None,
};
found.ok_or_else(|| PyKeyError::new_err(key.clone().unbind()))
}
fn __contains__(&self, key: &Bound<'_, PyAny>) -> bool {
key.extract::<String>()
.is_ok_and(|name| KEYS.contains(&name.as_str()))
}
fn __iter__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyIterator>> {
PyList::new(py, KEYS)?.as_any().try_iter()
}
fn __len__(&self) -> usize {
KEYS.len()
}
fn keys(&self) -> Vec<&'static str> {
KEYS.to_vec()
}
fn to_dict<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
let dict = to_py(py, &self.inner)?;
with_source_path(&dict, &self.inner.provenance)?;
Ok(dict)
}
fn __repr__(&self) -> String {
format!(
"<matra.Document: {} section(s), {} sentence(s), {} bytes>",
self.inner.sections.len(),
self.inner.sentences().count(),
self.inner.provenance.source.bytes,
)
}
}
fn provenance_dict<'py>(
py: Python<'py>,
provenance: &domain::Provenance,
) -> PyResult<Bound<'py, PyAny>> {
let dict = to_py(py, provenance)?;
if let Some(path) = provenance.source.path.as_deref() {
dict.get_item("source")?
.set_item("path", fs_path_str(py, path)?)?;
}
Ok(dict)
}
pub(super) fn with_source_path(
dict: &Bound<'_, PyAny>,
provenance: &domain::Provenance,
) -> PyResult<()> {
if let Some(path) = provenance.source.path.as_deref() {
dict.get_item("provenance")?
.get_item("source")?
.set_item("path", fs_path_str(dict.py(), path)?)?;
}
Ok(())
}
pub(super) fn document_error_dict<'py>(
py: Python<'py>,
err: &domain::DocumentError,
) -> PyResult<Bound<'py, PyAny>> {
let dict = to_py(py, err)?;
let path = err
.path
.as_deref()
.map(|p| fs_path_str(py, p))
.transpose()?;
dict.set_item("path", path)?;
Ok(dict)
}
#[cfg(unix)]
fn fs_path_str<'py>(py: Python<'py>, path: &Path) -> PyResult<Bound<'py, PyString>> {
use std::os::unix::ffi::OsStrExt;
let bytes = pyo3::types::PyBytes::new(py, path.as_os_str().as_bytes());
let decoded = py.import("os")?.getattr("fsdecode")?.call1((bytes,))?;
Ok(decoded.cast_into::<PyString>()?)
}
#[cfg(not(unix))]
fn fs_path_str<'py>(py: Python<'py>, path: &Path) -> PyResult<Bound<'py, PyString>> {
Ok(PyString::new(py, &path.to_string_lossy()))
}