-
Notifications
You must be signed in to change notification settings - Fork 24
/
build.rs
74 lines (61 loc) · 2.33 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
use std::collections::hash_map::DefaultHasher;
use std::fs::File;
use std::hash::Hasher;
use std::io::{BufReader, Read, Write};
use std::path::{Path, PathBuf};
use walkdir::WalkDir;
fn main() {
write_version_to_lua();
embed_lua_file_hashes();
}
/// Write the current version into `lua/DCS-gRPC/version.lua` to be picked up by the Lua side of the
/// server.
fn write_version_to_lua() {
println!("cargo:rerun-if-env-changed=CARGO_PKG_VERSION");
let path = PathBuf::from("./lua/DCS-gRPC/version.lua");
let mut out = File::create(path).unwrap();
writeln!(out, r#"-- this file is auto-generated on `cargo build`"#).unwrap();
writeln!(out, r#"GRPC.version = "{}""#, env!("CARGO_PKG_VERSION")).unwrap();
}
/// Embed the hash of each Lua file into the binary to allow a runtime integrity check.
fn embed_lua_file_hashes() {
println!("cargo:rerun-if-changed=lua/DCS-gRPC");
println!("cargo:rerun-if-changed=lua/Hooks");
let path = PathBuf::from(std::env::var("OUT_DIR").unwrap()).join("lua_files.rs");
let mut out = File::create(path).unwrap();
for (ident, base_path) in [("DCS_GRPC", "./lua/DCS-gRPC"), ("HOOKS", "./lua/Hooks")] {
writeln!(out, "#[allow(clippy::needless_raw_string_hashes)]").unwrap();
writeln!(out, "const {ident}: &[(&str, u64)] = &[").unwrap();
for entry in WalkDir::new(base_path) {
let entry = entry.unwrap();
if !entry.metadata().unwrap().is_file() {
continue;
}
let path = entry
.path()
.strip_prefix(base_path)
.unwrap()
.to_str()
.expect("non-utf8 path");
let hash = file_hash(entry.path());
writeln!(out, r##" (r#"{path}"#, {hash}),"##).unwrap();
eprintln!("{}", entry.path().display());
}
writeln!(out, "];").unwrap();
}
}
fn file_hash(path: &Path) -> u64 {
// Not a cryptographic hasher, but good enough for our use-case.
let mut hasher = DefaultHasher::new();
let mut buffer = [0; 1024];
let file = File::open(path).unwrap();
let mut reader = BufReader::new(file);
loop {
let count = reader.read(&mut buffer).unwrap();
if count == 0 {
break;
}
hasher.write(&buffer[..count]);
}
hasher.finish()
}