rust/hg-cpython/src/dagops.rs
changeset 41694 0c7b353ce100
child 42557 d26e4a434fe5
equal deleted inserted replaced
41693:060c030c9993 41694:0c7b353ce100
       
     1 // dagops.rs
       
     2 //
       
     3 // Copyright 2019 Georges Racinet <georges.racinet@octobus.net>
       
     4 //
       
     5 // This software may be used and distributed according to the terms of the
       
     6 // GNU General Public License version 2 or any later version.
       
     7 
       
     8 //! Bindings for the `hg::dagops` module provided by the
       
     9 //! `hg-core` package.
       
    10 //!
       
    11 //! From Python, this will be seen as `mercurial.rustext.dagop`
       
    12 use cindex::Index;
       
    13 use cpython::{PyDict, PyModule, PyObject, PyResult, Python};
       
    14 use crate::conversion::{py_set, rev_pyiter_collect};
       
    15 use exceptions::GraphError;
       
    16 use hg::dagops;
       
    17 use hg::Revision;
       
    18 use std::collections::HashSet;
       
    19 
       
    20 /// Using the the `index`, return heads out of any Python iterable of Revisions
       
    21 ///
       
    22 /// This is the Rust counterpart for `mercurial.dagop.headrevs`
       
    23 pub fn headrevs(
       
    24     py: Python,
       
    25     index: PyObject,
       
    26     revs: PyObject,
       
    27 ) -> PyResult<PyObject> {
       
    28     let mut as_set: HashSet<Revision> = rev_pyiter_collect(py, &revs)?;
       
    29     dagops::retain_heads(&Index::new(py, index)?, &mut as_set)
       
    30         .map_err(|e| GraphError::pynew(py, e))?;
       
    31     py_set(py, &as_set)
       
    32 }
       
    33 
       
    34 /// Create the module, with `__package__` given from parent
       
    35 pub fn init_module(py: Python, package: &str) -> PyResult<PyModule> {
       
    36     let dotted_name = &format!("{}.dagop", package);
       
    37     let m = PyModule::new(py, dotted_name)?;
       
    38     m.add(py, "__package__", package)?;
       
    39     m.add(py, "__doc__", "DAG operations - Rust implementation")?;
       
    40     m.add(
       
    41         py,
       
    42         "headrevs",
       
    43         py_fn!(py, headrevs(index: PyObject, revs: PyObject)),
       
    44     )?;
       
    45 
       
    46     let sys = PyModule::import(py, "sys")?;
       
    47     let sys_modules: PyDict = sys.get(py, "modules")?.extract(py)?;
       
    48     sys_modules.set_item(py, dotted_name, &m)?;
       
    49     // Example C code (see pyexpat.c and import.c) will "give away the
       
    50     // reference", but we won't because it will be consumed once the
       
    51     // Rust PyObject is dropped.
       
    52     Ok(m)
       
    53 }