-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.rs
91 lines (78 loc) · 2.87 KB
/
build.rs
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
use std::env;
use std::error::Error;
use std::process::Command;
use simple_error::bail;
use vergen::{BuildBuilder, CargoBuilder, Emitter, RustcBuilder, SysinfoBuilder};
fn uncommitted_count() -> Result<usize, Box<dyn Error>> {
let output = exec_git(&["status", "-s"])?;
let lines = output.trim().split('\n');
Ok(lines.filter(|line| !line.trim().is_empty()).count())
}
fn exec_git(args: &[&str]) -> Result<String, Box<dyn Error>> {
let mut cmd = Command::new("git");
let output = cmd.args(args).output()?;
if !output.status.success() {
let cmd = format!("git {}", args.join(" "));
bail!("Execute git command {} failed", cmd);
}
let output = String::from_utf8(output.stdout)?;
Ok(output.trim().to_string())
}
fn fetch_git_info() -> Result<(), Box<dyn Error>> {
let describe = match exec_git(&["describe", "--tags"]) {
Ok(d) => d,
Err(_) => String::from("unknown"),
};
let sha = exec_git(&["rev-parse", "HEAD"])?;
let short_sha = exec_git(&["rev-parse", "--short", "HEAD"])?;
let cargo_version = env!("CARGO_PKG_VERSION");
let stable_tag = format!("v{cargo_version}");
let (mut version, mut build_type) = if stable_tag == describe {
if cargo_version.ends_with("alpha") {
(cargo_version.to_string(), "alpha")
} else if cargo_version.ends_with("beta") {
(cargo_version.to_string(), "beta")
} else if cargo_version.ends_with("rc") {
(cargo_version.to_string(), "pre-release")
} else {
(cargo_version.to_string(), "stable")
}
} else {
(format!("{cargo_version}-dev_{short_sha}"), "dev")
};
let uncommitted_count = uncommitted_count()?;
if uncommitted_count > 0 {
version = format!("{version}-uncommitted");
build_type = "dev-uncommitted";
}
println!("cargo:rustc-env=CSYNC_VERSION={version}");
println!("cargo:rustc-env=CSYNC_BUILD_TYPE={build_type}");
println!("cargo:rustc-env=CSYNC_SHA={sha}");
Ok(())
}
fn main() -> Result<(), Box<dyn Error>> {
let build = BuildBuilder::all_build()?;
let cargo = CargoBuilder::all_cargo()?;
let rustc = RustcBuilder::all_rustc()?;
let si = SysinfoBuilder::all_sysinfo()?;
Emitter::default()
.add_instructions(&build)?
.add_instructions(&cargo)?
.add_instructions(&rustc)?
.add_instructions(&si)?
.emit()?;
println!(
"cargo:rustc-env=CSYNC_TARGET={}",
env::var("TARGET").unwrap()
);
if let Ok(value) = env::var("BUILD_CSYNC_WITH_GIT_INFO") {
if value == "true" {
return fetch_git_info();
}
}
let cargo_version = env!("CARGO_PKG_VERSION");
println!("cargo:rustc-env=CSYNC_VERSION={cargo_version}");
println!("cargo:rustc-env=CSYNC_BUILD_TYPE=stable");
println!("cargo:rustc-env=CSYNC_SHA=<unknown>");
Ok(())
}