Python 3 build support
* Add python3-sys to rust-cpython as an optional feature, and make python27-sys also optional, but still the default * Parametrise python27-sys/build.rs so that it is python version independent, and clone it into python3-sys/build.rs. Hopefully this can continue to be maintained as an identical file. * python27-sys and python3-sys gain features for explicitly selecting a python version to link to. for python27-sys, there's currently only python27; for python3-sys there's python 3.4 and 3.5. * explicitly tell travis to use nightlies (seems to have started trying to use 1.0.0)
This commit is contained in:
parent
d4bdcc5cbd
commit
b1eca56ec3
|
@ -1,4 +1,5 @@
|
|||
language: rust
|
||||
rust: nightly
|
||||
env:
|
||||
global:
|
||||
- secure: g4kCg8twONwKPquuJmYrvGjo2n0lNtWTbyzFOITNn8FgCxNK2j38Qc9/UhErTR3g3rDjVzsTHZ8FTH7TJZrOK1Nzz90tJG6JHqUv77ufkcBlxgwwjilOz84uQhkDTMpLitMEeQDLEynKeWbxrjtc5LIpjEkxOPk5eiqwzKRN14c=
|
||||
|
|
10
Cargo.toml
10
Cargo.toml
|
@ -26,6 +26,16 @@ build = "build.rs"
|
|||
libc="*"
|
||||
num="*"
|
||||
|
||||
# These features are both optional, but you must pick one to
|
||||
# indicate which python ffi you are trying to bind to.
|
||||
[dependencies.python27-sys]
|
||||
path="python27-sys"
|
||||
optional = true
|
||||
|
||||
[dependencies.python3-sys]
|
||||
path = "python3-sys"
|
||||
optional = true
|
||||
|
||||
[features]
|
||||
# Maybe one day python 3 should be the default. But not this day.
|
||||
default = ["python27-sys"]
|
||||
|
|
19
build.rs
19
build.rs
|
@ -1,11 +1,28 @@
|
|||
use std::env;
|
||||
use std::io::Write;
|
||||
|
||||
const CFG_KEY: &'static str = "py_sys_config";
|
||||
|
||||
#[cfg(feature="python27-sys")]
|
||||
const PYTHONSYS_ENV_VAR: &'static str = "DEP_PYTHON27_PYTHON_FLAGS";
|
||||
|
||||
#[cfg(feature="python3-sys")]
|
||||
const PYTHONSYS_ENV_VAR: &'static str = "DEP_PYTHON3_PYTHON_FLAGS";
|
||||
|
||||
fn main() {
|
||||
// python{27,3.x}-sys/build.rs passes python interpreter compile flags via
|
||||
// environment variable (using the 'links' mechanism in the cargo.toml).
|
||||
let flags = env::var("DEP_PYTHON27_PYTHON_FLAGS").unwrap();
|
||||
let flags = match env::var(PYTHONSYS_ENV_VAR) {
|
||||
Ok(flags) => flags,
|
||||
Err(_) => {
|
||||
writeln!(std::io::stderr(),
|
||||
"Environment variable {} not found - this is supposed to be \
|
||||
exported from the pythonXX-sys dependency, so the build chain is broken",
|
||||
PYTHONSYS_ENV_VAR).unwrap();
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
for f in flags.split(",") {
|
||||
// write out flags as --cfg so that the same #cfg blocks can be used
|
||||
// in rust-cpython as in the -sys libs
|
||||
|
|
|
@ -22,11 +22,24 @@ exclude = [
|
|||
[dependencies]
|
||||
libc = "*"
|
||||
|
||||
# [build-dependencies]
|
||||
[build-dependencies]
|
||||
# pkg-config = "0.3"
|
||||
regex = "0.1.8"
|
||||
|
||||
# TODO: depends on trunk pkg-config for now because we
|
||||
# require 14c4b9, can revert this when alex bumps the
|
||||
# crate release
|
||||
[build-dependencies.pkg-config]
|
||||
git = "https://github.com/alexcrichton/pkg-config-rs.git"
|
||||
|
||||
[features]
|
||||
# This is examined by ./build.rs to determine which python version
|
||||
# to try to bind to.
|
||||
#
|
||||
# According to PEP 404 there will never be a python 2.8, but maybe
|
||||
# one day we could try to support < 2.7 ?
|
||||
#
|
||||
# Similarly functionality is duplicated in python3-sys/Cargo.toml
|
||||
# where supporting multiple 3.x's is more important.
|
||||
default = ["python_2_7"]
|
||||
python_2_7 = []
|
||||
|
|
|
@ -1,7 +1,16 @@
|
|||
extern crate pkg_config;
|
||||
extern crate regex;
|
||||
|
||||
use std::process::Command;
|
||||
use std::collections::HashMap;
|
||||
use std::env;
|
||||
use regex::Regex;
|
||||
use std::fs;
|
||||
|
||||
struct PythonVersion {
|
||||
major: u8,
|
||||
minor: u8
|
||||
}
|
||||
|
||||
const CFG_KEY: &'static str = "py_sys_config";
|
||||
|
||||
|
@ -32,7 +41,7 @@ static SYSCONFIG_VALUES: [&'static str; 1] = [
|
|||
// below are translated into bools as {varname}_{val}
|
||||
//
|
||||
// for example, Py_UNICODE_SIZE_2 or Py_UNICODE_SIZE_4
|
||||
"Py_UNICODE_SIZE"
|
||||
"Py_UNICODE_SIZE" // note - not present on python 3.3+, which is always wide
|
||||
];
|
||||
|
||||
/// Examine python's compile flags to pass to cfg by launching
|
||||
|
@ -43,7 +52,8 @@ fn get_config_vars(python_path: &String) -> Result<HashMap<String, String>, Stri
|
|||
config = sysconfig.get_config_vars();".to_owned();
|
||||
|
||||
for k in SYSCONFIG_FLAGS.iter().chain(SYSCONFIG_VALUES.iter()) {
|
||||
script.push_str(&format!("print(config.get('{}', 0))", k));
|
||||
script.push_str(&format!("print(config.get('{}', {}))", k,
|
||||
if is_value(k) { "None" } else { "0" } ));
|
||||
script.push_str(";");
|
||||
}
|
||||
|
||||
|
@ -62,18 +72,21 @@ config = sysconfig.get_config_vars();".to_owned();
|
|||
}
|
||||
|
||||
let stdout = String::from_utf8(out.stdout).unwrap();
|
||||
|
||||
let var_map : HashMap<String, String> =
|
||||
SYSCONFIG_FLAGS.iter().chain(SYSCONFIG_VALUES.iter()).zip(stdout.split('\n'))
|
||||
.map(|(&k, v)| (k.to_owned(), v.to_owned()))
|
||||
.collect();
|
||||
|
||||
if var_map.len() != SYSCONFIG_VALUES.len() + SYSCONFIG_FLAGS.len() {
|
||||
let split_stdout: Vec<&str> = stdout.trim_right().split('\n').collect();
|
||||
if split_stdout.len() != SYSCONFIG_VALUES.len() + SYSCONFIG_FLAGS.len() {
|
||||
return Err(
|
||||
"python stdout len didn't return expected number of lines".to_string());
|
||||
format!("python stdout len didn't return expected number of lines:
|
||||
{}", split_stdout.len()).to_string());
|
||||
}
|
||||
|
||||
return Ok(var_map);
|
||||
let all_vars = SYSCONFIG_FLAGS.iter().chain(SYSCONFIG_VALUES.iter());
|
||||
// let var_map: HashMap<String, String> = HashMap::new();
|
||||
Ok(all_vars.zip(split_stdout.iter())
|
||||
.fold(HashMap::new(), |mut memo: HashMap<String, String>, (&k, &v)| {
|
||||
if !(v.to_owned() == "None" && is_value(k)) {
|
||||
memo.insert(k.to_owned(), v.to_owned());
|
||||
}
|
||||
memo
|
||||
}))
|
||||
}
|
||||
|
||||
fn is_value(key: &str) -> bool {
|
||||
|
@ -114,11 +127,13 @@ fn run_python_script(script: &str) -> Result<String, String> {
|
|||
}
|
||||
|
||||
#[cfg(not(target_os="macos"))]
|
||||
fn get_rustc_link_lib(enable_shared: bool) -> Result<String, String> {
|
||||
fn get_rustc_link_lib(version: &PythonVersion, enable_shared: bool) -> Result<String, String> {
|
||||
if enable_shared {
|
||||
Ok("cargo:rustc-link-lib=python2.7".to_owned())
|
||||
Ok(format!("cargo:rustc-link-lib=python{}.{}", version.major,
|
||||
version.minor))
|
||||
} else {
|
||||
Ok("cargo:rustc-link-lib=static=python2.7".to_owned())
|
||||
Ok(format!("cargo:rustc-link-lib=static=python{}.{}", version.major,
|
||||
version.minor))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -130,13 +145,17 @@ fn get_macos_linkmodel() -> Result<String, String> {
|
|||
}
|
||||
|
||||
#[cfg(target_os="macos")]
|
||||
fn get_rustc_link_lib(_: bool) -> Result<String, String> {
|
||||
fn get_rustc_link_lib(version: &PythonVersion, _: bool) -> Result<String, String> {
|
||||
// os x can be linked to a framework or static or dynamic, and
|
||||
// Py_ENABLE_SHARED is wrong; framework means shared library
|
||||
let dotted_version = format!("{}.{}", version.major, version.minor);
|
||||
match get_macos_linkmodel().unwrap().as_ref() {
|
||||
"static" => Ok("cargo:rustc-link-lib=static=python2.7".to_owned()),
|
||||
"dynamic" => Ok("cargo:rustc-link-lib=python2.7".to_owned()),
|
||||
"framework" => Ok("cargo:rustc-link-lib=python2.7".to_owned()),
|
||||
"static" => Ok(format!("cargo:rustc-link-lib=static=python{}",
|
||||
dotted_version)),
|
||||
"dynamic" => Ok(format!("cargo:rustc-link-lib=python{}",
|
||||
dotted_version)),
|
||||
"framework" => Ok(format!("cargo:rustc-link-lib=python{}",
|
||||
dotted_version)),
|
||||
other => Err(format!("unknown linkmodel {}", other))
|
||||
}
|
||||
}
|
||||
|
@ -145,7 +164,7 @@ fn get_rustc_link_lib(_: bool) -> Result<String, String> {
|
|||
/// cargo vars to stdout.
|
||||
///
|
||||
/// Note that if that python isn't version 2.7, this will error.
|
||||
fn configure_from_path() -> Result<String, String> {
|
||||
fn configure_from_path(expected_version: &PythonVersion) -> Result<String, String> {
|
||||
let script = "import sys; import sysconfig; print(sys.version_info[0:2]); \
|
||||
print(sysconfig.get_config_var('LIBDIR')); \
|
||||
print(sysconfig.get_config_var('Py_ENABLE_SHARED')); \
|
||||
|
@ -158,28 +177,69 @@ print(sys.exec_prefix);";
|
|||
|
||||
let exec_prefix: &str = lines[3];
|
||||
|
||||
if version != "(2, 7)" {
|
||||
return Err(format!("'python' is not version 2.7 (is {})", version));
|
||||
if version != format!("({}, {})",
|
||||
expected_version.major,
|
||||
expected_version.minor)
|
||||
{
|
||||
return Err(format!("'python' is not version {}.{} (is {})",
|
||||
expected_version.major, expected_version.minor, version));
|
||||
}
|
||||
|
||||
println!("{}", get_rustc_link_lib(enable_shared == "1").unwrap());
|
||||
println!("{}", get_rustc_link_lib(expected_version,
|
||||
enable_shared == "1").unwrap());
|
||||
println!("cargo:rustc-link-search=native={}", libpath);
|
||||
return Ok(format!("{}/bin/python", exec_prefix));
|
||||
}
|
||||
|
||||
/// Deduce configuration from the python-2.7 in pkg-config and print
|
||||
/// Deduce configuration from the python-X.X in pkg-config and print
|
||||
/// cargo vars to stdout.
|
||||
fn configure_from_pkgconfig() -> Result<String, String> {
|
||||
fn configure_from_pkgconfig(version: &PythonVersion, pkg_name: &str)
|
||||
-> Result<String, String> {
|
||||
// this emits relevant build info to stdout, which is picked up by the
|
||||
// build chain (funny name for something with side-effects!)
|
||||
try!(pkg_config::find_library("python-2.7"));
|
||||
try!(pkg_config::find_library(pkg_name));
|
||||
|
||||
let exec_prefix = pkg_config::Config::get_variable("python-2.7",
|
||||
// This seems to be a convention - unfortunately pkg-config doesn't
|
||||
// tell you the executable name, but I've noticed at least on
|
||||
// OS X homebrew the python bin dir for 3.4 doesn't actually contain
|
||||
// a 'python'.
|
||||
let exec_prefix = pkg_config::Config::get_variable(pkg_name,
|
||||
"exec_prefix").unwrap();
|
||||
// assume path to the pkg_config python interpreter is
|
||||
// {exec_prefix}/bin/python - this might not hold for all platforms, but
|
||||
// the .pc doesn't give us anything else to go on
|
||||
return Ok(format!("{}/bin/python", exec_prefix));
|
||||
|
||||
// try to find the python interpreter in the exec_prefix somewhere.
|
||||
// the .pc doesn't tell us :(
|
||||
let attempts = [
|
||||
format!("/bin/python{}_{}", version.major, version.minor),
|
||||
format!("/bin/python{}", version.major),
|
||||
"/bin/python".to_owned()
|
||||
];
|
||||
|
||||
for attempt in attempts.iter() {
|
||||
let possible_exec_name = format!("{}{}", exec_prefix,
|
||||
attempt);
|
||||
match fs::metadata(&possible_exec_name) {
|
||||
Ok(_) => return Ok(possible_exec_name),
|
||||
Err(_) => ()
|
||||
};
|
||||
}
|
||||
return Err("Unable to locate python interpreter".to_owned());
|
||||
}
|
||||
|
||||
/// Determine the python version we're supposed to be building
|
||||
/// from the features passed via the environment.
|
||||
fn version_from_env() -> Result<PythonVersion, String> {
|
||||
let re = Regex::new(r"CARGO_FEATURE_PYTHON_(\d+)_(\d+)").unwrap();
|
||||
for (key, _) in env::vars() {
|
||||
match re.captures(&key) {
|
||||
Some(cap) => return Ok(PythonVersion {
|
||||
major: cap.at(1).unwrap().parse().unwrap(),
|
||||
minor: cap.at(2).unwrap().parse().unwrap()
|
||||
}),
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
Err("Python version feature was not found. At least one python version \
|
||||
feature must be enabled.".to_owned())
|
||||
}
|
||||
|
||||
fn main() {
|
||||
|
@ -189,16 +249,22 @@ fn main() {
|
|||
//
|
||||
// By default, try to use pkgconfig - this seems to be a rust norm.
|
||||
//
|
||||
// If you want to use a different python, setting the
|
||||
// PYTHON_2.7_NO_PKG_CONFIG environment variable will cause the script
|
||||
// to pick up the python in your PATH (this will work smoothly with an
|
||||
// activated virtualenv). If you have troubles with your shell accepting
|
||||
// '.' in a var name, try using 'env'.
|
||||
let python_interpreter_path = match configure_from_pkgconfig() {
|
||||
// If you want to use a different python, setting the appropriate
|
||||
// PYTHON_X.X_NO_PKG_CONFIG environment variable will cause the script
|
||||
// to pick up the python in your PATH; e.g. for python27 X.X is 2.7.
|
||||
//
|
||||
// This will work smoothly with an activated virtualenv.
|
||||
//
|
||||
// If you have troubles with your shell accepting '.' in a var name,
|
||||
// try using 'env' (sorry but this isn't our fault - it just has to
|
||||
// match the pkg-config package name, which is going to have a . in it).
|
||||
let version = version_from_env().unwrap();
|
||||
let pkg_name = format!("python-{}.{}", version.major, version.minor);
|
||||
let python_interpreter_path = match configure_from_pkgconfig(&version, &pkg_name) {
|
||||
Ok(p) => p,
|
||||
// no pkgconfig - either it failed or user set the environment
|
||||
// variable "PYTHON_2.7_NO_PKG_CONFIG".
|
||||
Err(_) => configure_from_path().unwrap()
|
||||
Err(_) => configure_from_path(&version).unwrap()
|
||||
};
|
||||
|
||||
let config_map = get_config_vars(&python_interpreter_path).unwrap();
|
||||
|
|
|
@ -12,6 +12,7 @@ homepage = "https://github.com/dgrunwald/rust-cpython/tree/master/python3-sys"
|
|||
repository = "https://github.com/dgrunwald/rust-cpython/tree/master/python3-sys"
|
||||
license = "Python-2.0"
|
||||
authors = ["Daniel Grunwald <daniel@danielgrunwald.de>"]
|
||||
links = "python3"
|
||||
build = "build.rs"
|
||||
exclude = [
|
||||
".gitignore",
|
||||
|
@ -22,15 +23,18 @@ exclude = [
|
|||
libc = "*"
|
||||
|
||||
[build-dependencies]
|
||||
pkg-config = "0.3"
|
||||
# pkg-config = "0.3"
|
||||
regex = "0.1.8"
|
||||
|
||||
# TODO: depends on trunk pkg-config for now because we
|
||||
# require 14c4b9, can revert this when alex bumps the
|
||||
# crate release
|
||||
[build-dependencies.pkg-config]
|
||||
git = "https://github.com/alexcrichton/pkg-config-rs.git"
|
||||
|
||||
[features]
|
||||
|
||||
default = ["WITH_THREAD"]
|
||||
|
||||
Py_TRACE_REFS = []
|
||||
WITH_THREAD = []
|
||||
|
||||
"python3_3" = []
|
||||
"python3_4" = ["python3_3"]
|
||||
|
||||
# This is examined by ./build.rs to determine which python version
|
||||
# to try to bind to.
|
||||
default = ["python_3_4"]
|
||||
python_3_4 = []
|
||||
python_3_5 = []
|
||||
|
|
|
@ -1,6 +1,301 @@
|
|||
extern crate pkg_config;
|
||||
extern crate regex;
|
||||
|
||||
fn main() {
|
||||
pkg_config::find_library("python3").unwrap();
|
||||
use std::process::Command;
|
||||
use std::collections::HashMap;
|
||||
use std::env;
|
||||
use regex::Regex;
|
||||
use std::fs;
|
||||
|
||||
struct PythonVersion {
|
||||
major: u8,
|
||||
minor: u8
|
||||
}
|
||||
|
||||
const CFG_KEY: &'static str = "py_sys_config";
|
||||
|
||||
// A list of python interpreter compile-time preprocessor defines that
|
||||
// we will pick up and pass to rustc via --cfg=py_sys_config={varname};
|
||||
// this allows using them conditional cfg attributes in the .rs files, so
|
||||
//
|
||||
// #[cfg(py_sys_config="{varname}"]
|
||||
//
|
||||
// is the equivalent of #ifdef {varname} name in C.
|
||||
//
|
||||
// see Misc/SpecialBuilds.txt in the python source for what these mean.
|
||||
//
|
||||
// (hrm, this is sort of re-implementing what distutils does, except
|
||||
// by passing command line args instead of referring to a python.h)
|
||||
static SYSCONFIG_FLAGS: [&'static str; 7] = [
|
||||
"Py_USING_UNICODE",
|
||||
"Py_UNICODE_WIDE",
|
||||
"WITH_THREAD",
|
||||
"Py_DEBUG",
|
||||
"Py_REF_DEBUG",
|
||||
"Py_TRACE_REFS",
|
||||
"COUNT_ALLOCS",
|
||||
];
|
||||
|
||||
static SYSCONFIG_VALUES: [&'static str; 1] = [
|
||||
// cfg doesn't support flags with values, just bools - so flags
|
||||
// below are translated into bools as {varname}_{val}
|
||||
//
|
||||
// for example, Py_UNICODE_SIZE_2 or Py_UNICODE_SIZE_4
|
||||
"Py_UNICODE_SIZE" // note - not present on python 3.3+, which is always wide
|
||||
];
|
||||
|
||||
/// Examine python's compile flags to pass to cfg by launching
|
||||
/// the interpreter and printing variables of interest from
|
||||
/// sysconfig.get_config_vars.
|
||||
fn get_config_vars(python_path: &String) -> Result<HashMap<String, String>, String> {
|
||||
let mut script = "import sysconfig; \
|
||||
config = sysconfig.get_config_vars();".to_owned();
|
||||
|
||||
for k in SYSCONFIG_FLAGS.iter().chain(SYSCONFIG_VALUES.iter()) {
|
||||
script.push_str(&format!("print(config.get('{}', {}))", k,
|
||||
if is_value(k) { "None" } else { "0" } ));
|
||||
script.push_str(";");
|
||||
}
|
||||
|
||||
let mut cmd = Command::new(python_path);
|
||||
cmd.arg("-c").arg(script);
|
||||
|
||||
let out = try!(cmd.output().map_err(|e| {
|
||||
format!("failed to run python interpreter `{:?}`: {}", cmd, e)
|
||||
}));
|
||||
|
||||
if !out.status.success() {
|
||||
let stderr = String::from_utf8(out.stderr).unwrap();
|
||||
let mut msg = format!("python script failed with stderr:\n\n");
|
||||
msg.push_str(&stderr);
|
||||
return Err(msg);
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8(out.stdout).unwrap();
|
||||
let split_stdout: Vec<&str> = stdout.trim_right().split('\n').collect();
|
||||
if split_stdout.len() != SYSCONFIG_VALUES.len() + SYSCONFIG_FLAGS.len() {
|
||||
return Err(
|
||||
format!("python stdout len didn't return expected number of lines:
|
||||
{}", split_stdout.len()).to_string());
|
||||
}
|
||||
let all_vars = SYSCONFIG_FLAGS.iter().chain(SYSCONFIG_VALUES.iter());
|
||||
// let var_map: HashMap<String, String> = HashMap::new();
|
||||
Ok(all_vars.zip(split_stdout.iter())
|
||||
.fold(HashMap::new(), |mut memo: HashMap<String, String>, (&k, &v)| {
|
||||
if !(v.to_owned() == "None" && is_value(k)) {
|
||||
memo.insert(k.to_owned(), v.to_owned());
|
||||
}
|
||||
memo
|
||||
}))
|
||||
}
|
||||
|
||||
fn is_value(key: &str) -> bool {
|
||||
SYSCONFIG_VALUES.iter().find(|x| **x == key).is_some()
|
||||
}
|
||||
|
||||
fn cfg_line_for_var(key: &str, val: &str) -> Option<String> {
|
||||
if is_value(key) {
|
||||
// is a value; suffix the key name with the value
|
||||
Some(format!("cargo:rustc-cfg={}=\"{}_{}\"\n", CFG_KEY, key, val))
|
||||
} else if val != "0" {
|
||||
// is a flag that isn't zero
|
||||
Some(format!("cargo:rustc-cfg={}=\"{}\"", CFG_KEY, key))
|
||||
} else {
|
||||
// is a flag that is zero
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a python script using the 'python' located by PATH.
|
||||
fn run_python_script(script: &str) -> Result<String, String> {
|
||||
let mut cmd = Command::new("python");
|
||||
cmd.arg("-c").arg(script);
|
||||
|
||||
let out = try!(cmd.output().map_err(|e| {
|
||||
format!("failed to run python interpreter `{:?}`: {}", cmd, e)
|
||||
}));
|
||||
|
||||
if !out.status.success() {
|
||||
let stderr = String::from_utf8(out.stderr).unwrap();
|
||||
let mut msg = format!("python script failed with stderr:\n\n");
|
||||
msg.push_str(&stderr);
|
||||
return Err(msg);
|
||||
}
|
||||
|
||||
let out = String::from_utf8(out.stdout).unwrap();
|
||||
return Ok(out);
|
||||
}
|
||||
|
||||
#[cfg(not(target_os="macos"))]
|
||||
fn get_rustc_link_lib(version: &PythonVersion, enable_shared: bool) -> Result<String, String> {
|
||||
if enable_shared {
|
||||
Ok(format!("cargo:rustc-link-lib=python{}.{}", version.major,
|
||||
version.minor))
|
||||
} else {
|
||||
Ok(format!("cargo:rustc-link-lib=static=python{}.{}", version.major,
|
||||
version.minor))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os="macos")]
|
||||
fn get_macos_linkmodel() -> Result<String, String> {
|
||||
let script = "import MacOS; print MacOS.linkmodel;";
|
||||
let out = run_python_script(script).unwrap();
|
||||
Ok(out.trim_right().to_owned())
|
||||
}
|
||||
|
||||
#[cfg(target_os="macos")]
|
||||
fn get_rustc_link_lib(version: &PythonVersion, _: bool) -> Result<String, String> {
|
||||
// os x can be linked to a framework or static or dynamic, and
|
||||
// Py_ENABLE_SHARED is wrong; framework means shared library
|
||||
let dotted_version = format!("{}.{}", version.major, version.minor);
|
||||
match get_macos_linkmodel().unwrap().as_ref() {
|
||||
"static" => Ok(format!("cargo:rustc-link-lib=static=python{}",
|
||||
dotted_version)),
|
||||
"dynamic" => Ok(format!("cargo:rustc-link-lib=python{}",
|
||||
dotted_version)),
|
||||
"framework" => Ok(format!("cargo:rustc-link-lib=python{}",
|
||||
dotted_version)),
|
||||
other => Err(format!("unknown linkmodel {}", other))
|
||||
}
|
||||
}
|
||||
|
||||
/// Deduce configuration from the 'python' in the current PATH and print
|
||||
/// cargo vars to stdout.
|
||||
///
|
||||
/// Note that if that python isn't version 2.7, this will error.
|
||||
fn configure_from_path(expected_version: &PythonVersion) -> Result<String, String> {
|
||||
let script = "import sys; import sysconfig; print(sys.version_info[0:2]); \
|
||||
print(sysconfig.get_config_var('LIBDIR')); \
|
||||
print(sysconfig.get_config_var('Py_ENABLE_SHARED')); \
|
||||
print(sys.exec_prefix);";
|
||||
let out = run_python_script(script).unwrap();
|
||||
let lines: Vec<&str> = out.split("\n").collect();
|
||||
let version: &str = lines[0];
|
||||
let libpath: &str = lines[1];
|
||||
let enable_shared: &str = lines[2];
|
||||
|
||||
let exec_prefix: &str = lines[3];
|
||||
|
||||
if version != format!("({}, {})",
|
||||
expected_version.major,
|
||||
expected_version.minor)
|
||||
{
|
||||
return Err(format!("'python' is not version {}.{} (is {})",
|
||||
expected_version.major, expected_version.minor, version));
|
||||
}
|
||||
|
||||
println!("{}", get_rustc_link_lib(expected_version,
|
||||
enable_shared == "1").unwrap());
|
||||
println!("cargo:rustc-link-search=native={}", libpath);
|
||||
return Ok(format!("{}/bin/python", exec_prefix));
|
||||
}
|
||||
|
||||
/// Deduce configuration from the python-X.X in pkg-config and print
|
||||
/// cargo vars to stdout.
|
||||
fn configure_from_pkgconfig(version: &PythonVersion, pkg_name: &str)
|
||||
-> Result<String, String> {
|
||||
// this emits relevant build info to stdout, which is picked up by the
|
||||
// build chain (funny name for something with side-effects!)
|
||||
try!(pkg_config::find_library(pkg_name));
|
||||
|
||||
// This seems to be a convention - unfortunately pkg-config doesn't
|
||||
// tell you the executable name, but I've noticed at least on
|
||||
// OS X homebrew the python bin dir for 3.4 doesn't actually contain
|
||||
// a 'python'.
|
||||
let exec_prefix = pkg_config::Config::get_variable(pkg_name,
|
||||
"exec_prefix").unwrap();
|
||||
|
||||
// try to find the python interpreter in the exec_prefix somewhere.
|
||||
// the .pc doesn't tell us :(
|
||||
let attempts = [
|
||||
format!("/bin/python{}_{}", version.major, version.minor),
|
||||
format!("/bin/python{}", version.major),
|
||||
"/bin/python".to_owned()
|
||||
];
|
||||
|
||||
for attempt in attempts.iter() {
|
||||
let possible_exec_name = format!("{}{}", exec_prefix,
|
||||
attempt);
|
||||
match fs::metadata(&possible_exec_name) {
|
||||
Ok(_) => return Ok(possible_exec_name),
|
||||
Err(_) => ()
|
||||
};
|
||||
}
|
||||
return Err("Unable to locate python interpreter".to_owned());
|
||||
}
|
||||
|
||||
/// Determine the python version we're supposed to be building
|
||||
/// from the features passed via the environment.
|
||||
fn version_from_env() -> Result<PythonVersion, String> {
|
||||
let re = Regex::new(r"CARGO_FEATURE_PYTHON_(\d+)_(\d+)").unwrap();
|
||||
for (key, _) in env::vars() {
|
||||
match re.captures(&key) {
|
||||
Some(cap) => return Ok(PythonVersion {
|
||||
major: cap.at(1).unwrap().parse().unwrap(),
|
||||
minor: cap.at(2).unwrap().parse().unwrap()
|
||||
}),
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
Err("Python version feature was not found. At least one python version \
|
||||
feature must be enabled.".to_owned())
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// 1. Setup cfg variables so we can do conditional compilation in this
|
||||
// library based on the python interpeter's compilation flags. This is
|
||||
// necessary for e.g. matching the right unicode and threading interfaces.
|
||||
//
|
||||
// By default, try to use pkgconfig - this seems to be a rust norm.
|
||||
//
|
||||
// If you want to use a different python, setting the appropriate
|
||||
// PYTHON_X.X_NO_PKG_CONFIG environment variable will cause the script
|
||||
// to pick up the python in your PATH; e.g. for python27 X.X is 2.7.
|
||||
//
|
||||
// This will work smoothly with an activated virtualenv.
|
||||
//
|
||||
// If you have troubles with your shell accepting '.' in a var name,
|
||||
// try using 'env' (sorry but this isn't our fault - it just has to
|
||||
// match the pkg-config package name, which is going to have a . in it).
|
||||
let version = version_from_env().unwrap();
|
||||
let pkg_name = format!("python-{}.{}", version.major, version.minor);
|
||||
let python_interpreter_path = match configure_from_pkgconfig(&version, &pkg_name) {
|
||||
Ok(p) => p,
|
||||
// no pkgconfig - either it failed or user set the environment
|
||||
// variable "PYTHON_2.7_NO_PKG_CONFIG".
|
||||
Err(_) => configure_from_path(&version).unwrap()
|
||||
};
|
||||
|
||||
let config_map = get_config_vars(&python_interpreter_path).unwrap();
|
||||
for (key, val) in &config_map {
|
||||
match cfg_line_for_var(key, val) {
|
||||
Some(line) => println!("{}", line),
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Export python interpreter compilation flags as cargo variables that
|
||||
// will be visible to dependents. All flags will be available to dependent
|
||||
// build scripts in the environment variable DEP_PYTHON27_PYTHON_FLAGS as
|
||||
// comma separated list; each item in the list looks like
|
||||
//
|
||||
// {VAL,FLAG}_{flag_name}=val;
|
||||
//
|
||||
// FLAG indicates the variable is always 0 or 1
|
||||
// VAL indicates it can take on any value
|
||||
//
|
||||
// rust-cypthon/build.rs contains an example of how to unpack this data
|
||||
// into cfg flags that replicate the ones present in this library, so
|
||||
// you can use the same cfg syntax.
|
||||
let flags: String = config_map.iter().fold("".to_owned(), |memo, (key, val)| {
|
||||
if is_value(key) {
|
||||
memo + format!("VAL_{}={},", key, val).as_ref()
|
||||
} else if val != "0" {
|
||||
memo + format!("FLAG_{}={},", key, val).as_ref()
|
||||
} else {
|
||||
memo
|
||||
}
|
||||
});
|
||||
println!("cargo:python_flags={}", &flags[..flags.len()-1]);
|
||||
}
|
||||
|
|
|
@ -73,7 +73,13 @@
|
|||
//! ```
|
||||
|
||||
extern crate libc;
|
||||
|
||||
#[cfg(feature="python27-sys")]
|
||||
extern crate python27_sys as ffi;
|
||||
|
||||
#[cfg(feature="python3-sys")]
|
||||
extern crate python3_sys as ffi;
|
||||
|
||||
pub use ffi::Py_ssize_t;
|
||||
pub use err::{PyErr, PyResult};
|
||||
pub use objects::*;
|
||||
|
|
Loading…
Reference in New Issue