Skip to main content

vertigo_cli/build/
build_run.rs

1use std::{
2    path::{Path, PathBuf},
3    time::Instant,
4};
5
6use crate::{
7    commons::{ErrorCode, models::IndexModel},
8    serve::save_precompressed,
9};
10
11use super::{
12    build_opts::BuildOpts,
13    cargo_build::run_cargo_build,
14    cargo_workspace::{Workspace, get_workspace},
15    check_env::check_env,
16    find_target::find_wasm_in_target,
17    wasm_opt::run_wasm_opt,
18    wasm_path::WasmPath,
19};
20
21pub fn run(opts: BuildOpts) -> Result<(), ErrorCode> {
22    let ws = match get_workspace() {
23        Ok(ws) => ws,
24        Err(err) => {
25            log::error!("Can't read workspace");
26            return Err(err);
27        }
28    };
29
30    run_with_ws(opts, &ws, false)
31}
32
33pub fn run_with_ws(opts: BuildOpts, ws: &Workspace, allow_error: bool) -> Result<(), ErrorCode> {
34    let package_name = match opts.inner.package_name.as_deref() {
35        Some(name) => name.to_string(),
36        None => match ws.infer_package_name() {
37            Some(name) => {
38                log::info!("Inferred package name = {name}");
39                name
40            }
41            None => {
42                log::error!(
43                    "Can't find vertigo project in {} (no cdylib member)",
44                    ws.get_root_dir()
45                );
46                return Err(ErrorCode::CantFindCdylibMember);
47            }
48        },
49    };
50
51    check_env()?;
52
53    let release = opts.inner.release_mode.unwrap_or(true);
54    let precompress = opts.inner.precompress.unwrap_or(true);
55
56    let dest_dir = WasmPath::new(PathBuf::from(&opts.common.dest_dir));
57
58    // Clean destination
59
60    dest_dir.remove_dir_all();
61    dest_dir.create_dir_all();
62
63    // Run build (which cleans the package first, to re-generate static files)
64
65    let target_path = match run_cargo_build(
66        &package_name,
67        &opts.get_public_path(),
68        ws,
69        allow_error,
70        release,
71        &opts.inner.cargo_opts,
72    )? {
73        Ok(path) => path,
74        Err(_) => return Err(ErrorCode::BuildFailed),
75    };
76
77    // Get wasm_run.js and index.template.html from vertigo build
78
79    let vertigo_statics_dir = target_path.join("static");
80
81    let mut run_script_content = match std::fs::read(vertigo_statics_dir.join("wasm_run.js")) {
82        Ok(content) => content,
83        Err(err) => {
84            log::error!("Can't read wasm_run from statics directory: {err}");
85            return Err(ErrorCode::CantReadWasmRunFromStatics);
86        }
87    };
88
89    if !opts.inner.wasm_run_source_map {
90        erase_last_two_lines(&mut run_script_content);
91    }
92
93    let run_script_hash_name = opts
94        .new_path_in_static_make(&["wasm_run.js"])
95        .save_with_hash(&run_script_content)?;
96
97    if opts.inner.wasm_run_source_map {
98        let run_script_sourcemap_content =
99            match std::fs::read_to_string(vertigo_statics_dir.join("wasm_run.js.map")) {
100                Ok(content) => {
101                    // Replace original script filename in sourcemap with the hashed one
102                    content.replace("wasm_run.js", &run_script_hash_name)
103                }
104                Err(err) => {
105                    log::error!("Can't read wasm_run sourcemap from statics directory: {err}");
106                    return Err(ErrorCode::CantReadWasmRunFromStatics);
107                }
108            };
109
110        opts.new_path_in_static_make(&["wasm_run.js.map"])
111            .save(&run_script_sourcemap_content.into_bytes())?;
112    }
113
114    // Copy .wasm to destination
115
116    let wasm_path_target = find_wasm_in_target(&target_path, &package_name);
117    let wasm_path = opts.new_path_in_static_from(&wasm_path_target);
118
119    // Optimize .wasm
120
121    let wasm_path_hash =
122        // with the files saved precompressed below, the log tells the size of all of them
123        if opts.inner.wasm_opt.unwrap_or(true)
124            && run_wasm_opt(&wasm_path_target, &wasm_path, !precompress)
125        {
126            // optimized
127            let wasm_path_hash = wasm_path.save_with_hash(wasm_path.read()?.as_slice())?;
128            wasm_path.remove_file()?;
129            wasm_path_hash
130        } else {
131            // copy without optimization
132            let wasm_content = wasm_path_target.read()?;
133            wasm_path.save_with_hash(wasm_content.as_slice())?
134        };
135
136    // Generate index.json in destination
137
138    let index = IndexModel {
139        run_js: opts.public_path_to(run_script_hash_name),
140        wasm: opts.public_path_to(wasm_path_hash),
141    };
142
143    let index_content = serde_json::to_string_pretty(&index).map_err(|err| {
144        log::error!("Can't serialize index.json: {err}");
145        ErrorCode::CantWriteOrRemoveFile
146    })?;
147    opts.new_path_in_static_make(&["index.json"])
148        .save(index_content.as_bytes())?;
149
150    // Copy statics generated by dom macro invocations
151
152    if let Ok(dir) = std::fs::read_dir(vertigo_statics_dir.join("included")) {
153        for entry in dir {
154            match entry {
155                Ok(entry) => {
156                    let src_file_path = WasmPath::new(entry.path());
157                    let content = src_file_path.read()?;
158                    let dest_file_path = opts.new_path_in_static_from(&src_file_path);
159                    dest_file_path.save(&content)?;
160                }
161                Err(err) => {
162                    log::warn!("Can't read entry: {err}");
163                    return Err(ErrorCode::CantReadStaticFile);
164                }
165            }
166        }
167    }
168
169    // Text files compressed next to them, so a server with `--precompress` starts at once
170
171    if precompress {
172        let started = Instant::now();
173        match save_precompressed(Path::new(&opts.common.dest_dir)) {
174            Ok((count, size, compressed_size)) => log::info!(
175                "Saved {count} files precompressed with brotli: {}K -> {}K in {:.1?}",
176                size / 1024,
177                compressed_size / 1024,
178                started.elapsed()
179            ),
180            Err(err) => {
181                log::error!("Can't save the files precompressed: {err}");
182                return Err(ErrorCode::CantWriteOrRemoveFile);
183            }
184        }
185    }
186
187    Ok(())
188}
189
190fn erase_last_two_lines(content: &mut Vec<u8>) {
191    // Find the positions of the last two newline characters
192    let mut last_newline_pos = None;
193    let mut second_last_newline_pos = None;
194
195    for (i, &byte) in content.iter().enumerate() {
196        if byte == b'\n' {
197            second_last_newline_pos = last_newline_pos; // Update second last
198            last_newline_pos = Some(i); // Update last
199        }
200    }
201
202    // Truncate the Vec<u8> to the position of the second last newline
203    if let Some(second_last) = second_last_newline_pos {
204        content.truncate(second_last);
205    }
206}