Skip to main content

euv_cli/bundle/
fn.rs

1use super::*;
2
3/// Returns the host operating system this build runs on.
4///
5/// # Returns
6///
7/// - `HostOs` - The host operating system.
8pub fn current_host() -> HostOs {
9    match HOST_OS {
10        HOST_MACOS => HostOs::Macos,
11        HOST_LINUX => HostOs::Linux,
12        HOST_WINDOWS => HostOs::Windows,
13        _ => HostOs::Unsupported,
14    }
15}
16
17/// Returns the host architecture this build runs on.
18///
19/// # Returns
20///
21/// - `String` - The host architecture identifier.
22pub fn current_arch() -> String {
23    HOST_ARCH.to_string()
24}
25
26/// Returns every platform the given host can build.
27///
28/// The order is the build order: the desktop clients first, then the
29/// mobile deliverables, so a failure in the desktop client is reported
30/// before the mobile toolchains are entered.
31///
32/// # Arguments
33///
34/// - `HostOs` - The host operating system.
35///
36/// # Returns
37///
38/// - `Vec<NativePlatform>` - The platforms this host builds.
39pub fn host_platforms(host: HostOs) -> Vec<NativePlatform> {
40    match host {
41        HostOs::Macos => vec![
42            NativePlatform::Macos,
43            NativePlatform::Ios,
44            NativePlatform::IosSimulator,
45            NativePlatform::Android,
46        ],
47        HostOs::Linux => vec![NativePlatform::Linux, NativePlatform::Android],
48        HostOs::Windows => vec![NativePlatform::Windows],
49        HostOs::Unsupported => Vec::new(),
50    }
51}
52
53/// Returns the kind of builder a platform needs.
54///
55/// # Arguments
56///
57/// - `NativePlatform` - The platform to classify.
58///
59/// # Returns
60///
61/// - `NativeTask` - The builder the platform needs.
62pub fn native_task(platform: NativePlatform) -> NativeTask {
63    match platform {
64        NativePlatform::Android => NativeTask::Android,
65        _ => NativeTask::Client,
66    }
67}
68
69/// Reports whether a host can build a platform.
70///
71/// # Arguments
72///
73/// - `HostOs` - The host operating system.
74/// - `NativePlatform` - The platform to test.
75///
76/// # Returns
77///
78/// - `bool` - Whether the host can build the platform.
79pub fn host_supports(host: HostOs, platform: NativePlatform) -> bool {
80    match platform {
81        NativePlatform::Android => matches!(host, HostOs::Macos | HostOs::Linux),
82        NativePlatform::Macos | NativePlatform::Ios | NativePlatform::IosSimulator => {
83            matches!(host, HostOs::Macos)
84        }
85        NativePlatform::Linux => matches!(host, HostOs::Linux),
86        NativePlatform::Windows => matches!(host, HostOs::Windows),
87    }
88}
89
90/// Renders a platform list as a comma separated list of names.
91///
92/// # Arguments
93///
94/// - `&[NativePlatform]` - The platforms to render.
95///
96/// # Returns
97///
98/// - `String` - The rendered platform list.
99pub fn describe_platforms(platforms: &[NativePlatform]) -> String {
100    platforms
101        .iter()
102        .map(|platform: &NativePlatform| platform.platform_name())
103        .collect::<Vec<&str>>()
104        .join(", ")
105}
106
107/// Renders the host requirement of every platform in a list.
108///
109/// # Arguments
110///
111/// - `&[NativePlatform]` - The platforms to describe.
112///
113/// # Returns
114///
115/// - `String` - The rendered requirements.
116pub fn describe_requirements(platforms: &[NativePlatform]) -> String {
117    platforms
118        .iter()
119        .map(|platform: &NativePlatform| {
120            format!(
121                "{} needs a {} host",
122                platform.platform_name(),
123                platform.required_host()
124            )
125        })
126        .collect::<Vec<String>>()
127        .join("; ")
128}
129
130/// Resolves the requested platforms from the command line.
131///
132/// `--all` selects every platform the host can build, and `--platforms`
133/// selects an explicit list. The two are mutually exclusive, and neither
134/// means the ordinary web-only build.
135///
136/// # Arguments
137///
138/// - `bool` - Whether `--all` was given.
139/// - `&[NativePlatform]` - The platforms given by `--platforms`.
140///
141/// # Returns
142///
143/// - `Result<Vec<NativePlatform>, EuvError>` - The requested platforms.
144pub fn resolve_requested_platforms(
145    all: bool,
146    platforms: &[NativePlatform],
147) -> Result<Vec<NativePlatform>, EuvError> {
148    if all && !platforms.is_empty() {
149        return Err(EuvError::Message(format!(
150            "{ALL_ARG} and {PLATFORMS_ARG} cannot be combined: {ALL_ARG} selects every \
151             platform this host can build, and {PLATFORMS_ARG} names them explicitly."
152        )));
153    }
154    if all {
155        return Ok(host_platforms(current_host()));
156    }
157    if platforms.is_empty() {
158        return Ok(Vec::new());
159    }
160    let mut unique: Vec<NativePlatform> = Vec::new();
161    for platform in platforms {
162        if !unique.contains(platform) {
163            unique.push(*platform);
164        }
165    }
166    Ok(unique)
167}
168
169/// Resolves the native build plan for the requested platforms.
170///
171/// Every requested platform that this host cannot build is reported as
172/// unsupported, and the plan is only produced when nothing requested is
173/// out of reach: an incompatible request must fail before any build
174/// starts rather than silently skipping a deliverable.
175///
176/// # Arguments
177///
178/// - `&[NativePlatform]` - The requested platforms.
179/// - `HostOs` - The host to resolve against.
180///
181/// # Returns
182///
183/// - `Result<NativePlan, EuvError>` - The resolved plan, or an error naming
184///   every platform that cannot be built here.
185pub fn resolve_native_plan(
186    requested: &[NativePlatform],
187    host: HostOs,
188) -> Result<NativePlan, EuvError> {
189    if host == HostOs::Unsupported || current_arch() == ARCH_UNSUPPORTED {
190        return Err(EuvError::Message(
191            "Native packaging is unsupported on this operating system or architecture".to_string(),
192        ));
193    }
194    let mut unsupported: Vec<NativePlatform> = Vec::new();
195    for platform in requested {
196        if !host_supports(host, *platform) && !unsupported.contains(platform) {
197            unsupported.push(*platform);
198        }
199    }
200    if !unsupported.is_empty() {
201        return Err(EuvError::Message(format!(
202            "{} cannot be built on {}: {}. Build {} on a matching host, or drop it from \
203             {PLATFORMS_ARG}.",
204            describe_platforms(&unsupported),
205            host.host_name(),
206            describe_requirements(&unsupported),
207            describe_platforms(&unsupported),
208        )));
209    }
210    let mut targets: Vec<NativeTarget> = Vec::new();
211    for platform in requested {
212        targets.push(NativeTarget {
213            platform: *platform,
214            task: native_task(*platform),
215        });
216    }
217    Ok(NativePlan {
218        host,
219        arch: current_arch(),
220        targets,
221        unsupported,
222    })
223}
224
225/// Prints the resolved plan for a native build.
226///
227/// The plan names the host, the deliverables that will be built, and the
228/// platforms that were requested but cannot be built here.
229///
230/// # Arguments
231///
232/// - `&NativePlan` - The resolved plan.
233pub fn print_native_plan(plan: &NativePlan) {
234    log::info!("Host: {} ({})", plan.host.host_name(), plan.arch);
235    log::info!(
236        "Native selection is host-specific; other operating systems require matching build hosts."
237    );
238    if plan.targets.is_empty() {
239        log::info!("Native platforms: none");
240    } else {
241        for target in &plan.targets {
242            log::info!(
243                "Native platform: {} ({})",
244                target.platform.platform_name(),
245                target.task.task_name()
246            );
247        }
248    }
249    if !plan.unsupported.is_empty() {
250        log::warn!(
251            "Not buildable on this host: {} ({})",
252            describe_platforms(&plan.unsupported),
253            describe_requirements(&plan.unsupported)
254        );
255    }
256}
257
258/// Resolves the native client project directory.
259///
260/// The directory inside this repository is used unless the caller names
261/// another one, so an external layout can be built without changing the
262/// repository. The directory is checked when the build runs rather than
263/// here, so a plan can be printed for a layout that is not present yet.
264///
265/// # Arguments
266///
267/// - `&Path` - The directory this build runs in.
268/// - `Option<&PathBuf>` - The `--native-path` override, when one was given.
269///
270/// # Returns
271///
272/// - `PathBuf` - The native client project directory.
273pub fn resolve_native_project(base: &Path, native_path: Option<&PathBuf>) -> PathBuf {
274    match native_path {
275        Some(path) if path.is_absolute() => path.clone(),
276        Some(path) => base.join(path),
277        None => base.join(NATIVE_PROJECT_RELATIVE_PATH),
278    }
279}
280
281/// Rejects a native client project directory that is not there.
282///
283/// The check runs when the build starts rather than when the plan is
284/// resolved, so a plan can be printed for a layout that is not present
285/// yet, and so the failure names the directory that is missing.
286///
287/// # Arguments
288///
289/// - `&Path` - The native client project directory.
290///
291/// # Returns
292///
293/// - `Result<(), EuvError>` - `Ok` when the directory exists.
294pub fn require_native_project(native_project: &Path) -> Result<(), EuvError> {
295    if native_project.is_dir() {
296        return Ok(());
297    }
298    Err(EuvError::Message(format!(
299        "The native client project directory '{}' does not exist. Pass {NATIVE_PATH_ARG} to \
300         point at it.",
301        native_project.display()
302    )))
303}
304
305/// Resolves the directory the web build output is published into.
306///
307/// The native builders embed the pages this build produced, so the
308/// directory must be the one the web build actually wrote: the serving
309/// root holds the page, and the wasm artifacts sit beside it.
310///
311/// # Arguments
312///
313/// - `&ModeArgs` - The build arguments carrying the crate path.
314///
315/// # Returns
316///
317/// - `PathBuf` - The web build output directory.
318pub async fn resolve_web_dist(args: &ModeArgs) -> PathBuf {
319    resolve_serving_root(args).await
320}
321
322/// Rejects the native-only flags when they reach the run mode.
323///
324/// The run mode forwards everything it does not own to `wasm-pack`, so a
325/// misplaced `--all` would silently become a wasm-pack argument and the
326/// native build the user asked for would never run. The run mode serves
327/// the pages in a browser, so it has no native deliverable to produce.
328///
329/// # Arguments
330///
331/// - `&ModeArgs` - The run mode arguments.
332///
333/// # Returns
334///
335/// - `Result<(), EuvError>` - `Ok` when no native-only flag was given.
336pub fn reject_native_flags_in_run(args: &ModeArgs) -> Result<(), EuvError> {
337    for argument in args.get_wasm_pack_args() {
338        let name: &str = argument.split('=').next().unwrap_or(argument.as_str());
339        if name == ALL_ARG || name == PLATFORMS_ARG || name == NATIVE_PATH_ARG || name == PLAN_ARG {
340            return Err(EuvError::Message(format!(
341                "{name} selects a native build, which the run mode cannot perform. Use \
342                 `euv build {name}` instead."
343            )));
344        }
345    }
346    Ok(())
347}
348
349/// Dispatches the build mode to the web-only pipeline or the native one.
350///
351/// A build that names no native platform keeps the ordinary web-only
352/// behaviour, so the existing `euv build` invocations are unchanged.
353/// A build that names one, or asks for the whole host plan, runs the
354/// native pipeline as well.
355///
356/// # Arguments
357///
358/// - `BuildArgs` - The build arguments.
359///
360/// # Returns
361///
362/// - `Result<(), EuvError>` - Indicates success or failure.
363pub async fn dispatch_build_mode(args: BuildArgs) -> Result<(), EuvError> {
364    if args.try_get_native_path().is_some() && !args.get_all() && args.get_platforms().is_empty() {
365        return Err(EuvError::Message(format!(
366            "{NATIVE_PATH_ARG} requires {ALL_ARG} or {PLATFORMS_ARG}"
367        )));
368    }
369    if args.get_all() || !args.get_platforms().is_empty() || args.get_plan() {
370        build_all_mode(args).await
371    } else {
372        build_mode(args.get_mode().clone()).await
373    }
374}
375
376/// Executes the build pipeline that produces the web output and every
377/// requested native client.
378///
379/// The web build runs exactly once, and the directory it wrote is handed
380/// to the native builders so every client embeds the same pages the web
381/// build produced. The native deliverables are built one after another,
382/// and a failing builder stops the pipeline with its own exit status
383/// rather than being reported as a skipped deliverable.
384///
385/// # Arguments
386///
387/// - `BuildArgs` - The build arguments.
388///
389/// # Returns
390///
391/// - `Result<(), EuvError>` - Indicates success or failure.
392pub async fn build_all_mode(args: BuildArgs) -> Result<(), EuvError> {
393    let mut mode_args: ModeArgs = args.get_mode().clone();
394    reconcile_args(&mut mode_args);
395    mode_args.set_crate_path(sync_canonicalize(mode_args.get_crate_path()).map_err(
396        |error: io::Error| EuvError::IoPath {
397            message: ERROR_INVALID_CRATE_PATH.to_string(),
398            path: mode_args.get_crate_path().clone(),
399            error,
400        },
401    )?);
402    let crate_path_str: String = mode_args.get_crate_path().to_string_lossy().to_string();
403    if crate_path_str.starts_with(WINDOWS_UNC_PREFIX) {
404        mode_args.set_crate_path(PathBuf::from(
405            crate_path_str
406                .strip_prefix(WINDOWS_UNC_PREFIX)
407                .unwrap_or(&crate_path_str),
408        ));
409    }
410    let requested: Vec<NativePlatform> =
411        resolve_requested_platforms(args.get_all(), args.get_platforms())?;
412    let plan: NativePlan = resolve_native_plan(&requested, current_host())?;
413    print_banner(Action::Build);
414    print_native_plan(&plan);
415    if args.get_plan() {
416        log::info!("Plan requested. Exiting without building.");
417        return Ok(());
418    }
419    if plan.get_targets().is_empty() {
420        run_build_only_pipeline(&mode_args).await?;
421        log::info!("Build completed. Exiting (build-only mode).");
422        return Ok(());
423    }
424    let base: PathBuf = current_dir().map_err(|error: io::Error| EuvError::Io {
425        message: ERROR_CURRENT_DIRECTORY.to_string(),
426        error,
427    })?;
428    let native_path: Option<&PathBuf> = args.try_get_native_path().as_ref();
429    let native_project: PathBuf = resolve_native_project(&base, native_path);
430    require_native_project(&native_project)?;
431    prepare_native_profile(&mut mode_args)?;
432    run_build_only_pipeline(&mode_args).await?;
433    let web_dist: PathBuf = resolve_web_dist(&mode_args).await;
434    log::info!("Web build output: {}", web_dist.display());
435    run_native_builds(&plan, &native_project, &web_dist, NATIVE_MODE_RELEASE).await?;
436    log::info!("Build completed. Exiting (build-all mode).");
437    Ok(())
438}
439
440/// Defaults native packaging to release and rejects unsupported build profiles.
441///
442/// # Arguments
443///
444/// - `&mut ModeArgs` - Web arguments sharing the native release snapshot.
445///
446/// # Returns
447///
448/// - `Result<(), EuvError>` - Success for a release-compatible request.
449pub(crate) fn prepare_native_profile(args: &mut ModeArgs) -> Result<(), EuvError> {
450    if args.get_dev() || args.get_profiling() {
451        return Err(EuvError::Message(
452            "Native packages support release builds only; omit --dev and --profiling".to_string(),
453        ));
454    }
455    args.set_release(true);
456    Ok(())
457}
458
459/// Runs the native builders for every deliverable in the plan.
460///
461/// The deliverables are built one after another: the Android build and
462/// the Apple builds both drive the same Cargo target directory and the
463/// same Gradle and Xcode state, so a parallel run would have them fight
464/// over the same files. Every step's exit status is propagated: a
465/// builder that fails stops the pipeline instead of being reported as
466/// a skipped deliverable.
467///
468/// # Arguments
469///
470/// - `&NativePlan` - The resolved plan.
471/// - `&Path` - The native client project directory.
472/// - `&Path` - The web build output directory the clients must embed.
473/// - `&str` - The native build mode.
474///
475/// # Returns
476///
477/// - `Result<(), EuvError>` - `Ok` when every deliverable was built.
478pub(crate) async fn run_native_builds(
479    plan: &NativePlan,
480    native_project: &Path,
481    web_dist: &Path,
482    mode: &str,
483) -> Result<(), EuvError> {
484    for target in plan.get_targets() {
485        let platform: &str = target.platform.platform_name();
486        log::info!("Building native client: {platform}");
487        match target.task {
488            NativeTask::Android => {
489                run_android_build(native_project, web_dist, mode).await?;
490            }
491            NativeTask::Client => {
492                run_client_build(native_project, platform, web_dist, mode).await?;
493            }
494        }
495    }
496    Ok(())
497}
498
499/// Runs the Android build script in the native client project.
500///
501/// The Android builder reads the web pages from the environment, so the
502/// directory this pipeline built is passed in rather than left to the
503/// builder's own default.
504///
505/// # Arguments
506///
507/// - `&Path` - The native client project directory.
508/// - `&Path` - The web build output directory the client must embed.
509/// - `&str` - The native build mode.
510///
511/// # Returns
512///
513/// - `Result<(), EuvError>` - `Ok` when the build succeeded.
514async fn run_android_build(
515    native_project: &Path,
516    web_dist: &Path,
517    mode: &str,
518) -> Result<(), EuvError> {
519    let script: PathBuf = native_project.join(ANDROID_BUILD_SCRIPT_PATH);
520    if !script.is_file() {
521        return Err(EuvError::Message(format!(
522            "The Android build script '{}' does not exist.",
523            script.display()
524        )));
525    }
526    let mut command: Command = Command::new(BASH_COMMAND);
527    command
528        .arg(&script)
529        .arg(PLATFORM_ANDROID)
530        .arg(mode)
531        .current_dir(native_project)
532        .env(ENV_WEB_DIST, web_dist)
533        .env(ENV_NATIVE_MODE, mode)
534        .stdout(Stdio::inherit())
535        .stderr(Stdio::inherit());
536    run_command(command, "Android build").await
537}
538
539/// Runs the per-platform client builder in the native client project.
540///
541/// The client builders read the web pages from the environment, so the
542/// directory this pipeline built is passed in rather than left to the
543/// builder's own default.
544///
545/// # Arguments
546///
547/// - `&Path` - The native client project directory.
548/// - `&str` - The platform to build.
549/// - `&Path` - The web build output directory the client must embed.
550/// - `&str` - The native build mode.
551///
552/// # Returns
553///
554/// - `Result<(), EuvError>` - `Ok` when the build succeeded.
555async fn run_client_build(
556    native_project: &Path,
557    platform: &str,
558    web_dist: &Path,
559    mode: &str,
560) -> Result<(), EuvError> {
561    let script: PathBuf = native_project
562        .join("scripts")
563        .join(BUILD_CLIENT_SCRIPT_PATH);
564    if !script.is_file() {
565        return Err(EuvError::Message(format!(
566            "The native client builder '{}' does not exist.",
567            script.display()
568        )));
569    }
570    let mut command: Command = Command::new(NODE_COMMAND);
571    command
572        .arg(&script)
573        .arg(platform)
574        .current_dir(native_project)
575        .env(ENV_WEB_DIST, web_dist)
576        .env(ENV_NATIVE_MODE, mode)
577        .stdout(Stdio::inherit())
578        .stderr(Stdio::inherit());
579    run_command(command, "native client build").await
580}
581
582/// Runs a native build command and propagates its exit status.
583///
584/// The command's output is forwarded as it happens, so a failing build
585/// shows the same diagnostics the builder printed on its own.
586///
587/// # Arguments
588///
589/// - `Command` - The command to run.
590/// - `&str` - The name of the step, used in the failure message.
591///
592/// # Returns
593///
594/// - `Result<(), EuvError>` - `Ok` when the command succeeded.
595async fn run_command(mut command: Command, step: &str) -> Result<(), EuvError> {
596    let status: ExitStatus = command
597        .status()
598        .await
599        .map_err(|error: io::Error| EuvError::Io {
600            message: format!("Failed to execute the {step}"),
601            error,
602        })?;
603    if status.success() {
604        return Ok(());
605    }
606    Err(EuvError::Message(format!(
607        "The {step} failed with exit code {}",
608        status.code().unwrap_or(-1)
609    )))
610}