servo/components/script/build.rs
Jonathan Schwender 637770600f
libservo: Improve finding python (#33385)
* libservo: Improve finding python

Servo is built in a virtual environment, which sets `VIRTUAL_ENV` to
the base path of the venv.
PYTHON3 is only set if mach or the user set it.

Additional changes:

- Use Path / var_os for Paths instead of strings.
 In General using Path APIs is preferable, since in rare cases
 valid paths may not be valid utf-8.
- Don't search for python 3.8 anymore, since
  we require a newer version anyway.
- Don't add the .exe suffix anymore, since
  Command::new() will take care of that.

Signed-off-by: Jonathan Schwender <schwenderjonathan@gmail.com>
Signed-off-by: Jonathan Schwender <jonathan.schwender@huawei.com>

* script: Improve finding python

Synchronize `find_python` in scripts build.rs with the version in
libservo.

Signed-off-by: Jonathan Schwender <jonathan.schwender@huawei.com>

* Apply suggestions from code review

Co-authored-by: Martin Robinson <mrobinson@igalia.com>
Signed-off-by: Jonathan Schwender <55576758+jschwe@users.noreply.github.com>
Signed-off-by: Jonathan Schwender <jonathan.schwender@huawei.com>

* Fix finding venv python on windows

- On Windows the venv scripts and python binaries are in the
  `Scripts` subdirectory instead of `bin`.
- We shouldn't check if the executable in the venv binary dir
  exists, since the actual file could have a `.exe` suffix.
  We don't need to consider the `.exe` suffix for the filename,
  since `Command` will handle that for us.
  We also anyway check the validity of the candidate file, by
  running `$candidate --version`.

Signed-off-by: Jonathan Schwender <schwenderjonathan@gmail.com>

---------

Signed-off-by: Jonathan Schwender <schwenderjonathan@gmail.com>
Signed-off-by: Jonathan Schwender <jonathan.schwender@huawei.com>
Signed-off-by: Jonathan Schwender <55576758+jschwe@users.noreply.github.com>
Co-authored-by: Martin Robinson <mrobinson@igalia.com>
2024-09-12 02:21:41 +00:00

118 lines
3.8 KiB
Rust

/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use std::process::Command;
use std::time::Instant;
use std::{env, fmt};
use phf_shared::{self, FmtConst};
use serde_json::{self, Value};
fn main() {
let start = Instant::now();
let style_out_dir = PathBuf::from(env::var_os("DEP_SERVO_STYLE_CRATE_OUT_DIR").unwrap());
let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
let status = Command::new(find_python())
.arg("dom/bindings/codegen/run.py")
.arg(style_out_dir.join("css-properties.json"))
.arg(&out_dir)
.status()
.unwrap();
if !status.success() {
std::process::exit(1)
}
println!("Binding generation completed in {:?}", start.elapsed());
let json = out_dir.join("InterfaceObjectMapData.json");
let json: Value = serde_json::from_reader(File::open(json).unwrap()).unwrap();
let mut map = phf_codegen::Map::new();
for (key, value) in json.as_object().unwrap() {
map.entry(Bytes(key), value.as_str().unwrap());
}
let phf = PathBuf::from(env::var_os("OUT_DIR").unwrap()).join("InterfaceObjectMapPhf.rs");
let mut phf = File::create(phf).unwrap();
writeln!(
&mut phf,
"pub static MAP: phf::Map<&'static [u8], fn(JSContext, HandleObject)> = {};",
map.build(),
)
.unwrap();
}
#[derive(Eq, Hash, PartialEq)]
struct Bytes<'a>(&'a str);
impl<'a> FmtConst for Bytes<'a> {
fn fmt_const(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
// https://github.com/rust-lang/rust/issues/55223
// should technically be just `write!(formatter, "b\"{}\"", self.0)
// but the referenced issue breaks promotion in the surrounding code
write!(formatter, "{{ const FOO: &[u8] = b\"{}\"; FOO }}", self.0)
}
}
impl<'a> phf_shared::PhfHash for Bytes<'a> {
fn phf_hash<H: std::hash::Hasher>(&self, hasher: &mut H) {
self.0.as_bytes().phf_hash(hasher)
}
}
/// Tries to find a suitable python
///
/// Algorithm
/// 1. Trying to find python3/python in $VIRTUAL_ENV (this should be from Servo's venv)
/// 2. Checking PYTHON3 (set by mach)
/// 3. Falling back to the system installation.
///
/// Note: This function should be kept in sync with the version in `components/servo/build.rs`
fn find_python() -> PathBuf {
let mut candidates = vec![];
if let Some(venv) = env::var_os("VIRTUAL_ENV") {
let bin_directory = PathBuf::from(venv).join("bin");
let python3 = bin_directory.join("python3");
if python3.exists() {
candidates.push(python3);
}
let python = bin_directory.join("python");
if python.exists() {
candidates.push(python);
}
};
if let Some(python3) = env::var_os("PYTHON3") {
let python3 = PathBuf::from(python3);
if python3.exists() {
candidates.push(python3);
}
}
let system_python = ["python3", "python"].map(PathBuf::from);
candidates.extend_from_slice(&system_python);
for name in &candidates {
// Command::new() allows us to omit the `.exe` suffix on windows
if Command::new(&name)
.arg("--version")
.output()
.is_ok_and(|out| out.status.success())
{
return name.to_owned();
}
}
let candidates = candidates
.into_iter()
.map(|c| c.into_os_string())
.collect::<Vec<_>>();
panic!(
"Can't find python (tried {:?})! Try enabling Servo's Python venv, \
setting the PYTHON3 env var or adding python3 to PATH.",
candidates.join(", ".as_ref())
)
}