From c68b00ae248476751935499dbe5fb151e2919569 Mon Sep 17 00:00:00 2001 From: Emmanuel Gil Peyrot Date: Wed, 23 Mar 2022 14:06:22 +0100 Subject: [PATCH] roezio: Add Python bindings to logs parsing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Maxime “pep” Buquet --- src/lib.rs | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 40464c30..4a99947a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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::())?; 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) -> PyResult { + 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 { + 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)) +}