-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathbuild.rs
More file actions
79 lines (66 loc) · 2.4 KB
/
Copy pathbuild.rs
File metadata and controls
79 lines (66 loc) · 2.4 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
67
68
69
70
71
72
73
74
75
76
77
78
79
use std::{
fs,
io::Write,
path::{Path, PathBuf},
};
use flate2::{Compression, write::GzEncoder};
const BUNDLE_MAGIC: &[u8] = b"KFVIEW\x01";
fn main() {
let viewer_dir = Path::new("docs/viewer");
println!("cargo:rerun-if-changed={}", viewer_dir.display());
emit_rerun_for_tree(viewer_dir);
let output = PathBuf::from(std::env::var_os("OUT_DIR").expect("OUT_DIR must be set"))
.join("viewer-assets.gz");
write_viewer_bundle(viewer_dir, &output)
.expect("failed to create embedded viewer asset bundle");
}
fn emit_rerun_for_tree(path: &Path) {
let Ok(entries) = fs::read_dir(path) else {
return;
};
for entry in entries.flatten() {
let p = entry.path();
if p.is_dir() {
emit_rerun_for_tree(&p);
continue;
}
println!("cargo:rerun-if-changed={}", p.display());
}
}
fn write_viewer_bundle(viewer_dir: &Path, output: &Path) -> std::io::Result<()> {
let mut files = Vec::new();
collect_files(viewer_dir, &mut files)?;
files.sort();
let mut encoder = GzEncoder::new(fs::File::create(output)?, Compression::best());
encoder.write_all(BUNDLE_MAGIC)?;
for path in files {
let relative = path
.strip_prefix(viewer_dir)
.expect("viewer asset path must be under viewer directory");
// Bundle paths are used as URL paths by the viewer, which always uses
// forward slashes regardless of the platform that built the binary.
let name = relative.to_str().expect("viewer asset paths must be UTF-8").replace('\\', "/");
let contents = fs::read(&path)?;
let name_len = u32::try_from(name.len()).expect("viewer asset path exceeds bundle limit");
let contents_len =
u64::try_from(contents.len()).expect("viewer asset file exceeds bundle limit");
encoder.write_all(&name_len.to_le_bytes())?;
encoder.write_all(&contents_len.to_le_bytes())?;
encoder.write_all(name.as_bytes())?;
encoder.write_all(&contents)?;
}
encoder.write_all(&0_u32.to_le_bytes())?;
encoder.finish()?;
Ok(())
}
fn collect_files(path: &Path, files: &mut Vec<PathBuf>) -> std::io::Result<()> {
for entry in fs::read_dir(path)? {
let path = entry?.path();
if path.is_dir() {
collect_files(&path, files)?;
} else {
files.push(path);
}
}
Ok(())
}