ifc_build_cache/
ifc-build-cache.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! `ifc-build-cache`: build the browser-readable `.ifclite` cache of one IFC
6//! file natively (#9584). A thin CLI over
7//! [`ifc_lite_cache::build_cache_to_path`]: the output streams to disk, is
8//! byte-identical to the in-memory writer's, and appears atomically.
9//!
10//! Prints the build's stats as one JSON object on stdout.
11
12use 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    // Mapped, not read: the source pages are file-backed and reclaimable
92    // instead of a heap copy. That bounds nothing by itself; what bounds the
93    // geometry the writer holds is the open-chunk set (see `CacheStats`).
94    // An empty file cannot be mapped on every platform, and needs no map.
95    let map = if length == 0 {
96        None
97    } else {
98        // SAFETY: the map is read-only and lives until the build returns. A
99        // concurrent truncation of the input by another process could fault
100        // the read; the same holds for any reader of a file being rewritten.
101        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}