Repository navigation
Expand file tree
/
Copy pathbuild.rs
More file actions
54 lines (43 loc) · 1.61 KB
/
Copy pathbuild.rs
File metadata and controls
54 lines (43 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
use std::fs;
use std::path::Path;
fn main() {
// `mx4 --version` reports the resolved hidapi version, not merely the semver requirement from
// Cargo.toml. Re-run whenever dependency resolution changes.
println!("cargo:rerun-if-changed=Cargo.lock");
let version =
resolved_dependency_version("Cargo.lock", "hidapi").unwrap_or_else(|| "unknown".to_owned());
println!("cargo:rustc-env=MX4_HIDAPI_VERSION={version}");
}
fn resolved_dependency_version(lockfile: impl AsRef<Path>, package: &str) -> Option<String> {
let lockfile = fs::read_to_string(lockfile).ok()?;
// Cargo.lock is regular TOML, but finding two scalar fields in each package block does not
// justify adding a TOML dependency to the build script.
for section in lockfile.split("\n\n") {
if !section.lines().any(|line| line == "[[package]]") {
continue;
}
let mut name = None;
let mut version = None;
for line in section.lines() {
if let Some(value) = lock_value(line, "name") {
name = Some(value);
} else if let Some(value) = lock_value(line, "version") {
version = Some(value);
}
}
if name == Some(package) {
if let Some(version) = version {
return Some(version.to_owned());
}
return None;
}
}
None
}
fn lock_value<'a>(line: &'a str, key: &str) -> Option<&'a str> {
let (found_key, value) = line.split_once(" = ")?;
if found_key != key {
return None;
}
value.strip_prefix('"')?.strip_suffix('"')
}