ifc_build_cache/
ifc-build-cache.rs1use std::fs::File;
13use std::path::PathBuf;
14use std::process::ExitCode;
15
16use ifc_lite_cache::{build_cache_to_path, CacheOptions, CacheStats, FORMAT_VERSION};
17
18const USAGE: &str = "\
19usage: ifc-build-cache [options] <input.ifc> <output.ifclite>
20
21Builds the @ifc-lite/cache binary cache (format v{VERSION}) of an IFC STEP
22file. The output is written to a temporary file beside it and renamed into
23place, so it is either complete or untouched.
24
25options:
26 --no-geometry write the data sections only (includeGeometry: false)
27 --omit-source-hash store a zero source hash and flag it unset
28 (omitSourceHash: true)
29 --no-compress store every geometry chunk raw
30 (compressGeometryChunks: false)
31 -V, --version print the crate and cache format versions
32 -h, --help print this help";
33
34enum Command {
35 Build(Args),
36 Help,
37 Version,
38}
39
40struct Args {
41 input: PathBuf,
42 output: PathBuf,
43 options: CacheOptions,
44}
45
46fn parse(args: impl Iterator<Item = String>) -> Result<Command, String> {
47 let mut options = CacheOptions::default();
48 let mut paths = Vec::new();
49 for arg in args {
50 match arg.as_str() {
51 "-h" | "--help" => return Ok(Command::Help),
52 "-V" | "--version" => return Ok(Command::Version),
53 "--no-geometry" => options.include_geometry = false,
54 "--omit-source-hash" => options.omit_source_hash = true,
55 "--no-compress" => options.compress_geometry_chunks = false,
56 flag if flag.starts_with('-') && flag != "-" => return Err(format!("unknown option {flag}")),
57 path => paths.push(PathBuf::from(path)),
58 }
59 }
60 match <[PathBuf; 2]>::try_from(paths) {
61 Ok([input, output]) => Ok(Command::Build(Args { input, output, options })),
62 Err(paths) => Err(format!("expected an input and an output path, got {}", paths.len())),
63 }
64}
65
66fn json(stats: &CacheStats) -> String {
67 format!(
68 concat!(
69 r#"{{"formatVersion":{},"entityCount":{},"entityRows":{},"meshCount":{},"skippedMeshes":{},"#,
70 r#""chunkCount":{},"totalVertices":{},"totalTriangles":{},"cacheBytes":{},"#,
71 r#""chunkCells":{},"peakOpenChunkBytes":{}}}"#
72 ),
73 FORMAT_VERSION,
74 stats.entity_count,
75 stats.entity_rows,
76 stats.mesh_count,
77 stats.skipped_meshes,
78 stats.chunk_count,
79 stats.total_vertices,
80 stats.total_triangles,
81 stats.cache_bytes,
82 stats.chunk_cells,
83 stats.peak_open_chunk_bytes,
84 )
85}
86
87fn run(args: Args) -> Result<CacheStats, String> {
88 let input = args.input.display();
89 let file = File::open(&args.input).map_err(|error| format!("open {input}: {error}"))?;
90 let length = file.metadata().map_err(|error| format!("stat {input}: {error}"))?.len();
91 let map = if length == 0 {
96 None
97 } else {
98 Some(unsafe { memmap2::Mmap::map(&file) }.map_err(|error| format!("map {input}: {error}"))?)
102 };
103 let source: &[u8] = map.as_deref().unwrap_or(&[]);
104 build_cache_to_path(source, &args.output, args.options).map_err(|error| error.to_string())
105}
106
107fn main() -> ExitCode {
108 let usage = USAGE.replace("{VERSION}", &FORMAT_VERSION.to_string());
109 match parse(std::env::args().skip(1)) {
110 Ok(Command::Help) => {
111 println!("{usage}");
112 ExitCode::SUCCESS
113 }
114 Ok(Command::Version) => {
115 println!("ifc-build-cache {} (format v{FORMAT_VERSION})", env!("CARGO_PKG_VERSION"));
116 ExitCode::SUCCESS
117 }
118 Err(message) => {
119 eprintln!("ifc-build-cache: {message}\n\n{usage}");
120 ExitCode::from(2)
121 }
122 Ok(Command::Build(args)) => match run(args) {
123 Ok(stats) => {
124 println!("{}", json(&stats));
125 ExitCode::SUCCESS
126 }
127 Err(message) => {
128 eprintln!("ifc-build-cache: {message}");
129 ExitCode::FAILURE
130 }
131 },
132 }
133}