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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
use crate::cmd::{cfg_spinner, run_stage};
use crate::errors::*;
use crate::parse::BuildOpts;
use crate::thread::{spawn_thread, ThreadHandle};
use console::{style, Emoji};
use indicatif::{MultiProgress, ProgressBar};
use std::env;
use std::path::PathBuf;

// Emojis for stages
static GENERATING: Emoji<'_, '_> = Emoji("🔨", "");
static BUILDING: Emoji<'_, '_> = Emoji("🏗️ ", ""); // Yes, there's a space here, for some reason it's needed...

/// Returns the exit code if it's non-zero.
macro_rules! handle_exit_code {
    ($code:expr) => {
        let (_, _, code) = $code;
        if code != 0 {
            return ::std::result::Result::Ok(code);
        }
    };
}

// /// Finalizes the build by renaming some directories.
// pub fn finalize(target: &Path) -> Result<(), ExecutionError> {
//     // Move the `pkg/` directory into `dist/pkg/`
//     let pkg_dir = target.join("dist/pkg");
//     if pkg_dir.exists() {
//         if let Err(err) = fs::remove_dir_all(&pkg_dir) {
//             return Err(ExecutionError::MovePkgDirFailed { source: err });
//         }
//     }
//     // The `fs::rename()` function will fail on Windows if the destination already exists, so this should work (we've just deleted it as per https://github.com/rust-lang/rust/issues/31301#issuecomment-177117325)
//     if let Err(err) = fs::rename(target.join("pkg"), target.join("dist/pkg"))
// {         return Err(ExecutionError::MovePkgDirFailed { source: err });
//     }

//     Ok(())
// }

/// Actually builds the user's code, program arguments having been interpreted.
/// This needs to know how many steps there are in total because the serving
/// logic also uses it. This also takes a `MultiProgress` to interact with so it
/// can be used truly atomically. This returns handles for waiting on the
/// component threads so we can use it composably.
#[allow(clippy::type_complexity)]
pub fn build_internal(
    dir: PathBuf,
    spinners: &MultiProgress,
    num_steps: u8,
    is_release: bool,
) -> Result<
    (
        ThreadHandle<impl FnOnce() -> Result<i32, ExecutionError>, Result<i32, ExecutionError>>,
        ThreadHandle<impl FnOnce() -> Result<i32, ExecutionError>, Result<i32, ExecutionError>>,
    ),
    ExecutionError,
> {
    // Static generation message
    let sg_msg = format!(
        "{} {} Generating your app",
        style(format!("[1/{}]", num_steps)).bold().dim(),
        GENERATING
    );
    // Wasm building message
    let wb_msg = format!(
        "{} {} Building your app to Wasm",
        style(format!("[2/{}]", num_steps)).bold().dim(),
        BUILDING
    );

    // Prepare the optimization flags for the Wasm build (only used in release mode)
    let wasm_opt_flags = if is_release {
        env::var("PERSEUS_WASM_RELEASE_RUSTFLAGS")
            .unwrap_or_else(|_| "-C opt-level=z -C codegen-units=1".to_string())
    } else {
        String::new()
    };

    // We parallelize the first two spinners (static generation and Wasm building)
    // We make sure to add them at the top (the server spinner may have already been
    // instantiated)
    let sg_spinner = spinners.insert(0, ProgressBar::new_spinner());
    let sg_spinner = cfg_spinner(sg_spinner, &sg_msg);
    let sg_dir = dir.clone();
    let wb_spinner = spinners.insert(1, ProgressBar::new_spinner());
    let wb_spinner = cfg_spinner(wb_spinner, &wb_msg);
    let wb_dir = dir;
    let sg_thread = spawn_thread(move || {
        handle_exit_code!(run_stage(
            vec![&format!(
                "{} run {} {}",
                env::var("PERSEUS_CARGO_PATH").unwrap_or_else(|_| "cargo".to_string()),
                if is_release { "--release" } else { "" },
                env::var("PERSEUS_CARGO_ARGS").unwrap_or_else(|_| String::new())
            )],
            &sg_dir,
            &sg_spinner,
            &sg_msg,
            vec![
                ("PERSEUS_ENGINE_OPERATION", "build"),
                ("CARGO_TARGET_DIR", "target_engine")
            ]
        )?);

        Ok(0)
    });
    let wb_thread = spawn_thread(move || {
        handle_exit_code!(run_stage(
            vec![&format!(
                "{} build --out-dir dist/pkg --out-name perseus_engine --target web {} {}",
                env::var("PERSEUS_WASM_PACK_PATH").unwrap_or_else(|_| "wasm-pack".to_string()),
                if is_release { "--release" } else { "--dev" }, /* If we don't supply `--dev`, another profile will be used */
                env::var("PERSEUS_WASM_PACK_ARGS").unwrap_or_else(|_| String::new())
            )],
            &wb_dir,
            &wb_spinner,
            &wb_msg,
            if is_release {
                vec![
                    ("CARGO_TARGET_DIR", "target_wasm"),
                    ("RUSTFLAGS", &wasm_opt_flags),
                ]
            } else {
                vec![("CARGO_TARGET_DIR", "target_wasm")]
            }
        )?);

        Ok(0)
    });

    Ok((sg_thread, wb_thread))
}

/// Builds the subcrates to get a directory that we can serve. Returns an exit
/// code.
pub fn build(dir: PathBuf, opts: BuildOpts) -> Result<i32, ExecutionError> {
    let spinners = MultiProgress::new();

    let (sg_thread, wb_thread) = build_internal(dir, &spinners, 2, opts.release)?;
    let sg_res = sg_thread
        .join()
        .map_err(|_| ExecutionError::ThreadWaitFailed)??;
    if sg_res != 0 {
        return Ok(sg_res);
    }
    let wb_res = wb_thread
        .join()
        .map_err(|_| ExecutionError::ThreadWaitFailed)??;
    if wb_res != 0 {
        return Ok(wb_res);
    }

    // This waits for all the threads and lets the spinners draw to the terminal
    // spinners.join().map_err(|_| ErrorKind::ThreadWaitFailed)?;
    // And now we can run the finalization stage
    // finalize(&dir)?;

    // We've handled errors in the component threads, so the exit code is now zero
    Ok(0)
}