vertigo_cli/build/
build_run.rs

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