Skip to main content

euv_cli/builder/pipeline/
fn.rs

1use super::*;
2
3/// Parses a single target or group name from `euv.toml` into a `TargetArg`.
4///
5/// # Arguments
6///
7/// - `&str` - Raw target name string (for example `"web"`, `"ios-sim"`, or `"desktop"`).
8///
9/// # Returns
10///
11/// - `Option<TargetArg>` - Parsed target enum variant when valid.
12#[must_use]
13pub fn parse_target_name_from_config(raw: &str) -> Option<TargetArg> {
14    let trimmed: &str = raw.trim();
15    if trimmed.is_empty() {
16        return None;
17    }
18    TargetArg::from_str(trimmed, true).ok()
19}
20
21/// Resolves the ordered, deduplicated concrete targets for a pipeline invocation using CLI flags and `euv.toml` defaults.
22///
23/// # Arguments
24///
25/// - `&BuildPipelineConfig` - Pipeline configuration from CLI arguments.
26/// - `Option<&EuvProjectConfig>` - Optional loaded `euv.toml` project manifest.
27///
28/// # Returns
29///
30/// - `Vec<TargetArg>` - Deduplicated concrete targets in deterministic execution order.
31#[must_use]
32pub fn resolve_pipeline_targets(
33    config: &BuildPipelineConfig,
34    euv_cfg: Option<&EuvProjectConfig>,
35) -> Vec<TargetArg> {
36    if config.get_all() {
37        return resolve_targets_dedup(&[TargetArg::All]);
38    }
39    if !config.get_targets().is_empty() {
40        return resolve_targets_dedup(config.get_targets());
41    }
42    if let Some(project_cfg) = euv_cfg {
43        let configured: Vec<TargetArg> = project_cfg
44            .get_app()
45            .get_default_targets()
46            .iter()
47            .filter_map(|raw: &String| parse_target_name_from_config(raw))
48            .collect();
49        if !configured.is_empty() {
50            return resolve_targets_dedup(&configured);
51        }
52    }
53    resolve_targets_dedup(&[TargetArg::Native])
54}
55
56/// Computes the bounded concurrency worker count for executing `target_count` targets.
57///
58/// # Arguments
59///
60/// - `&BuildPipelineConfig` - Pipeline configuration specifying `--parallel` and optional `-j/--jobs`.
61/// - `Option<&EuvProjectConfig>` - Optional loaded `euv.toml` project manifest.
62/// - `usize` - Number of runnable concrete targets.
63///
64/// # Returns
65///
66/// - `usize` - Bounded worker thread count in `1..=target_count.max(1)`.
67#[must_use]
68pub fn resolve_effective_pipeline_jobs(
69    config: &BuildPipelineConfig,
70    euv_cfg: Option<&EuvProjectConfig>,
71    target_count: usize,
72) -> usize {
73    let jobs_gt_one: bool = config.get_jobs().is_some_and(|val: usize| val > 1);
74    let cfg_parallel: bool =
75        euv_cfg.is_some_and(|cfg: &EuvProjectConfig| cfg.get_build().get_parallel());
76    let cli_parallel: bool = config.get_parallel() || jobs_gt_one;
77    let parallel_enabled: bool = cli_parallel || cfg_parallel;
78    if !parallel_enabled || target_count <= 1 {
79        return 1;
80    }
81    let requested: usize = config.get_jobs().unwrap_or_else(|| {
82        thread::available_parallelism()
83            .map(NonZeroUsize::get)
84            .unwrap_or(4)
85    });
86    requested.max(1).min(target_count)
87}
88
89/// Executes the multi-platform build pipeline against the live host toolchain capability probe.
90///
91/// # Arguments
92///
93/// - `&BuildPipelineConfig` - Pipeline configuration controlling targets, concurrency, packaging, and verification.
94///
95/// # Returns
96///
97/// - `io::Result<BuildPipelineReport>` - Structured per-target and aggregate build summary.
98pub fn execute_build_pipeline(config: &BuildPipelineConfig) -> io::Result<BuildPipelineReport> {
99    let probe: HostCapabilityProbe = HostCapabilityProbe::detect();
100    execute_build_pipeline_with_probe(config, &probe)
101}
102
103/// Executes the multi-platform build pipeline using an explicit `HostCapabilityProbe` snapshot.
104///
105/// # Arguments
106///
107/// - `&BuildPipelineConfig` - Pipeline configuration controlling targets, concurrency, packaging, and verification.
108/// - `&HostCapabilityProbe` - Host capability snapshot used to evaluate `--skip-unavailable`.
109///
110/// # Returns
111///
112/// - `io::Result<BuildPipelineReport>` - Structured per-target and aggregate build summary.
113pub fn execute_build_pipeline_with_probe(
114    config: &BuildPipelineConfig,
115    probe: &HostCapabilityProbe,
116) -> io::Result<BuildPipelineReport> {
117    let pipeline_started: Instant = Instant::now();
118    let workspace_root: PathBuf = resolve_pipeline_root(config.get_workspace_root())?;
119    let loaded_cfg: Option<LoadedEuvConfig> = load_euv_config(&workspace_root)?;
120    let euv_cfg: Option<&EuvProjectConfig> = loaded_cfg.as_ref().map(LoadedEuvConfig::get_config);
121    let workspace_meta: Option<WorkspaceMetadata> =
122        resolve_workspace_metadata(&workspace_root).ok();
123    let effective_version: String = resolve_effective_version(
124        &workspace_root,
125        config.try_get_version().as_deref(),
126        euv_cfg,
127    );
128    let effective_package: String = workspace_meta
129        .as_ref()
130        .and_then(|meta: &WorkspaceMetadata| {
131            resolve_effective_package(meta, euv_cfg, config.try_get_package().as_deref())
132        })
133        .or_else(|| config.try_get_package().clone())
134        .unwrap_or_else(|| PIPELINE_DEFAULT_PACKAGE.to_string());
135    let resolved_targets: Vec<TargetArg> = resolve_pipeline_targets(config, euv_cfg);
136    let ctx: ResolvedPipelineContext = build_resolved_context(
137        workspace_root,
138        effective_version.clone(),
139        effective_package.clone(),
140        config,
141        euv_cfg,
142        resolved_targets.len() > 1,
143    );
144    let mut outcomes: Vec<Option<TargetBuildOutcome>> = vec![None; resolved_targets.len()];
145    let mut runnable: Vec<(usize, TargetArg)> = Vec::new();
146    for (idx, target) in resolved_targets.iter().copied().enumerate() {
147        if config.get_skip_unavailable()
148            && let Some(skipped) = evaluate_target_unavailable(target, ctx.raw_wasm, probe)
149        {
150            outcomes[idx] = Some(skipped);
151            continue;
152        }
153        runnable.push((idx, target));
154    }
155    let effective_jobs: usize = resolve_effective_pipeline_jobs(config, euv_cfg, runnable.len());
156    if effective_jobs <= 1 || runnable.len() <= 1 {
157        for (idx, target) in runnable.into_iter() {
158            outcomes[idx] = Some(execute_single_pipeline_target(target, config, &ctx));
159        }
160    } else {
161        execute_targets_in_parallel(&runnable, effective_jobs, config, &ctx, &mut outcomes)?;
162    }
163    let final_outcomes: Vec<TargetBuildOutcome> = outcomes.into_iter().flatten().collect();
164    let mut passed_count: usize = 0;
165    let mut skipped_count: usize = 0;
166    let mut failed_count: usize = 0;
167    for outcome in final_outcomes.iter() {
168        match outcome.get_status() {
169            TargetBuildStatus::Passed => passed_count += 1,
170            TargetBuildStatus::SkippedUnavailable => skipped_count += 1,
171            TargetBuildStatus::Failed => failed_count += 1,
172        }
173    }
174    let total_elapsed_ms: u64 =
175        u64::try_from(pipeline_started.elapsed().as_millis()).unwrap_or(u64::MAX);
176    let mut report: BuildPipelineReport = BuildPipelineReport::default();
177    let _: &mut BuildPipelineReport = report
178        .set_version(effective_version)
179        .set_package(effective_package)
180        .set_parallel(effective_jobs > 1)
181        .set_jobs(effective_jobs)
182        .set_passed_count(passed_count)
183        .set_skipped_count(skipped_count)
184        .set_failed_count(failed_count)
185        .set_total_elapsed_ms(total_elapsed_ms)
186        .set_outcomes(final_outcomes);
187    Ok(report)
188}
189
190/// Formats a `BuildPipelineReport` into an aligned `TerminalTable` summary with skip install hints.
191///
192/// # Arguments
193///
194/// - `&BuildPipelineReport` - Completed pipeline build report.
195///
196/// # Returns
197///
198/// - `String` - Human-readable terminal summary table and totals footer.
199#[must_use]
200pub fn format_build_pipeline_report(report: &BuildPipelineReport) -> String {
201    let mut table: TerminalTable = TerminalTable::with_headers(vec![
202        PIPELINE_HEADER_TARGET.to_string(),
203        PIPELINE_HEADER_STATUS.to_string(),
204        PIPELINE_HEADER_TIME.to_string(),
205        PIPELINE_HEADER_DETAIL.to_string(),
206    ]);
207    let mut skip_hints: Vec<String> = Vec::new();
208    for outcome in report.get_outcomes().iter() {
209        let cell_detail: String = if let Some(archive) = outcome.try_get_archive_path() {
210            archive.clone()
211        } else if let Some(artifact) = outcome.try_get_artifact_path() {
212            artifact.clone()
213        } else {
214            outcome.get_detail().clone()
215        };
216        table.push_row(vec![
217            outcome.get_target().clone(),
218            outcome.get_status().label().to_string(),
219            format_duration_ms(u128::from(outcome.get_elapsed_ms())),
220            cell_detail,
221        ]);
222        if outcome.get_status() == TargetBuildStatus::SkippedUnavailable
223            && let Some(hint) = outcome.try_get_install_hint()
224            && !hint.trim().is_empty()
225        {
226            skip_hints.push(format!("  - {}: {hint}", outcome.get_target()));
227        }
228    }
229    let mut out: String = table.render();
230    let mode_note: String = if report.get_parallel() {
231        format!("parallel jobs={}", report.get_jobs())
232    } else {
233        "sequential".to_string()
234    };
235    out.push_str(&format!(
236        "Build v{} ({}, {}): {} passed, {} skipped, {} failed ({})\n",
237        report.get_version(),
238        report.get_package(),
239        mode_note,
240        report.get_passed_count(),
241        report.get_skipped_count(),
242        report.get_failed_count(),
243        format_duration_ms(u128::from(report.get_total_elapsed_ms()))
244    ));
245    if !skip_hints.is_empty() {
246        out.push_str("Install hints for skipped targets:\n");
247        for hint_line in skip_hints.iter() {
248            out.push_str(hint_line);
249            out.push('\n');
250        }
251    }
252    out
253}
254
255/// Builds a `DevRebuildHook` invoking pure-Rust `builder::{web,ecosystem}` engines for `euv dev`.
256///
257/// # Returns
258///
259/// - `DevRebuildHook` - Thread-safe rebuild callback wired into `start_dev_server_with_hook`.
260#[must_use]
261pub fn create_builder_dev_rebuild_hook() -> DevRebuildHook {
262    Arc::new(
263        |config: &DevServerConfig, _changed: &[String]| -> io::Result<String> {
264            run_dev_builder_hook(config)
265        },
266    )
267}
268
269/// Dispatches a live `euv dev` rebuild for `web`, `harmony`, `wearable`, `miniapp`, or `quickapp` via pure-Rust builders.
270///
271/// # Arguments
272///
273/// - `&DevServerConfig` - Active dev server configuration.
274///
275/// # Returns
276///
277/// - `io::Result<String>` - Human-readable rebuild summary or error.
278fn run_dev_builder_hook(config: &DevServerConfig) -> io::Result<String> {
279    let workspace_root: PathBuf = resolve_pipeline_root(config.get_src_dir())?;
280    let loaded_cfg: Option<LoadedEuvConfig> = load_euv_config(&workspace_root).ok().flatten();
281    let euv_cfg: Option<&EuvProjectConfig> = loaded_cfg.as_ref().map(LoadedEuvConfig::get_config);
282    let version: String = resolve_effective_version(&workspace_root, None, euv_cfg);
283    match config.get_target() {
284        DevTargetArg::Web => {
285            let ws_meta: Option<WorkspaceMetadata> =
286                resolve_workspace_metadata(&workspace_root).ok();
287            let package: String = ws_meta
288                .as_ref()
289                .and_then(|meta: &WorkspaceMetadata| {
290                    resolve_effective_package(meta, euv_cfg, config.try_get_package().as_deref())
291                })
292                .or_else(|| config.try_get_package().clone())
293                .unwrap_or_else(|| PIPELINE_DEFAULT_PACKAGE.to_string());
294            let mut web_cfg: WebBuildConfig = WebBuildConfig::default();
295            let _: &mut WebBuildConfig = web_cfg
296                .set_repo_root(workspace_root)
297                .set_package(package)
298                .set_out_dir(config.get_out_dir().clone())
299                .set_base_url(PIPELINE_DEFAULT_BASE_URL.to_string())
300                .set_title(
301                    config
302                        .try_get_title()
303                        .clone()
304                        .unwrap_or_else(|| PIPELINE_DEFAULT_WEB_TITLE.to_string()),
305                )
306                .set_version(Some(version))
307                .set_release(config.get_release())
308                .set_skip_wasm_opt(!config.get_release())
309                .set_raw_wasm(false)
310                .set_verify(false);
311            let report: WebBuildReport = build_web_bundle(&web_cfg)?;
312            let index_path: PathBuf = report.get_out_dir().join(INDEX_HTML_NAME);
313            if index_path.is_file() {
314                let raw_html: String = fs::read_to_string(&index_path)?;
315                let injected: String = inject_dev_hmr_into_html(&raw_html, HMR_ENDPOINT);
316                fs::write(&index_path, injected)?;
317            }
318            Ok(format!(
319                "{PIPELINE_DEV_REBUILT_WEB} ({} {})",
320                report.get_wasm_file(),
321                format_bytes_human(report.get_wasm_bytes())
322            ))
323        }
324        DevTargetArg::Harmony => {
325            let icon_writer: &MobileIconWriter<'_> =
326                &|path: &Path, size: u32| -> io::Result<()> { write_icon_png(path, size, None) };
327            let mut harmony_cfg: HarmonyBuildConfig = HarmonyBuildConfig::default();
328            let _: &mut HarmonyBuildConfig = harmony_cfg
329                .set_workspace_root(workspace_root)
330                .set_app_version(Some(version))
331                .set_out_dir(Some(config.get_out_dir().clone()));
332            let report: HarmonyBuildReport = build_harmony_app(&harmony_cfg, Some(icon_writer))?;
333            Ok(format!(
334                "{PIPELINE_DEV_REBUILT_HARMONY} ({})",
335                report.get_out_dir().display()
336            ))
337        }
338        DevTargetArg::Wearable => {
339            let icon_writer: &MobileIconWriter<'_> =
340                &|path: &Path, size: u32| -> io::Result<()> { write_icon_png(path, size, None) };
341            let mut wearable_cfg: WearableBuildConfig = WearableBuildConfig::default();
342            let _: &mut WearableBuildConfig = wearable_cfg
343                .set_workspace_root(workspace_root)
344                .set_app_version(Some(version))
345                .set_out_base(Some(config.get_out_dir().clone()))
346                .set_release(config.get_release())
347                .set_skip_wasm_opt(!config.get_release());
348            let report: WearableBuildReport =
349                build_wearable_targets(&wearable_cfg, Some(icon_writer))?;
350            Ok(format!(
351                "{PIPELINE_DEV_REBUILT_WEARABLE} ({} target(s))",
352                report.get_generated_paths().len()
353            ))
354        }
355        DevTargetArg::Miniapp => {
356            let icon_writer: &MobileIconWriter<'_> =
357                &|path: &Path, size: u32| -> io::Result<()> { write_icon_png(path, size, None) };
358            let mut miniapp_cfg: MiniAppBuildConfig = MiniAppBuildConfig::default();
359            let _: &mut MiniAppBuildConfig = miniapp_cfg
360                .set_workspace_root(workspace_root)
361                .set_app_version(Some(version))
362                .set_out_base(Some(config.get_out_dir().clone()))
363                .set_release(config.get_release())
364                .set_skip_wasm_opt(!config.get_release());
365            let report: MiniAppBuildReport =
366                build_miniapp_targets(&miniapp_cfg, Some(icon_writer))?;
367            Ok(format!(
368                "{PIPELINE_DEV_REBUILT_MINIAPP} ({} vendor(s))",
369                report.get_generated_dirs().len()
370            ))
371        }
372        DevTargetArg::Quickapp => {
373            let icon_writer: &MobileIconWriter<'_> =
374                &|path: &Path, size: u32| -> io::Result<()> { write_icon_png(path, size, None) };
375            let mut quickapp_cfg: QuickAppBuildConfig = QuickAppBuildConfig::default();
376            let _: &mut QuickAppBuildConfig = quickapp_cfg
377                .set_workspace_root(workspace_root)
378                .set_app_version(Some(version))
379                .set_out_base(Some(config.get_out_dir().clone()))
380                .set_release(config.get_release())
381                .set_skip_wasm_opt(!config.get_release());
382            let report: QuickAppBuildReport =
383                build_quickapp_targets(&quickapp_cfg, Some(icon_writer))?;
384            Ok(format!(
385                "{PIPELINE_DEV_REBUILT_QUICKAPP} ({} vendor(s))",
386                report.get_generated_dirs().len()
387            ))
388        }
389        _ => Ok(PIPELINE_DEV_REBUILT_NOOP.to_string()),
390    }
391}
392
393/// Resolves `workspace_root` to an absolute filesystem path.
394///
395/// # Arguments
396///
397/// - `&Path` - Configured root path (relative or absolute).
398///
399/// # Returns
400///
401/// - `io::Result<PathBuf>` - Resolved absolute workspace root path.
402fn resolve_pipeline_root(raw_root: &Path) -> io::Result<PathBuf> {
403    if raw_root.is_absolute() {
404        Ok(raw_root.to_path_buf())
405    } else {
406        Ok(env::current_dir()?.join(raw_root))
407    }
408}
409
410/// Resolves a potentially relative path against `root`, keeping absolute paths unchanged.
411///
412/// # Arguments
413///
414/// - `&Path` - Base root directory.
415/// - `&Path` - Target path to normalize.
416///
417/// # Returns
418///
419/// - `PathBuf` - Absolute or root-anchored path.
420fn resolve_against_root(root: &Path, path: &Path) -> PathBuf {
421    if path.is_absolute() {
422        path.to_path_buf()
423    } else {
424        root.join(path)
425    }
426}
427
428/// Constructs a `ResolvedPipelineContext` merging CLI flags over `euv.toml` defaults.
429///
430/// # Arguments
431///
432/// - `PathBuf` - Resolved workspace root directory.
433/// - `String` - Effective semantic version string.
434/// - `String` - Effective primary Cargo package name.
435/// - `&BuildPipelineConfig` - Explicit CLI configuration.
436/// - `Option<&EuvProjectConfig>` - Optional `euv.toml` manifest.
437/// - `bool` - Whether multiple targets are being built.
438///
439/// # Returns
440///
441/// - `ResolvedPipelineContext` - Effective merged pipeline context.
442fn build_resolved_context(
443    workspace_root: PathBuf,
444    version: String,
445    package: String,
446    config: &BuildPipelineConfig,
447    euv_cfg: Option<&EuvProjectConfig>,
448    multi_target: bool,
449) -> ResolvedPipelineContext {
450    let app_label: Option<String> =
451        euv_cfg.and_then(|cfg: &EuvProjectConfig| cfg.get_app().try_get_name().clone());
452    let bundle_id: Option<String> =
453        euv_cfg.and_then(|cfg: &EuvProjectConfig| cfg.get_app().try_get_bundle_id().clone());
454    let base_url: String = config
455        .try_get_base()
456        .clone()
457        .or_else(|| {
458            euv_cfg.and_then(|cfg: &EuvProjectConfig| cfg.get_build().try_get_base().clone())
459        })
460        .unwrap_or_else(|| PIPELINE_DEFAULT_BASE_URL.to_string());
461    let icon_path: Option<PathBuf> = config.try_get_icon().clone().or_else(|| {
462        euv_cfg.and_then(|cfg: &EuvProjectConfig| cfg.get_app().try_get_icon().clone())
463    });
464    let android_api_level: Option<String> = euv_cfg
465        .and_then(|cfg: &EuvProjectConfig| cfg.get_build().get_android_api_level())
466        .map(|level: u32| level.to_string());
467    let android_build_tools: Option<String> = euv_cfg
468        .and_then(|cfg: &EuvProjectConfig| cfg.get_build().try_get_android_build_tools().clone());
469    let cfg_raw_wasm: bool =
470        euv_cfg.is_some_and(|cfg: &EuvProjectConfig| cfg.get_build().get_raw_wasm());
471    let cfg_skip_opt: bool =
472        euv_cfg.is_some_and(|cfg: &EuvProjectConfig| cfg.get_build().get_skip_wasm_opt());
473    let cfg_include_cli: bool =
474        euv_cfg.is_some_and(|cfg: &EuvProjectConfig| cfg.get_build().get_include_cli());
475    let raw_wasm: bool = config.get_raw_wasm() || cfg_raw_wasm;
476    let skip_wasm_opt: bool = config.get_skip_wasm_opt() || cfg_skip_opt;
477    let include_cli: bool = config.get_include_cli() || cfg_include_cli;
478    let out_dir: Option<PathBuf> = config.try_get_out_dir().clone().or_else(|| {
479        euv_cfg.and_then(|cfg: &EuvProjectConfig| cfg.get_build().try_get_out_dir().clone())
480    });
481    ResolvedPipelineContext {
482        workspace_root,
483        version,
484        package,
485        app_label,
486        bundle_id,
487        base_url,
488        icon_path,
489        android_api_level,
490        android_build_tools,
491        raw_wasm,
492        skip_wasm_opt,
493        include_cli,
494        out_dir,
495        multi_target,
496    }
497}
498
499/// Evaluates whether `target` should be skipped cleanly under `--skip-unavailable`.
500///
501/// # Arguments
502///
503/// - `TargetArg` - Concrete target under evaluation.
504/// - `bool` - Whether `--raw-wasm` is enabled (relaxes `wasm-bindgen` requirement on `web`).
505/// - `&HostCapabilityProbe` - Host capability snapshot.
506///
507/// # Returns
508///
509/// - `Option<TargetBuildOutcome>` - `Some(SkippedUnavailable)` when unavailable, or `None` when runnable.
510fn evaluate_target_unavailable(
511    target: TargetArg,
512    raw_wasm: bool,
513    probe: &HostCapabilityProbe,
514) -> Option<TargetBuildOutcome> {
515    if target == TargetArg::Web && raw_wasm {
516        if probe.has_triple(TRIPLE_WEB) {
517            return None;
518        }
519        let mut outcome: TargetBuildOutcome = TargetBuildOutcome::new(
520            NAME_WEB.to_string(),
521            TargetBuildStatus::SkippedUnavailable,
522            0,
523            format!("{PIPELINE_DETAIL_MISSING_PREFIX}{TRIPLE_WEB}"),
524        );
525        let _: &mut TargetBuildOutcome =
526            outcome.set_install_hint(Some(PIPELINE_HINT_WASM32_TARGET.to_string()));
527        return Some(outcome);
528    }
529    let cap: TargetCapability = probe.probe_target(target);
530    if cap.get_ready() {
531        return None;
532    }
533    let detail: String = if cap.get_missing_tools().is_empty() {
534        PIPELINE_DETAIL_SKIPPED_DEFAULT.to_string()
535    } else {
536        format!(
537            "{PIPELINE_DETAIL_MISSING_PREFIX}{}",
538            cap.get_missing_tools().join(", ")
539        )
540    };
541    let hint: Option<String> = if cap.get_install_hints().is_empty() {
542        None
543    } else {
544        Some(cap.get_install_hints().join(" && "))
545    };
546    let mut outcome: TargetBuildOutcome = TargetBuildOutcome::new(
547        cap.get_target().clone(),
548        TargetBuildStatus::SkippedUnavailable,
549        0,
550        detail,
551    );
552    let _: &mut TargetBuildOutcome = outcome.set_install_hint(hint);
553    Some(outcome)
554}
555
556/// Executes runnable targets concurrently across `jobs` scoped worker threads, preserving deterministic output order.
557///
558/// # Arguments
559///
560/// - `&[(usize, TargetArg)]` - Indexed runnable targets.
561/// - `usize` - Bounded worker thread count.
562/// - `&BuildPipelineConfig` - Pipeline configuration.
563/// - `&ResolvedPipelineContext` - Shared resolved pipeline context.
564/// - `&mut [Option<TargetBuildOutcome>]` - Pre-allocated outcome slots indexed by original target position.
565///
566/// # Returns
567///
568/// - `io::Result<()>` - Completion status or worker panic error.
569fn execute_targets_in_parallel(
570    runnable: &[(usize, TargetArg)],
571    jobs: usize,
572    config: &BuildPipelineConfig,
573    ctx: &ResolvedPipelineContext,
574    outcomes: &mut [Option<TargetBuildOutcome>],
575) -> io::Result<()> {
576    let cursor: Mutex<usize> = Mutex::new(0);
577    let results: Mutex<Vec<(usize, TargetBuildOutcome)>> =
578        Mutex::new(Vec::with_capacity(runnable.len()));
579    let worker_count: usize = jobs.min(runnable.len()).max(1);
580    let mut panicked: bool = false;
581    thread::scope(|scope: &Scope<'_, '_>| {
582        let mut handles: Vec<ScopedJoinHandle<'_, ()>> = Vec::with_capacity(worker_count);
583        for _worker_idx in 0..worker_count {
584            let cursor_ref: &Mutex<usize> = &cursor;
585            let results_ref: &Mutex<Vec<(usize, TargetBuildOutcome)>> = &results;
586            let handle: ScopedJoinHandle<'_, ()> = scope.spawn(move || {
587                loop {
588                    let next_pos: usize = {
589                        let Ok(mut guard) = cursor_ref.lock() else {
590                            break;
591                        };
592                        let current: usize = *guard;
593                        if current >= runnable.len() {
594                            break;
595                        }
596                        *guard = current + 1;
597                        current
598                    };
599                    let (slot_idx, target): (usize, TargetArg) = runnable[next_pos];
600                    let outcome: TargetBuildOutcome =
601                        execute_single_pipeline_target(target, config, ctx);
602                    if let Ok(mut out_guard) = results_ref.lock() {
603                        out_guard.push((slot_idx, outcome));
604                    }
605                }
606            });
607            handles.push(handle);
608        }
609        for handle in handles.into_iter() {
610            if handle.join().is_err() {
611                panicked = true;
612            }
613        }
614    });
615    if panicked {
616        return Err(Error::other(PIPELINE_ERR_WORKER_PANIC));
617    }
618    let collected: Vec<(usize, TargetBuildOutcome)> = results
619        .into_inner()
620        .map_err(|_| Error::other(PIPELINE_ERR_LOCK_POISONED))?;
621    for (slot_idx, outcome) in collected.into_iter() {
622        outcomes[slot_idx] = Some(outcome);
623    }
624    Ok(())
625}
626
627/// Dispatches one concrete `target` to its native pure-Rust builder and captures timing and outcome metadata.
628///
629/// # Arguments
630///
631/// - `TargetArg` - Concrete platform target.
632/// - `&BuildPipelineConfig` - Pipeline configuration.
633/// - `&ResolvedPipelineContext` - Shared resolved pipeline context.
634///
635/// # Returns
636///
637/// - `TargetBuildOutcome` - Passed or Failed outcome with artifact, archive, and manifest paths.
638fn execute_single_pipeline_target(
639    target: TargetArg,
640    config: &BuildPipelineConfig,
641    ctx: &ResolvedPipelineContext,
642) -> TargetBuildOutcome {
643    let spec: TargetSpec = spec_for_platform(target);
644    let label: String = spec.get_name().clone();
645    let started: Instant = Instant::now();
646    let result: io::Result<TargetBuildOutcome> = match target {
647        TargetArg::Web => dispatch_web_target(config, ctx),
648        TargetArg::Macos
649        | TargetArg::Windows
650        | TargetArg::Linux
651        | TargetArg::Tui
652        | TargetArg::Cli
653        | TargetArg::Native => dispatch_desktop_target(target, config, ctx),
654        TargetArg::Android => dispatch_android_target(AndroidTargetKind::Phone, config, ctx),
655        TargetArg::Wearos => dispatch_android_target(AndroidTargetKind::WearOs, config, ctx),
656        TargetArg::Ios => dispatch_apple_target(AppleTargetKind::IosDevice, config, ctx),
657        TargetArg::IosSim => dispatch_apple_target(AppleTargetKind::IosSim, config, ctx),
658        TargetArg::Ipad => dispatch_apple_target(AppleTargetKind::IpadDevice, config, ctx),
659        TargetArg::IpadSim => dispatch_apple_target(AppleTargetKind::IpadSim, config, ctx),
660        TargetArg::Watchos => dispatch_apple_target(AppleTargetKind::WatchOsSim, config, ctx),
661        TargetArg::Harmony | TargetArg::HarmonyPc => dispatch_harmony_target(target, config, ctx),
662        TargetArg::HarmonyWearable
663        | TargetArg::Vela
664        | TargetArg::VivoWatch
665        | TargetArg::OppoWatch
666        | TargetArg::Garmin
667        | TargetArg::Zeppos
668        | TargetArg::Wearable => dispatch_wearable_target(target, config, ctx),
669        TargetArg::Wechat
670        | TargetArg::Alipay
671        | TargetArg::Douyin
672        | TargetArg::Baidu
673        | TargetArg::Qq
674        | TargetArg::Kuaishou
675        | TargetArg::Jd
676        | TargetArg::Xhs
677        | TargetArg::Dingtalk
678        | TargetArg::Feishu
679        | TargetArg::Taobao
680        | TargetArg::Meituan
681        | TargetArg::HarmonyAtomic => dispatch_miniapp_target(target, config, ctx),
682        TargetArg::Quickapp | TargetArg::QuickappAlliance | TargetArg::QuickappHuawei => {
683            dispatch_quickapp_target(target, config, ctx)
684        }
685        _ => dispatch_desktop_target(TargetArg::Native, config, ctx),
686    };
687    let elapsed_ms: u64 = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
688    match result {
689        Ok(mut outcome) => {
690            let _: &mut TargetBuildOutcome = outcome.set_elapsed_ms(elapsed_ms);
691            outcome
692        }
693        Err(err) => TargetBuildOutcome::new(
694            label,
695            TargetBuildStatus::Failed,
696            elapsed_ms,
697            err.to_string(),
698        ),
699    }
700}
701
702/// Computes a per-target output directory avoiding collisions when building multiple targets under one `--out-dir`.
703///
704/// # Arguments
705///
706/// - `&ResolvedPipelineContext` - Shared resolved pipeline context.
707/// - `&str` - Canonical target subdirectory name.
708/// - `&str` - Default target output directory when `--out-dir` is omitted.
709///
710/// # Returns
711///
712/// - `PathBuf` - Effective destination directory for the target.
713fn resolve_target_out_dir(
714    ctx: &ResolvedPipelineContext,
715    target_sub: &str,
716    default_dir: &str,
717) -> PathBuf {
718    match ctx.out_dir.as_ref() {
719        Some(base_dir) if ctx.multi_target => base_dir.join(target_sub),
720        Some(base_dir) => base_dir.clone(),
721        None => PathBuf::from(default_dir),
722    }
723}
724
725/// Optionally writes and verifies `euv-release.json` inside `dir` when `--manifest` is active.
726///
727/// # Arguments
728///
729/// - `&Path` - Staged output directory.
730/// - `&str` - Resolved semantic version.
731/// - `bool` - Whether `--manifest` is requested.
732/// - `bool` - Whether `--verify` is requested.
733///
734/// # Returns
735///
736/// - `io::Result<Option<String>>` - Generated `euv-release.json` path string, if written.
737fn maybe_write_dir_manifest(
738    dir: &Path,
739    version: &str,
740    manifest: bool,
741    verify: bool,
742) -> io::Result<Option<String>> {
743    if !manifest || !dir.is_dir() {
744        return Ok(None);
745    }
746    let _: ReleaseAssetManifest = write_release_manifest(dir, version)?;
747    if verify {
748        let _: ReleaseAssetManifest = verify_release_manifest(dir, Some(version), &[])?;
749    }
750    Ok(Some(dir.join(RELEASE_MANIFEST_NAME).display().to_string()))
751}
752
753/// Dispatches `TargetArg::Web` to `builder::web` (`build_web_bundle` or `build_web_theme_variants`).
754///
755/// # Arguments
756///
757/// - `&BuildPipelineConfig` - Pipeline configuration.
758/// - `&ResolvedPipelineContext` - Shared resolved pipeline context.
759///
760/// # Returns
761///
762/// - `io::Result<TargetBuildOutcome>` - Built Web outcome.
763fn dispatch_web_target(
764    config: &BuildPipelineConfig,
765    ctx: &ResolvedPipelineContext,
766) -> io::Result<TargetBuildOutcome> {
767    let out_dir: PathBuf = resolve_target_out_dir(ctx, NAME_WEB, OUT_DIR_WEB);
768    let archive_path: Option<PathBuf> = if ctx.multi_target {
769        None
770    } else {
771        config
772            .try_get_archive()
773            .as_ref()
774            .map(|dest: &PathBuf| resolve_against_root(&ctx.workspace_root, dest))
775    };
776    let mut web_cfg: WebBuildConfig = WebBuildConfig::default();
777    let _: &mut WebBuildConfig = web_cfg
778        .set_repo_root(ctx.workspace_root.clone())
779        .set_package(ctx.package.clone())
780        .set_out_dir(out_dir)
781        .set_base_url(ctx.base_url.clone())
782        .set_title(
783            ctx.app_label
784                .clone()
785                .unwrap_or_else(|| PIPELINE_DEFAULT_WEB_TITLE.to_string()),
786        )
787        .set_version(Some(ctx.version.clone()))
788        .set_icon_path(ctx.icon_path.clone())
789        .set_archive_path(archive_path)
790        .set_features(config.get_features().clone())
791        .set_release(config.get_release())
792        .set_skip_wasm_opt(ctx.skip_wasm_opt)
793        .set_raw_wasm(ctx.raw_wasm)
794        .set_verify(config.get_verify())
795        .set_theme_variants(config.get_theme_variants());
796    if config.get_theme_variants() {
797        let report: ThemeVariantBuildReport = build_web_theme_variants(&web_cfg)?;
798        let detail: String = format!(
799            "{} ({} built, {} cached)",
800            report.get_out_dir().display(),
801            report.get_built_variants().len(),
802            report.get_cached_variants().len()
803        );
804        return Ok(make_passed_outcome(
805            NAME_WEB.to_string(),
806            report.get_elapsed_ms(),
807            Some(report.get_out_dir().display().to_string()),
808            None,
809            None,
810            detail,
811        ));
812    }
813    let report: WebBuildReport = build_web_bundle(&web_cfg)?;
814    let manifest_path: Option<String> = match report.try_get_manifest_path() {
815        Some(existing) => Some(existing.display().to_string()),
816        None => maybe_write_dir_manifest(
817            report.get_out_dir(),
818            &ctx.version,
819            config.get_manifest(),
820            config.get_verify(),
821        )?,
822    };
823    let archive_str: Option<String> = report
824        .try_get_archive_path()
825        .as_ref()
826        .map(|path: &PathBuf| path.display().to_string());
827    let detail: String = format!(
828        "{} ({}, {} files)",
829        report.get_out_dir().display(),
830        format_bytes_human(report.get_wasm_bytes()),
831        report.get_file_count()
832    );
833    Ok(make_passed_outcome(
834        NAME_WEB.to_string(),
835        report.get_elapsed_ms(),
836        Some(report.get_out_dir().display().to_string()),
837        archive_str,
838        manifest_path,
839        detail,
840    ))
841}
842
843/// Dispatches desktop and terminal targets (`macos`, `windows`, `linux`, `tui`, `cli`, `native`) to `builder::desktop`.
844///
845/// # Arguments
846///
847/// - `TargetArg` - Concrete desktop or terminal target.
848/// - `&BuildPipelineConfig` - Pipeline configuration.
849/// - `&ResolvedPipelineContext` - Shared resolved pipeline context.
850///
851/// # Returns
852///
853/// - `io::Result<TargetBuildOutcome>` - Built desktop/terminal outcome.
854fn dispatch_desktop_target(
855    target: TargetArg,
856    config: &BuildPipelineConfig,
857    ctx: &ResolvedPipelineContext,
858) -> io::Result<TargetBuildOutcome> {
859    let kind: DesktopTargetKind =
860        DesktopTargetKind::from_target_arg(target).unwrap_or_else(DesktopTargetKind::current_host);
861    let default_dir: PathBuf = kind.default_out_dir();
862    let default_dir_str: String = default_dir.display().to_string();
863    let out_dir: PathBuf = resolve_target_out_dir(ctx, kind.platform_label(), &default_dir_str);
864    let archive_path: Option<PathBuf> = if ctx.multi_target {
865        None
866    } else {
867        config
868            .try_get_archive()
869            .as_ref()
870            .map(|dest: &PathBuf| resolve_against_root(&ctx.workspace_root, dest))
871    };
872    let is_terminal_target: bool = kind == DesktopTargetKind::Tui || kind == DesktopTargetKind::Cli;
873    let is_host_native: bool = kind == DesktopTargetKind::current_host() || is_terminal_target;
874    let target_triple: Option<String> = if is_host_native {
875        None
876    } else {
877        Some(spec_for_platform(target).get_rust_triple().clone())
878    };
879    let mut desktop_cfg: DesktopBuildConfig = DesktopBuildConfig::default();
880    let _: &mut DesktopBuildConfig = desktop_cfg
881        .set_repo_root(ctx.workspace_root.clone())
882        .set_target(kind)
883        .set_package(config.try_get_package().clone())
884        .set_target_triple(target_triple)
885        .set_out_dir(out_dir)
886        .set_archive_path(archive_path)
887        .set_icon_path(ctx.icon_path.clone())
888        .set_version(Some(ctx.version.clone()))
889        .set_features(config.get_features().clone())
890        .set_release(config.get_release())
891        .set_include_cli(ctx.include_cli)
892        .set_smoke(config.get_smoke())
893        .set_verify_ai_schema(config.get_release() || config.get_verify());
894    let report: DesktopBuildReport = build_desktop_client(&desktop_cfg)?;
895    let manifest_path: Option<String> = maybe_write_dir_manifest(
896        report.get_out_dir(),
897        &ctx.version,
898        config.get_manifest(),
899        config.get_verify(),
900    )?;
901    let archive_str: Option<String> = report
902        .try_get_archive_path()
903        .as_ref()
904        .map(|path: &PathBuf| path.display().to_string());
905    let detail: String = format!(
906        "{} ({} staged file(s))",
907        report.get_out_dir().display(),
908        report.get_staged_files().len()
909    );
910    Ok(make_passed_outcome(
911        report.get_platform().clone(),
912        report.get_elapsed_ms(),
913        Some(report.get_out_dir().display().to_string()),
914        archive_str,
915        manifest_path,
916        detail,
917    ))
918}
919
920/// Dispatches Android phone or Wear OS APK builds to `builder::android` using `builder::icon::write_icon_png`.
921///
922/// # Arguments
923///
924/// - `AndroidTargetKind` - `Phone` or `WearOs`.
925/// - `&BuildPipelineConfig` - Pipeline configuration.
926/// - `&ResolvedPipelineContext` - Shared resolved pipeline context.
927///
928/// # Returns
929///
930/// - `io::Result<TargetBuildOutcome>` - Built Android/Wear OS APK outcome.
931fn dispatch_android_target(
932    kind: AndroidTargetKind,
933    config: &BuildPipelineConfig,
934    ctx: &ResolvedPipelineContext,
935) -> io::Result<TargetBuildOutcome> {
936    let mut abis: Vec<AndroidAbi> = Vec::new();
937    for raw_abi in config.get_abis().iter() {
938        abis.push(parse_android_abi(raw_abi)?);
939    }
940    let kind_label: &str = match kind {
941        AndroidTargetKind::Phone => NAME_ANDROID,
942        AndroidTargetKind::WearOs => NAME_WEAROS,
943    };
944    let out_file: Option<PathBuf> = if !ctx.multi_target
945        && let Some(explicit) = config.try_get_out_file()
946    {
947        Some(resolve_against_root(&ctx.workspace_root, explicit))
948    } else if let Some(base_dir) = ctx.out_dir.as_ref() {
949        let target_dir: PathBuf = if ctx.multi_target {
950            resolve_against_root(&ctx.workspace_root, base_dir).join(kind_label)
951        } else {
952            resolve_against_root(&ctx.workspace_root, base_dir)
953        };
954        let apk_name: &str = match kind {
955            AndroidTargetKind::Phone => PIPELINE_ANDROID_DEFAULT_APK,
956            AndroidTargetKind::WearOs => PIPELINE_WEAROS_DEFAULT_APK,
957        };
958        Some(target_dir.join(apk_name))
959    } else {
960        None
961    };
962    let android_render: RenderArg = config.get_render().unwrap_or(RenderArg::Auto);
963    let mut android_cfg: AndroidBuildConfig = AndroidBuildConfig::default();
964    let _: &mut AndroidBuildConfig = android_cfg
965        .set_workspace_root(ctx.workspace_root.clone())
966        .set_target_kind(kind)
967        .set_render_mode(android_render)
968        .set_app_version(Some(ctx.version.clone()))
969        .set_app_label(ctx.app_label.clone())
970        .set_out_file(out_file)
971        .set_release(config.get_release())
972        .set_install(config.get_install())
973        .set_api_level(ctx.android_api_level.clone())
974        .set_build_tools(ctx.android_build_tools.clone())
975        .set_avd_name(config.try_get_device().clone());
976    if !abis.is_empty() {
977        let _: &mut AndroidBuildConfig = android_cfg.set_abis(abis);
978    }
979    if let Some(pkg_id) = ctx.bundle_id.as_ref() {
980        let _: &mut AndroidBuildConfig = android_cfg.set_package_id(pkg_id.clone());
981    }
982    let custom_icon: Option<&Path> = ctx.icon_path.as_deref();
983    let icon_writer: &MobileIconWriter<'_> =
984        &|path: &Path, size: u32| -> io::Result<()> { write_icon_png(path, size, custom_icon) };
985    let report: AndroidBuildReport = build_android_apk(&android_cfg, Some(icon_writer))?;
986    let label: String = match kind {
987        AndroidTargetKind::Phone => NAME_ANDROID.to_string(),
988        AndroidTargetKind::WearOs => NAME_WEAROS.to_string(),
989    };
990    let manifest_path: Option<String> = match report.get_apk_path().parent() {
991        Some(parent) => maybe_write_dir_manifest(
992            parent,
993            &ctx.version,
994            config.get_manifest(),
995            config.get_verify(),
996        )?,
997        None => None,
998    };
999    let detail: String = format!(
1000        "{} ({}, abis={})",
1001        report.get_apk_path().display(),
1002        format_bytes_human(report.get_apk_bytes()),
1003        report.get_abis().join(",")
1004    );
1005    Ok(make_passed_outcome(
1006        label,
1007        0,
1008        Some(report.get_apk_path().display().to_string()),
1009        None,
1010        manifest_path,
1011        detail,
1012    ))
1013}
1014
1015/// Dispatches iOS, iPadOS, and watchOS `.app` bundle builds to `builder::apple` using `builder::icon::write_icon_png`.
1016///
1017/// # Arguments
1018///
1019/// - `AppleTargetKind` - Selected Apple platform/simulator kind.
1020/// - `&BuildPipelineConfig` - Pipeline configuration.
1021/// - `&ResolvedPipelineContext` - Shared resolved pipeline context.
1022///
1023/// # Returns
1024///
1025/// - `io::Result<TargetBuildOutcome>` - Built Apple bundle outcome.
1026fn dispatch_apple_target(
1027    kind: AppleTargetKind,
1028    config: &BuildPipelineConfig,
1029    ctx: &ResolvedPipelineContext,
1030) -> io::Result<TargetBuildOutcome> {
1031    let kind_label: &str = match kind {
1032        AppleTargetKind::IosSim => NAME_IOS_SIM,
1033        AppleTargetKind::IpadSim => NAME_IPAD_SIM,
1034        AppleTargetKind::IosDevice => NAME_IOS,
1035        AppleTargetKind::IpadDevice => NAME_IPAD,
1036        AppleTargetKind::WatchOsSim | AppleTargetKind::WatchOsDevice => NAME_WATCHOS,
1037    };
1038    let out_dir: Option<PathBuf> = ctx.out_dir.as_ref().map(|base: &PathBuf| {
1039        if ctx.multi_target {
1040            base.join(kind_label)
1041        } else {
1042            base.clone()
1043        }
1044    });
1045    let archive_path: Option<PathBuf> = if ctx.multi_target {
1046        None
1047    } else {
1048        config
1049            .try_get_archive()
1050            .as_ref()
1051            .map(|dest: &PathBuf| resolve_against_root(&ctx.workspace_root, dest))
1052    };
1053    let apple_render: RenderArg = config.get_render().unwrap_or(RenderArg::Hardware);
1054    let mut apple_cfg: AppleBuildConfig = AppleBuildConfig::default();
1055    let _: &mut AppleBuildConfig = apple_cfg
1056        .set_workspace_root(ctx.workspace_root.clone())
1057        .set_target_kind(kind)
1058        .set_render_mode(apple_render)
1059        .set_app_version(Some(ctx.version.clone()))
1060        .set_bundle_id(ctx.bundle_id.clone())
1061        .set_out_dir(out_dir)
1062        .set_archive_path(archive_path)
1063        .set_sim_udid(config.try_get_device().clone())
1064        .set_release(config.get_release())
1065        .set_no_launch(config.get_no_launch());
1066    let custom_icon: Option<&Path> = ctx.icon_path.as_deref();
1067    let icon_writer: &MobileIconWriter<'_> =
1068        &|path: &Path, size: u32| -> io::Result<()> { write_icon_png(path, size, custom_icon) };
1069    let report: AppleBuildReport = build_apple_bundle(&apple_cfg, Some(icon_writer))?;
1070    let archive_str: Option<String> = report
1071        .try_get_archive_path()
1072        .as_ref()
1073        .map(|path: &PathBuf| path.display().to_string());
1074    let manifest_path: Option<String> = match report.get_app_bundle_path().parent() {
1075        Some(parent) => maybe_write_dir_manifest(
1076            parent,
1077            &ctx.version,
1078            config.get_manifest(),
1079            config.get_verify(),
1080        )?,
1081        None => None,
1082    };
1083    let detail: String = format!(
1084        "{} ({})",
1085        report.get_app_bundle_path().display(),
1086        format_bytes_human(report.get_binary_bytes())
1087    );
1088    Ok(make_passed_outcome(
1089        report.get_target_kind().clone(),
1090        0,
1091        Some(report.get_app_bundle_path().display().to_string()),
1092        archive_str,
1093        manifest_path,
1094        detail,
1095    ))
1096}
1097
1098/// Dispatches HarmonyOS and HarmonyOS PC builds to `builder::ecosystem::build_harmony_app`.
1099///
1100/// # Arguments
1101///
1102/// - `TargetArg` - `Harmony` or `HarmonyPc`.
1103/// - `&BuildPipelineConfig` - Pipeline configuration.
1104/// - `&ResolvedPipelineContext` - Shared resolved pipeline context.
1105///
1106/// # Returns
1107///
1108/// - `io::Result<TargetBuildOutcome>` - Built HarmonyOS outcome.
1109fn dispatch_harmony_target(
1110    target: TargetArg,
1111    config: &BuildPipelineConfig,
1112    ctx: &ResolvedPipelineContext,
1113) -> io::Result<TargetBuildOutcome> {
1114    let device_kind: HarmonyDeviceKind = if target == TargetArg::HarmonyPc {
1115        HarmonyDeviceKind::Pc2In1
1116    } else {
1117        match config.get_form_factor() {
1118            HarmonyFormFactorArg::Phone => HarmonyDeviceKind::Phone,
1119            HarmonyFormFactorArg::Tablet => HarmonyDeviceKind::Tablet,
1120            HarmonyFormFactorArg::Pc => HarmonyDeviceKind::Pc2In1,
1121            HarmonyFormFactorArg::Foldable => HarmonyDeviceKind::Foldable,
1122            HarmonyFormFactorArg::Tv => HarmonyDeviceKind::Tv,
1123            HarmonyFormFactorArg::Car => HarmonyDeviceKind::Car,
1124            HarmonyFormFactorArg::Wearable => HarmonyDeviceKind::Wearable,
1125        }
1126    };
1127    let mut abis: Vec<HarmonyAbi> = Vec::new();
1128    for raw_abi in config.get_abis().iter() {
1129        let lower: String = raw_abi.trim().to_ascii_lowercase();
1130        if lower == PIPELINE_ABI_ARM64 || lower == PIPELINE_ABI_ARM64_ALT {
1131            abis.push(HarmonyAbi::Arm64V8a);
1132        } else if lower == PIPELINE_ABI_X86_64 || lower == PIPELINE_ABI_X64 {
1133            abis.push(HarmonyAbi::X86_64);
1134        } else {
1135            return Err(Error::new(
1136                ErrorKind::InvalidInput,
1137                format!("{PIPELINE_ERR_UNSUPPORTED_HARMONY_ABI}: {raw_abi}"),
1138            ));
1139        }
1140    }
1141    let label: &str = if target == TargetArg::HarmonyPc {
1142        NAME_HARMONY_PC
1143    } else {
1144        NAME_HARMONY
1145    };
1146    let out_dir: Option<PathBuf> = ctx.out_dir.as_ref().map(|base: &PathBuf| {
1147        if ctx.multi_target {
1148            base.join(label)
1149        } else {
1150            base.clone()
1151        }
1152    });
1153    let mut harmony_cfg: HarmonyBuildConfig = HarmonyBuildConfig::default();
1154    let _: &mut HarmonyBuildConfig = harmony_cfg
1155        .set_workspace_root(ctx.workspace_root.clone())
1156        .set_device_kind(device_kind)
1157        .set_abis(abis)
1158        .set_app_version(Some(ctx.version.clone()))
1159        .set_out_dir(out_dir)
1160        .set_install_hap(config.get_install());
1161    let custom_icon: Option<&Path> = ctx.icon_path.as_deref();
1162    let icon_writer: &MobileIconWriter<'_> =
1163        &|path: &Path, size: u32| -> io::Result<()> { write_icon_png(path, size, custom_icon) };
1164    let report: HarmonyBuildReport = build_harmony_app(&harmony_cfg, Some(icon_writer))?;
1165    let artifact_path: PathBuf = report
1166        .try_get_hap_path()
1167        .clone()
1168        .unwrap_or_else(|| report.get_out_dir().clone());
1169    let archive_str: Option<String> =
1170        maybe_archive_ecosystem_dir(report.get_out_dir(), config, ctx)?;
1171    let manifest_path: Option<String> = maybe_write_dir_manifest(
1172        report.get_out_dir(),
1173        &ctx.version,
1174        config.get_manifest(),
1175        config.get_verify(),
1176    )?;
1177    let detail: String = format!(
1178        "{} ({} native .so)",
1179        artifact_path.display(),
1180        report.get_compiled_so_paths().len()
1181    );
1182    Ok(make_passed_outcome(
1183        label.to_string(),
1184        0,
1185        Some(artifact_path.display().to_string()),
1186        archive_str,
1187        manifest_path,
1188        detail,
1189    ))
1190}
1191
1192/// Dispatches wearable smartwatch targets to `builder::ecosystem::build_wearable_targets` with `write_icon_png`.
1193///
1194/// # Arguments
1195///
1196/// - `TargetArg` - Concrete wearable target.
1197/// - `&BuildPipelineConfig` - Pipeline configuration.
1198/// - `&ResolvedPipelineContext` - Shared resolved pipeline context.
1199///
1200/// # Returns
1201///
1202/// - `io::Result<TargetBuildOutcome>` - Built wearable outcome.
1203fn dispatch_wearable_target(
1204    target: TargetArg,
1205    config: &BuildPipelineConfig,
1206    ctx: &ResolvedPipelineContext,
1207) -> io::Result<TargetBuildOutcome> {
1208    let vendors: Vec<WearableVendor> = match target {
1209        TargetArg::HarmonyWearable => vec![WearableVendor::HarmonyWatch],
1210        TargetArg::Vela => vec![WearableVendor::Vela],
1211        TargetArg::VivoWatch => vec![WearableVendor::VivoWatch],
1212        TargetArg::OppoWatch => vec![WearableVendor::OppoWatch],
1213        TargetArg::Garmin => vec![WearableVendor::Garmin],
1214        TargetArg::Zeppos => vec![WearableVendor::ZeppOs],
1215        _ => Vec::new(),
1216    };
1217    let label: String = spec_for_platform(target).get_name().clone();
1218    let out_base: Option<PathBuf> = ctx.out_dir.as_ref().map(|base: &PathBuf| {
1219        if ctx.multi_target {
1220            base.join(&label)
1221        } else {
1222            base.clone()
1223        }
1224    });
1225    let mut wearable_cfg: WearableBuildConfig = WearableBuildConfig::default();
1226    let _: &mut WearableBuildConfig = wearable_cfg
1227        .set_workspace_root(ctx.workspace_root.clone())
1228        .set_vendors(vendors)
1229        .set_app_version(Some(ctx.version.clone()))
1230        .set_out_base(out_base)
1231        .set_release(config.get_release())
1232        .set_install(config.get_install())
1233        .set_skip_wasm_opt(ctx.skip_wasm_opt);
1234    let custom_icon: Option<&Path> = ctx.icon_path.as_deref();
1235    let icon_writer: &MobileIconWriter<'_> =
1236        &|path: &Path, size: u32| -> io::Result<()> { write_icon_png(path, size, custom_icon) };
1237    let report: WearableBuildReport = build_wearable_targets(&wearable_cfg, Some(icon_writer))?;
1238    let primary_path: Option<PathBuf> = report.get_generated_paths().first().cloned();
1239    let archive_str: Option<String> = match primary_path.as_deref() {
1240        Some(dir) if dir.is_dir() => maybe_archive_ecosystem_dir(dir, config, ctx)?,
1241        _ => None,
1242    };
1243    let manifest_path: Option<String> = match primary_path.as_deref() {
1244        Some(dir) if dir.is_dir() => maybe_write_dir_manifest(
1245            dir,
1246            &ctx.version,
1247            config.get_manifest(),
1248            config.get_verify(),
1249        )?,
1250        _ => None,
1251    };
1252    let artifact_str: Option<String> = primary_path.map(|path: PathBuf| path.display().to_string());
1253    let detail: String = format!(
1254        "{} target(s) generated (wasm_bundled={})",
1255        report.get_generated_paths().len(),
1256        report.get_wasm_bundled()
1257    );
1258    Ok(make_passed_outcome(
1259        label,
1260        0,
1261        artifact_str,
1262        archive_str,
1263        manifest_path,
1264        detail,
1265    ))
1266}
1267
1268/// Dispatches MiniApp targets across all 13 vendors to `builder::ecosystem::build_miniapp_targets`.
1269///
1270/// # Arguments
1271///
1272/// - `TargetArg` - Concrete MiniApp target.
1273/// - `&BuildPipelineConfig` - Pipeline configuration.
1274/// - `&ResolvedPipelineContext` - Shared resolved pipeline context.
1275///
1276/// # Returns
1277///
1278/// - `io::Result<TargetBuildOutcome>` - Built MiniApp outcome.
1279fn dispatch_miniapp_target(
1280    target: TargetArg,
1281    config: &BuildPipelineConfig,
1282    ctx: &ResolvedPipelineContext,
1283) -> io::Result<TargetBuildOutcome> {
1284    let vendor: MiniAppVendor = match target {
1285        TargetArg::Wechat => MiniAppVendor::Wechat,
1286        TargetArg::Alipay => MiniAppVendor::Alipay,
1287        TargetArg::Douyin => MiniAppVendor::Douyin,
1288        TargetArg::Baidu => MiniAppVendor::Baidu,
1289        TargetArg::Qq => MiniAppVendor::Qq,
1290        TargetArg::Kuaishou => MiniAppVendor::Kuaishou,
1291        TargetArg::Jd => MiniAppVendor::Jd,
1292        TargetArg::Xhs => MiniAppVendor::Xhs,
1293        TargetArg::Dingtalk => MiniAppVendor::Dingtalk,
1294        TargetArg::Feishu => MiniAppVendor::Feishu,
1295        TargetArg::Taobao => MiniAppVendor::Taobao,
1296        TargetArg::Meituan => MiniAppVendor::Meituan,
1297        _ => MiniAppVendor::HarmonyAtomic,
1298    };
1299    let label: String = spec_for_platform(target).get_name().clone();
1300    let out_base: Option<PathBuf> = ctx.out_dir.as_ref().map(|base: &PathBuf| {
1301        if ctx.multi_target {
1302            base.join(&label)
1303        } else {
1304            base.clone()
1305        }
1306    });
1307    let mut miniapp_cfg: MiniAppBuildConfig = MiniAppBuildConfig::default();
1308    let _: &mut MiniAppBuildConfig = miniapp_cfg
1309        .set_workspace_root(ctx.workspace_root.clone())
1310        .set_vendors(vec![vendor])
1311        .set_app_version(Some(ctx.version.clone()))
1312        .set_out_base(out_base)
1313        .set_release(config.get_release())
1314        .set_skip_wasm_opt(ctx.skip_wasm_opt);
1315    let custom_icon: Option<&Path> = ctx.icon_path.as_deref();
1316    let icon_writer: &MobileIconWriter<'_> =
1317        &|path: &Path, size: u32| -> io::Result<()> { write_icon_png(path, size, custom_icon) };
1318    let report: MiniAppBuildReport = build_miniapp_targets(&miniapp_cfg, Some(icon_writer))?;
1319    let primary_dir: Option<PathBuf> = report.get_generated_dirs().first().cloned();
1320    let archive_str: Option<String> = match primary_dir.as_deref() {
1321        Some(dir) => maybe_archive_ecosystem_dir(dir, config, ctx)?,
1322        None => None,
1323    };
1324    let manifest_path: Option<String> = match primary_dir.as_deref() {
1325        Some(dir) => maybe_write_dir_manifest(
1326            dir,
1327            &ctx.version,
1328            config.get_manifest(),
1329            config.get_verify(),
1330        )?,
1331        None => None,
1332    };
1333    let artifact_str: Option<String> = primary_dir.map(|path: PathBuf| path.display().to_string());
1334    let detail: String = format!(
1335        "{} vendor dir(s) (wasm_bundled={})",
1336        report.get_generated_dirs().len(),
1337        report.get_wasm_bundled()
1338    );
1339    Ok(make_passed_outcome(
1340        label,
1341        0,
1342        artifact_str,
1343        archive_str,
1344        manifest_path,
1345        detail,
1346    ))
1347}
1348
1349/// Dispatches QuickApp targets to `builder::ecosystem::build_quickapp_targets`.
1350///
1351/// # Arguments
1352///
1353/// - `TargetArg` - `Quickapp`, `QuickappAlliance`, or `QuickappHuawei`.
1354/// - `&BuildPipelineConfig` - Pipeline configuration.
1355/// - `&ResolvedPipelineContext` - Shared resolved pipeline context.
1356///
1357/// # Returns
1358///
1359/// - `io::Result<TargetBuildOutcome>` - Built QuickApp outcome.
1360fn dispatch_quickapp_target(
1361    target: TargetArg,
1362    config: &BuildPipelineConfig,
1363    ctx: &ResolvedPipelineContext,
1364) -> io::Result<TargetBuildOutcome> {
1365    let vendors: Vec<QuickAppVendor> = match target {
1366        TargetArg::QuickappAlliance => vec![QuickAppVendor::Alliance],
1367        TargetArg::QuickappHuawei => vec![QuickAppVendor::Huawei],
1368        _ => Vec::new(),
1369    };
1370    let label: String = spec_for_platform(target).get_name().clone();
1371    let out_base: Option<PathBuf> = ctx.out_dir.as_ref().map(|base: &PathBuf| {
1372        if ctx.multi_target {
1373            base.join(&label)
1374        } else {
1375            base.clone()
1376        }
1377    });
1378    let mut quickapp_cfg: QuickAppBuildConfig = QuickAppBuildConfig::default();
1379    let _: &mut QuickAppBuildConfig = quickapp_cfg
1380        .set_workspace_root(ctx.workspace_root.clone())
1381        .set_vendors(vendors)
1382        .set_app_version(Some(ctx.version.clone()))
1383        .set_out_base(out_base)
1384        .set_release(config.get_release())
1385        .set_skip_wasm_opt(ctx.skip_wasm_opt);
1386    let custom_icon: Option<&Path> = ctx.icon_path.as_deref();
1387    let icon_writer: &MobileIconWriter<'_> =
1388        &|path: &Path, size: u32| -> io::Result<()> { write_icon_png(path, size, custom_icon) };
1389    let report: QuickAppBuildReport = build_quickapp_targets(&quickapp_cfg, Some(icon_writer))?;
1390    let primary_dir: Option<PathBuf> = report.get_generated_dirs().first().cloned();
1391    let archive_str: Option<String> = match primary_dir.as_deref() {
1392        Some(dir) => maybe_archive_ecosystem_dir(dir, config, ctx)?,
1393        None => None,
1394    };
1395    let manifest_path: Option<String> = match primary_dir.as_deref() {
1396        Some(dir) => maybe_write_dir_manifest(
1397            dir,
1398            &ctx.version,
1399            config.get_manifest(),
1400            config.get_verify(),
1401        )?,
1402        None => None,
1403    };
1404    let artifact_str: Option<String> = primary_dir.map(|path: PathBuf| path.display().to_string());
1405    let detail: String = format!(
1406        "{} QuickApp dir(s) (wasm_bundled={})",
1407        report.get_generated_dirs().len(),
1408        report.get_wasm_bundled()
1409    );
1410    Ok(make_passed_outcome(
1411        label,
1412        0,
1413        artifact_str,
1414        archive_str,
1415        manifest_path,
1416        detail,
1417    ))
1418}
1419
1420/// Archives an ecosystem output directory when `--archive` is requested on a single-target run.
1421///
1422/// # Arguments
1423///
1424/// - `&Path` - Generated ecosystem directory.
1425/// - `&BuildPipelineConfig` - Pipeline configuration.
1426/// - `&ResolvedPipelineContext` - Shared resolved pipeline context.
1427///
1428/// # Returns
1429///
1430/// - `io::Result<Option<String>>` - Written archive path string when created.
1431fn maybe_archive_ecosystem_dir(
1432    dir: &Path,
1433    config: &BuildPipelineConfig,
1434    ctx: &ResolvedPipelineContext,
1435) -> io::Result<Option<String>> {
1436    if ctx.multi_target {
1437        return Ok(None);
1438    }
1439    let Some(archive_dest) = config.try_get_archive() else {
1440        return Ok(None);
1441    };
1442    let resolved_dest: PathBuf = if archive_dest.is_absolute() {
1443        archive_dest.clone()
1444    } else {
1445        ctx.workspace_root.join(archive_dest)
1446    };
1447    let _: u64 = archive_directory_auto(dir, &resolved_dest, None)?;
1448    Ok(Some(resolved_dest.display().to_string()))
1449}
1450
1451/// Constructs a `TargetBuildStatus::Passed` outcome populated with optional artifact, archive, and manifest paths.
1452///
1453/// # Arguments
1454///
1455/// - `String` - Canonical target name.
1456/// - `u64` - Elapsed build duration in milliseconds.
1457/// - `Option<String>` - Primary generated artifact or directory path.
1458/// - `Option<String>` - Optional generated archive path.
1459/// - `Option<String>` - Optional generated `euv-release.json` manifest path.
1460/// - `String` - Human-readable outcome summary detail.
1461///
1462/// # Returns
1463///
1464/// - `TargetBuildOutcome` - Populated passed target outcome.
1465fn make_passed_outcome(
1466    target: String,
1467    elapsed_ms: u64,
1468    artifact_path: Option<String>,
1469    archive_path: Option<String>,
1470    manifest_path: Option<String>,
1471    detail: String,
1472) -> TargetBuildOutcome {
1473    let mut outcome: TargetBuildOutcome =
1474        TargetBuildOutcome::new(target, TargetBuildStatus::Passed, elapsed_ms, detail);
1475    let _: &mut TargetBuildOutcome = outcome
1476        .set_artifact_path(artifact_path)
1477        .set_archive_path(archive_path)
1478        .set_manifest_path(manifest_path);
1479    outcome
1480}