view rust/hg-cpython/src/utils.rs @ 44540:82f51ab7a2dd

rust: add logging utils This change adds the `log` crate, the community-approved logging facade backed by Rust core developers as well as the logging-consumer crate `simple_logger` to build a foundation for logging from Rust. Using this setup allows us to choose how to log depending on the way `hg-core` is used: if it's within the context of `hg-cpython`, we might not want to use it the same way as with a direct cli for example. Differential Revision: https://phab.mercurial-scm.org/D8252
author Raphaël Gomès <rgomes@octobus.net>
date Fri, 06 Mar 2020 18:08:13 +0100
parents d738b7a18438
children 26114bd6ec60
line wrap: on
line source

use cpython::exc::ValueError;
use cpython::{PyBytes, PyDict, PyErr, PyObject, PyResult, PyTuple, Python};
use hg::revlog::Node;
use std::convert::TryFrom;

#[allow(unused)]
pub fn print_python_trace(py: Python) -> PyResult<PyObject> {
    eprintln!("===============================");
    eprintln!("Printing Python stack from Rust");
    eprintln!("===============================");
    let traceback = py.import("traceback")?;
    let sys = py.import("sys")?;
    let kwargs = PyDict::new(py);
    kwargs.set_item(py, "file", sys.get(py, "stderr")?)?;
    traceback.call(py, "print_stack", PyTuple::new(py, &[]), Some(&kwargs))
}

// Necessary evil for the time being, could maybe be moved to
// a TryFrom in Node itself
const NODE_BYTES_LENGTH: usize = 20;
type NodeData = [u8; NODE_BYTES_LENGTH];

/// Copy incoming Python bytes given as `PyObject` into `Node`,
/// doing the necessary checks
pub fn node_from_py_object<'a>(
    py: Python,
    bytes: &'a PyObject,
) -> PyResult<Node> {
    let as_py_bytes: &'a PyBytes = bytes.extract(py)?;
    node_from_py_bytes(py, as_py_bytes)
}

/// Clone incoming Python bytes given as `PyBytes` as a `Node`,
/// doing the necessary checks.
pub fn node_from_py_bytes<'a>(
    py: Python,
    bytes: &'a PyBytes,
) -> PyResult<Node> {
    <NodeData>::try_from(bytes.data(py))
        .map_err(|_| {
            PyErr::new::<ValueError, _>(
                py,
                format!("{}-byte hash required", NODE_BYTES_LENGTH),
            )
        })
        .map(|n| n.into())
}