roezio: Add Python bindings to logs parsing

Signed-off-by: Maxime “pep” Buquet <pep@bouah.net>
This commit is contained in:
Emmanuel Gil Peyrot 2022-03-23 14:06:22 +01:00 committed by Maxime “pep” Buquet
parent 5346e88840
commit c68b00ae24

View file

@ -1,13 +1,16 @@
mod logger;
mod theming;
use crate::logger::LogItem;
use crate::theming::{curses_attr, parse_attrs};
use chrono::{Datelike, Timelike};
use pyo3::{
conversion::{IntoPy, ToPyObject},
create_exception,
marker::Python,
prelude::{pyfunction, pymodule, wrap_pyfunction, PyErr, PyModule, PyObject, PyResult},
types::{PyDateTime, PyDict},
};
create_exception!(libpoezio, LogParseError, pyo3::exceptions::PyException);
@ -16,6 +19,7 @@ create_exception!(libpoezio, LogParseError, pyo3::exceptions::PyException);
fn libpoezio(py: Python, m: &PyModule) -> PyResult<()> {
m.add("LogParseError", py.get_type::<LogParseError>())?;
m.add_function(wrap_pyfunction!(to_curses_attr, m)?)?;
m.add_function(wrap_pyfunction!(parse_logs, m)?)?;
Ok(())
}
@ -39,3 +43,46 @@ fn to_curses_attr(py: Python, fg: i16, bg: i16, attrs: &str) -> PyResult<PyObjec
let result = curses_attr(fg, bg, attrs);
Ok(py_object!(py, result))
}
fn chrono_to_datetime(py: Python, chrono: &chrono::DateTime<chrono::Utc>) -> PyResult<PyObject> {
let datetime = PyDateTime::new(
py,
chrono.year(),
chrono.month() as u8,
chrono.day() as u8,
chrono.hour() as u8,
chrono.minute() as u8,
chrono.second() as u8,
0,
None,
)?;
Ok(datetime.to_object(py))
}
#[pyfunction]
fn parse_logs(py: Python, input: &str) -> PyResult<PyObject> {
let logs = match logger::parse_logs(input) {
Ok((_, logs)) => logs,
Err(err) => return Err(nom_to_py_err(py, err)),
};
let mut items = Vec::new();
for item in logs {
let dict = PyDict::new(py);
let (time, txt) = match item {
logger::Item::Message(message) => {
let time = chrono_to_datetime(py, message.get_time())?;
dict.set_item("nickname", message.get_nick())?;
(time, message.get_message())
}
logger::Item::Info(info) => {
let time = chrono_to_datetime(py, info.get_time())?;
(time, info.get_message())
}
};
dict.set_item("history", true)?;
dict.set_item("time", time)?;
dict.set_item("txt", txt)?;
items.push(dict);
}
Ok(items.into_py(py).to_object(py))
}