-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.rs
More file actions
66 lines (53 loc) · 2.04 KB
/
Copy pathbuild.rs
File metadata and controls
66 lines (53 loc) · 2.04 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
55
56
57
58
59
60
61
62
63
64
65
66
use std::collections::HashMap;
use std::env;
use std::error::Error;
use std::fs;
use std::path::Path;
type BuildResult = Result<(), Box<dyn Error>>;
fn main() -> BuildResult {
println!("cargo:rerun-if-changed=manifest.template.yml");
println!("cargo:rerun-if-changed=Cargo.toml");
let vars = build_template_vars()?;
generate_manifest(&vars)?;
Ok(())
}
fn build_template_vars() -> Result<HashMap<&'static str, String>, Box<dyn Error>> {
let version = env::var("CARGO_PKG_VERSION")?;
let binary = env::var("CARGO_BIN_NAME")
.or_else(|_| env::var("CARGO_PKG_NAME"))
.map_err(|_| "Failed to read binary name from CARGO_BIN_NAME or CARGO_PKG_NAME")?;
// Add .exe extension on Windows.
let binary = if env::var("CARGO_CFG_TARGET_OS").is_ok_and(|os| os == "windows") {
format!("{binary}.exe")
} else {
binary
};
let repo_url = env::var("CARGO_PKG_REPOSITORY")?;
let github_path = repo_url
.strip_prefix("https://github.com/")
.ok_or("Repository URL must start with 'https://github.com/'")?;
let (owner, name) = github_path
.split_once('/')
.ok_or("Repository URL must be in format 'owner/name'")?;
Ok(HashMap::from([
("VERSION", version),
("BINARY", binary),
("GITHUB_REPOSITORY_OWNER", owner.to_string()),
("GITHUB_REPOSITORY_NAME", name.to_string()),
]))
}
fn generate_manifest(vars: &HashMap<&str, String>) -> BuildResult {
let template_path = Path::new("manifest.template.yml");
let output_path = Path::new("manifest.yml");
let template_content = fs::read_to_string(template_path)?;
// Anchored `${VAR}` substitution avoids `$VERSION` matching inside
// `$VERSION_OLD` if the template gains overlapping variable names.
let result = vars.iter().fold(template_content, |content, (var, value)| {
content.replace(&format!("${{{var}}}"), value)
});
fs::write(output_path, result)?;
for (var, value) in vars {
println!("cargo:warning=Using {var}={value}");
}
Ok(())
}