##// END OF EJS Templates
rust: implementation of `hg`...
rust: implementation of `hg` This commit provides a mostly-working implementation of the `hg` script in Rust along with scaffolding to support Rust in the repository. If you are familiar with Rust, the contents of the added rust/ directory should be pretty straightforward. We create an "hgcli" package that implements a binary application to run Mercurial. The output of this package is an "hg" binary. Our Rust `hg` (henceforth "rhg") essentially is a port of the existing `hg` Python script. The main difference is the creation of the embedded CPython interpreter is handled by the binary itself instead of relying on the shebang. In that sense, rhg is more similar to the "exe wrapper" we currently use on Windows. However, unlike the exe wrapper, rhg does not call the `hg` Python script. Instead, it uses the CPython APIs to import mercurial modules and call appropriate functions. The amount of code here is surprisingly small. It is my intent to replace the existing C-based exe wrapper with rhg. Preferably in the next Mercurial release. This should be achievable - at least for some Mercurial distributions. The future/timeline for rhg on other platforms is less clear. We already ship a hg.exe on Windows. So if we get the quirks with Rust worked out, shipping a Rust-based hg.exe should hopefully not be too contentious. Now onto the implementation. We're using python27-sys and the cpython crates for talking to the CPython API. We currently don't use too much functionality of the cpython crate and could have probably cut it out. However, it does provide a reasonable abstraction over unsafe {} CPython function calls. While we still have our fair share of those, at least we're not dealing with too much refcounting, error checking, etc. So I think the use of the cpython crate is justified. Plus, there is not-yet-implemented functionality that could benefit from cpython. I see our use of this crate only increasing. The cpython and python27-sys crates are not without their issues. The cpython crate didn't seem to account for the embedding use case in its design. Instead, it seems to assume that you are building a Python extension. It is making some questionable decisions around certain CPython APIs. For example, it insists that PyEval_ThreadsInitialized() is called and that the Python code likely isn't the main thread in the underlying application. It is also missing some functionality that is important for embedded use cases (such as exporting the path to the Python interpreter from its build script). After spending several hours trying to wrangle python27-sys and cpython, I gave up and forked the project on GitHub. Our Cargo.toml tracks this fork. I'm optimistic that the upstream project will accept our contributions and we can eventually unfork. There is a non-trivial amount of code in our custom Cargo build script. Our build.rs (which is called as part of building the hgcli crate): * Validates that the Python interpreter that was detected by the python27-sys crate provides a shared library (we only support shared library linking at this time - although this restriction could be loosened). * Validates that the Python is built with UCS-4 support. This ensures maximum Unicode compatibility. * Exports variables to the crate build allowing the built crate to e.g. find the path to the Python interpreter. The produced rhg should be considered alpha quality. There are several known deficiencies. Many of these are documented with inline TODOs. Probably the biggest limitation of rhg is that it assumes it is running from the ./rust/target/<target> directory of a source distribution. So, rhg is currently not very practical for real-world use. But, if you can `cargo build` it, running the binary *should* yield a working Mercurial CLI. In order to support using rhg with the test harness, we needed to hack up run-tests.py so the path to Mercurial's Python files is set properly. The change is extremely hacky and is only intended to be a stop-gap until the test harness gains first-class support for installing rhg. This will likely occur after we support running rhg outside the source directory. Despite its officially alpha quality, rhg copes extremely well with the test harness (at least on Linux). Using `run-tests.py --with-hg ../rust/target/debug/hg`, I only encounter the following failures: * test-run-tests.t -- Warnings emitted about using an unexpected Mercurial library. This is due to the hacky nature of setting the Python directory when run-tests.py detected rhg. * test-devel-warnings.t -- Expected stack trace missing frame for `hg` (This is expected since we no longer have an `hg` script!) * test-convert.t -- Test running `$PYTHON "$BINDIR"/hg`, which obviously assumes `hg` is a Python script. * test-merge-tools.t -- Same assumption about `hg` being executable with Python. * test-http-bad-server.t -- Seeing exit code 255 instead of 1 around line 358. * test-blackbox.t -- Exit code 255 instead of 1. * test-basic.t -- Exit code 255 instead of 1. It certainly looks like we have a bug around exit code handling. I don't think it is severe enough to hold up review and landing of this initial implementation. Perfect is the enemy of good. Differential Revision: https://phab.mercurial-scm.org/D1581

File last commit:

r35587:96421278 default
r35587:96421278 default
Show More
main.rs
222 lines | 7.2 KiB | application/rls-services+xml | RustLexer
Gregory Szorc
rust: implementation of `hg`...
r35587 // main.rs -- Main routines for `hg` program
//
// Copyright 2017 Gregory Szorc <gregory.szorc@gmail.com>
//
// This software may be used and distributed according to the terms of the
// GNU General Public License version 2 or any later version.
extern crate libc;
extern crate cpython;
extern crate python27_sys;
use cpython::{NoArgs, ObjectProtocol, PyModule, PyResult, Python};
use libc::{c_char, c_int};
use std::env;
use std::path::PathBuf;
use std::ffi::CString;
#[cfg(target_family = "unix")]
use std::os::unix::ffi::OsStringExt;
#[derive(Debug)]
struct Environment {
_exe: PathBuf,
python_exe: PathBuf,
python_home: PathBuf,
mercurial_modules: PathBuf,
}
/// Run Mercurial locally from a source distribution or checkout.
///
/// hg is <srcdir>/rust/target/<target>/hg
/// Python interpreter is detected by build script.
/// Python home is relative to Python interpreter.
/// Mercurial files are relative to hg binary, which is relative to source root.
#[cfg(feature = "localdev")]
fn get_environment() -> Environment {
let exe = env::current_exe().unwrap();
let mut mercurial_modules = exe.clone();
mercurial_modules.pop(); // /rust/target/<target>
mercurial_modules.pop(); // /rust/target
mercurial_modules.pop(); // /rust
mercurial_modules.pop(); // /
let python_exe: &'static str = env!("PYTHON_INTERPRETER");
let python_exe = PathBuf::from(python_exe);
let mut python_home = python_exe.clone();
python_home.pop();
// On Windows, python2.7.exe exists at the root directory of the Python
// install. Everywhere else, the Python install root is one level up.
if !python_exe.ends_with("python2.7.exe") {
python_home.pop();
}
Environment {
_exe: exe.clone(),
python_exe: python_exe,
python_home: python_home,
mercurial_modules: mercurial_modules.to_path_buf(),
}
}
// On UNIX, argv starts as an array of char*. So it is easy to convert
// to C strings.
#[cfg(target_family = "unix")]
fn args_to_cstrings() -> Vec<CString> {
env::args_os()
.map(|a| CString::new(a.into_vec()).unwrap())
.collect()
}
// TODO Windows support is incomplete. We should either use env::args_os()
// (or call into GetCommandLineW() + CommandLinetoArgvW()), convert these to
// PyUnicode instances, and pass these into Python/Mercurial outside the
// standard PySys_SetArgvEx() mechanism. This will allow us to preserve the
// raw bytes (since PySys_SetArgvEx() is based on char* and can drop wchar
// data.
//
// For now, we use env::args(). This will choke on invalid UTF-8 arguments.
// But it is better than nothing.
#[cfg(target_family = "windows")]
fn args_to_cstrings() -> Vec<CString> {
env::args().map(|a| CString::new(a).unwrap()).collect()
}
fn set_python_home(env: &Environment) {
let raw = CString::new(env.python_home.to_str().unwrap())
.unwrap()
.into_raw();
unsafe {
python27_sys::Py_SetPythonHome(raw);
}
}
fn update_encoding(_py: Python, _sys_mod: &PyModule) {
// Call sys.setdefaultencoding("undefined") if HGUNICODEPEDANTRY is set.
let pedantry = env::var("HGUNICODEPEDANTRY").is_ok();
if pedantry {
// site.py removes the sys.setdefaultencoding attribute. So we need
// to reload the module to get a handle on it. This is a lesser
// used feature and we'll support this later.
// TODO support this
panic!("HGUNICODEPEDANTRY is not yet supported");
}
}
fn update_modules_path(env: &Environment, py: Python, sys_mod: &PyModule) {
let sys_path = sys_mod.get(py, "path").unwrap();
sys_path
.call_method(py, "insert", (0, env.mercurial_modules.to_str()), None)
.expect("failed to update sys.path to location of Mercurial modules");
}
fn run() -> Result<(), i32> {
let env = get_environment();
//println!("{:?}", env);
// Tell Python where it is installed.
set_python_home(&env);
// Set program name. The backing memory needs to live for the duration of the
// interpreter.
//
// Yes, we use the path to the Python interpreter not argv[0] here. The
// reason is because Python uses the given path to find the location of
// Python files. Apparently we could define our own ``Py_GetPath()``
// implementation. But this may require statically linking Python, which is
// not desirable.
let program_name = CString::new(env.python_exe.to_str().unwrap())
.unwrap()
.as_ptr();
unsafe {
python27_sys::Py_SetProgramName(program_name as *mut i8);
}
unsafe {
python27_sys::Py_Initialize();
}
// https://docs.python.org/2/c-api/init.html#c.PySys_SetArgvEx has important
// usage information about PySys_SetArgvEx:
//
// * It says the first argument should be the script that is being executed.
// If not a script, it can be empty. We are definitely not a script.
// However, parts of Mercurial do look at sys.argv[0]. So we need to set
// something here.
//
// * When embedding Python, we should use ``PySys_SetArgvEx()`` and set
// ``updatepath=0`` for security reasons. Essentially, Python's default
// logic will treat an empty argv[0] in a manner that could result in
// sys.path picking up directories it shouldn't and this could lead to
// loading untrusted modules.
// env::args() will panic if it sees a non-UTF-8 byte sequence. And
// Mercurial supports arbitrary encodings of input data. So we need to
// use OS-specific mechanisms to get the raw bytes without UTF-8
// interference.
let args = args_to_cstrings();
let argv: Vec<*const c_char> = args.iter().map(|a| a.as_ptr()).collect();
unsafe {
python27_sys::PySys_SetArgvEx(args.len() as c_int, argv.as_ptr() as *mut *mut i8, 0);
}
let result;
{
// These need to be dropped before we call Py_Finalize(). Hence the
// block.
let gil = Python::acquire_gil();
let py = gil.python();
// Mercurial code could call sys.exit(), which will call exit()
// itself. So this may not return.
// TODO this may cause issues on Windows due to the CRT mismatch.
// Investigate if we can intercept sys.exit() or SystemExit() to
// ensure we handle process exit.
result = match run_py(&env, py) {
// Print unhandled exceptions and exit code 255, as this is what
// `python` does.
Err(err) => {
err.print(py);
Err(255)
}
Ok(()) => Ok(()),
};
}
unsafe {
python27_sys::Py_Finalize();
}
result
}
fn run_py(env: &Environment, py: Python) -> PyResult<()> {
let sys_mod = py.import("sys").unwrap();
update_encoding(py, &sys_mod);
update_modules_path(&env, py, &sys_mod);
// TODO consider a better error message on failure to import.
let demand_mod = py.import("hgdemandimport")?;
demand_mod.call(py, "enable", NoArgs, None)?;
let dispatch_mod = py.import("mercurial.dispatch")?;
dispatch_mod.call(py, "run", NoArgs, None)?;
Ok(())
}
fn main() {
let exit_code = match run() {
Err(err) => err,
Ok(()) => 0,
};
std::process::exit(exit_code);
}