Mercurial > hg
comparison rust/hgcli/src/main.rs @ 35569:964212780daf
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
author | Gregory Szorc <gregory.szorc@gmail.com> |
---|---|
date | Wed, 10 Jan 2018 08:53:22 -0800 |
parents | |
children | 74bec9e74831 |
comparison
equal
deleted
inserted
replaced
35568:ebf14075a5c1 | 35569:964212780daf |
---|---|
1 // main.rs -- Main routines for `hg` program | |
2 // | |
3 // Copyright 2017 Gregory Szorc <gregory.szorc@gmail.com> | |
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 extern crate libc; | |
9 extern crate cpython; | |
10 extern crate python27_sys; | |
11 | |
12 use cpython::{NoArgs, ObjectProtocol, PyModule, PyResult, Python}; | |
13 use libc::{c_char, c_int}; | |
14 | |
15 use std::env; | |
16 use std::path::PathBuf; | |
17 use std::ffi::CString; | |
18 #[cfg(target_family = "unix")] | |
19 use std::os::unix::ffi::OsStringExt; | |
20 | |
21 #[derive(Debug)] | |
22 struct Environment { | |
23 _exe: PathBuf, | |
24 python_exe: PathBuf, | |
25 python_home: PathBuf, | |
26 mercurial_modules: PathBuf, | |
27 } | |
28 | |
29 /// Run Mercurial locally from a source distribution or checkout. | |
30 /// | |
31 /// hg is <srcdir>/rust/target/<target>/hg | |
32 /// Python interpreter is detected by build script. | |
33 /// Python home is relative to Python interpreter. | |
34 /// Mercurial files are relative to hg binary, which is relative to source root. | |
35 #[cfg(feature = "localdev")] | |
36 fn get_environment() -> Environment { | |
37 let exe = env::current_exe().unwrap(); | |
38 | |
39 let mut mercurial_modules = exe.clone(); | |
40 mercurial_modules.pop(); // /rust/target/<target> | |
41 mercurial_modules.pop(); // /rust/target | |
42 mercurial_modules.pop(); // /rust | |
43 mercurial_modules.pop(); // / | |
44 | |
45 let python_exe: &'static str = env!("PYTHON_INTERPRETER"); | |
46 let python_exe = PathBuf::from(python_exe); | |
47 | |
48 let mut python_home = python_exe.clone(); | |
49 python_home.pop(); | |
50 | |
51 // On Windows, python2.7.exe exists at the root directory of the Python | |
52 // install. Everywhere else, the Python install root is one level up. | |
53 if !python_exe.ends_with("python2.7.exe") { | |
54 python_home.pop(); | |
55 } | |
56 | |
57 Environment { | |
58 _exe: exe.clone(), | |
59 python_exe: python_exe, | |
60 python_home: python_home, | |
61 mercurial_modules: mercurial_modules.to_path_buf(), | |
62 } | |
63 } | |
64 | |
65 // On UNIX, argv starts as an array of char*. So it is easy to convert | |
66 // to C strings. | |
67 #[cfg(target_family = "unix")] | |
68 fn args_to_cstrings() -> Vec<CString> { | |
69 env::args_os() | |
70 .map(|a| CString::new(a.into_vec()).unwrap()) | |
71 .collect() | |
72 } | |
73 | |
74 // TODO Windows support is incomplete. We should either use env::args_os() | |
75 // (or call into GetCommandLineW() + CommandLinetoArgvW()), convert these to | |
76 // PyUnicode instances, and pass these into Python/Mercurial outside the | |
77 // standard PySys_SetArgvEx() mechanism. This will allow us to preserve the | |
78 // raw bytes (since PySys_SetArgvEx() is based on char* and can drop wchar | |
79 // data. | |
80 // | |
81 // For now, we use env::args(). This will choke on invalid UTF-8 arguments. | |
82 // But it is better than nothing. | |
83 #[cfg(target_family = "windows")] | |
84 fn args_to_cstrings() -> Vec<CString> { | |
85 env::args().map(|a| CString::new(a).unwrap()).collect() | |
86 } | |
87 | |
88 fn set_python_home(env: &Environment) { | |
89 let raw = CString::new(env.python_home.to_str().unwrap()) | |
90 .unwrap() | |
91 .into_raw(); | |
92 unsafe { | |
93 python27_sys::Py_SetPythonHome(raw); | |
94 } | |
95 } | |
96 | |
97 fn update_encoding(_py: Python, _sys_mod: &PyModule) { | |
98 // Call sys.setdefaultencoding("undefined") if HGUNICODEPEDANTRY is set. | |
99 let pedantry = env::var("HGUNICODEPEDANTRY").is_ok(); | |
100 | |
101 if pedantry { | |
102 // site.py removes the sys.setdefaultencoding attribute. So we need | |
103 // to reload the module to get a handle on it. This is a lesser | |
104 // used feature and we'll support this later. | |
105 // TODO support this | |
106 panic!("HGUNICODEPEDANTRY is not yet supported"); | |
107 } | |
108 } | |
109 | |
110 fn update_modules_path(env: &Environment, py: Python, sys_mod: &PyModule) { | |
111 let sys_path = sys_mod.get(py, "path").unwrap(); | |
112 sys_path | |
113 .call_method(py, "insert", (0, env.mercurial_modules.to_str()), None) | |
114 .expect("failed to update sys.path to location of Mercurial modules"); | |
115 } | |
116 | |
117 fn run() -> Result<(), i32> { | |
118 let env = get_environment(); | |
119 | |
120 //println!("{:?}", env); | |
121 | |
122 // Tell Python where it is installed. | |
123 set_python_home(&env); | |
124 | |
125 // Set program name. The backing memory needs to live for the duration of the | |
126 // interpreter. | |
127 // | |
128 // Yes, we use the path to the Python interpreter not argv[0] here. The | |
129 // reason is because Python uses the given path to find the location of | |
130 // Python files. Apparently we could define our own ``Py_GetPath()`` | |
131 // implementation. But this may require statically linking Python, which is | |
132 // not desirable. | |
133 let program_name = CString::new(env.python_exe.to_str().unwrap()) | |
134 .unwrap() | |
135 .as_ptr(); | |
136 unsafe { | |
137 python27_sys::Py_SetProgramName(program_name as *mut i8); | |
138 } | |
139 | |
140 unsafe { | |
141 python27_sys::Py_Initialize(); | |
142 } | |
143 | |
144 // https://docs.python.org/2/c-api/init.html#c.PySys_SetArgvEx has important | |
145 // usage information about PySys_SetArgvEx: | |
146 // | |
147 // * It says the first argument should be the script that is being executed. | |
148 // If not a script, it can be empty. We are definitely not a script. | |
149 // However, parts of Mercurial do look at sys.argv[0]. So we need to set | |
150 // something here. | |
151 // | |
152 // * When embedding Python, we should use ``PySys_SetArgvEx()`` and set | |
153 // ``updatepath=0`` for security reasons. Essentially, Python's default | |
154 // logic will treat an empty argv[0] in a manner that could result in | |
155 // sys.path picking up directories it shouldn't and this could lead to | |
156 // loading untrusted modules. | |
157 | |
158 // env::args() will panic if it sees a non-UTF-8 byte sequence. And | |
159 // Mercurial supports arbitrary encodings of input data. So we need to | |
160 // use OS-specific mechanisms to get the raw bytes without UTF-8 | |
161 // interference. | |
162 let args = args_to_cstrings(); | |
163 let argv: Vec<*const c_char> = args.iter().map(|a| a.as_ptr()).collect(); | |
164 | |
165 unsafe { | |
166 python27_sys::PySys_SetArgvEx(args.len() as c_int, argv.as_ptr() as *mut *mut i8, 0); | |
167 } | |
168 | |
169 let result; | |
170 { | |
171 // These need to be dropped before we call Py_Finalize(). Hence the | |
172 // block. | |
173 let gil = Python::acquire_gil(); | |
174 let py = gil.python(); | |
175 | |
176 // Mercurial code could call sys.exit(), which will call exit() | |
177 // itself. So this may not return. | |
178 // TODO this may cause issues on Windows due to the CRT mismatch. | |
179 // Investigate if we can intercept sys.exit() or SystemExit() to | |
180 // ensure we handle process exit. | |
181 result = match run_py(&env, py) { | |
182 // Print unhandled exceptions and exit code 255, as this is what | |
183 // `python` does. | |
184 Err(err) => { | |
185 err.print(py); | |
186 Err(255) | |
187 } | |
188 Ok(()) => Ok(()), | |
189 }; | |
190 } | |
191 | |
192 unsafe { | |
193 python27_sys::Py_Finalize(); | |
194 } | |
195 | |
196 result | |
197 } | |
198 | |
199 fn run_py(env: &Environment, py: Python) -> PyResult<()> { | |
200 let sys_mod = py.import("sys").unwrap(); | |
201 | |
202 update_encoding(py, &sys_mod); | |
203 update_modules_path(&env, py, &sys_mod); | |
204 | |
205 // TODO consider a better error message on failure to import. | |
206 let demand_mod = py.import("hgdemandimport")?; | |
207 demand_mod.call(py, "enable", NoArgs, None)?; | |
208 | |
209 let dispatch_mod = py.import("mercurial.dispatch")?; | |
210 dispatch_mod.call(py, "run", NoArgs, None)?; | |
211 | |
212 Ok(()) | |
213 } | |
214 | |
215 fn main() { | |
216 let exit_code = match run() { | |
217 Err(err) => err, | |
218 Ok(()) => 0, | |
219 }; | |
220 | |
221 std::process::exit(exit_code); | |
222 } |