build(rust): use $CARGO_PKG_RUST_VERSION when generating bindings (#4512)

Since cargo 1.63, $CARGO_PKG_RUST_VERSION is set in the build
environment to the value of the rust-version Cargo.toml field.

This removes the need to manually invoke cargo from build.rs during a
build of the tree-sitter crate with the bindgen feature enabled.

Removing the cargo invocation also ensures the build doesn't write to
the current directory when the target directory has been redirected
elsewhere. "cargo metadata" will attempt to update Cargo.lock, which
will fail if the source tree is read-only.
This commit is contained in:
James McCoy 2025-06-13 11:11:22 -07:00 committed by GitHub
parent a2c98b4b5f
commit 889015f03b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -56,29 +56,6 @@ fn generate_bindings(out_dir: &std::path::Path) {
use bindgen::RustTarget;
let output = Command::new("cargo")
.args(["metadata", "--format-version", "1"])
.output()
.unwrap();
let metadata = serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();
let Some(rust_version) = metadata
.get("packages")
.and_then(|packages| packages.as_array())
.and_then(|packages| {
packages.iter().find_map(|package| {
if package["name"] == "tree-sitter" {
package.get("rust_version").and_then(|v| v.as_str())
} else {
None
}
})
})
else {
panic!("Failed to find tree-sitter package in cargo metadata");
};
const HEADER_PATH: &str = "include/tree_sitter/api.h";
println!("cargo:rerun-if-changed={HEADER_PATH}");
@ -97,6 +74,8 @@ fn generate_bindings(out_dir: &std::path::Path) {
"TSQueryPredicateStep",
];
let rust_version = env!("CARGO_PKG_RUST_VERSION");
let bindings = bindgen::Builder::default()
.header(HEADER_PATH)
.layout_tests(false)