Skip to main content

proa_cli/
lifecycle.rs

1// Copyright Proa Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{
5    collections::{BTreeMap, BTreeSet},
6    env,
7    ffi::{OsStr, OsString},
8    fs, io,
9    path::{Path, PathBuf},
10    process::{Child, Command, ExitStatus},
11    sync::{
12        atomic::{AtomicBool, AtomicU64, Ordering},
13        Arc,
14    },
15    thread,
16    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
17};
18
19use anyhow::{bail, Context, Result};
20use rsjs_ir::{
21    abi::{AbiVersion, ProducerVersion, SemanticHash},
22    build::{
23        ArtifactRole, BuildToolchain, DeclaredEnvironmentInput, InvocationSpec, RequestedRootTarget,
24    },
25};
26use rsjs_transport::TRANSPORT_FORMAT_VERSION;
27use serde::Deserialize;
28use sha2::{Digest, Sha256};
29
30mod dev_ui;
31mod public_assets;
32mod readiness;
33mod reload;
34
35pub(crate) use public_assets::load_start_manifest;
36
37use reload::{ReloadEvent, ReloadServer};
38
39#[cfg(not(windows))]
40use crate::rsjs::final_compile::snapshot_wrapper_executable;
41use crate::{
42    commands::{db, script, task},
43    config::{
44        load_project_config, AssetConfig, ProjectConfig, DEFAULT_BUILD_COMMAND, DEFAULT_DEV_COMMAND,
45    },
46    diagnostic::Severity,
47    rsjs::build::{
48        DescriptorCargoRequest, DESCRIPTOR_TARGET_POLICY_VERSION,
49        DESCRIPTOR_UNIT_SIDECAR_SCHEMA_VERSION, TOOL_NAMESPACE_DIR,
50    },
51    rsjs::cache::DESCRIPTOR_CACHE_SCHEMA_VERSION,
52    rsjs::final_compile::{prune_final_artifact_snapshot, FinalSnapshotLease},
53    rsjs::pipeline::{
54        run_linked_cargo_cached, run_linked_cargo_cached_with_progress,
55        try_run_optimistic_empty_linked_cargo, DescriptorRootSelector, LinkedCargoOutput,
56        LinkedCargoRequest, LinkedCargoStage, OptimisticLinkedCargoOutcome,
57    },
58    scaffold,
59};
60
61static RSJS_BUILD_NONCE: AtomicU64 = AtomicU64::new(0);
62static TEST_INTERRUPTED: AtomicBool = AtomicBool::new(false);
63const RSJS_COMPILER_ABI: AbiVersion = AbiVersion::new(1, 1);
64const RSJS_RUNTIME_PROTOCOL: AbiVersion = AbiVersion::new(1, 0);
65const RSJS_COMPILER_PRODUCER: ProducerVersion = ProducerVersion::new(0, 2, 0);
66const RSJS_WRAPPER_EXECUTABLE_FINGERPRINT_DOMAIN: &[u8] = b"proa.rsjs.wrapper-executable.v1\0";
67const PERSISTENT_DESCRIPTOR_TARGET_LAYOUT_VERSION: u16 = 1;
68const DEV_WATCH_POLL: Duration = Duration::from_millis(50);
69/// Editors write in bursts (temp file, rename, mtime touch) and formatters
70/// rewrite whole trees, so the loop waits for one quiet window before paying
71/// for a Cargo cycle. Vite and webpack sit in the same 100-300ms range.
72pub const DEV_WATCH_DEBOUNCE: Duration = Duration::from_millis(100);
73/// Refuse debounce windows shorter than one poll interval: they would claim a
74/// precision the poller cannot deliver.
75const DEV_WATCH_MIN_DEBOUNCE: Duration = DEV_WATCH_POLL;
76/// How long startup and restart probes wait for the server. A startup timeout
77/// leaves the browser closed and a restart timeout reports a failed reload.
78const DEV_READY_TIMEOUT: Duration = Duration::from_secs(20);
79
80pub struct DevOptions {
81    pub root: Option<PathBuf>,
82    pub host: Option<String>,
83    pub port: Option<u16>,
84    pub watch: Vec<PathBuf>,
85    pub open: bool,
86    pub offline: bool,
87    pub no_assets: bool,
88    pub hot_static: bool,
89    pub no_restart: bool,
90    pub no_reload: bool,
91    pub no_css_hot_swap: bool,
92    pub reload_port: Option<u16>,
93    pub debounce_ms: Option<u64>,
94    pub verbose: bool,
95    pub command: Vec<String>,
96}
97
98pub struct BuildOptions {
99    pub root: Option<PathBuf>,
100    pub profile: Option<String>,
101    pub package: Option<String>,
102    pub bin: Option<String>,
103    pub example: Option<String>,
104    pub target: Option<String>,
105    pub features: Vec<String>,
106    pub all_features: bool,
107    pub no_default_features: bool,
108    pub locked: bool,
109    pub offline: bool,
110    pub no_check: bool,
111    pub no_assets: bool,
112    pub artifact_out: Option<PathBuf>,
113    pub command: Vec<String>,
114}
115
116pub struct CheckOptions {
117    pub root: Option<PathBuf>,
118    pub profile: Option<String>,
119    pub package: Option<String>,
120    pub bin: Option<String>,
121    pub target: Option<String>,
122    pub features: Vec<String>,
123    pub all_features: bool,
124    pub no_default_features: bool,
125    pub locked: bool,
126    pub offline: bool,
127}
128
129pub struct RunOptions {
130    pub root: Option<PathBuf>,
131    pub profile: Option<String>,
132    pub package: Option<String>,
133    pub bin: Option<String>,
134    pub target: Option<String>,
135    pub features: Vec<String>,
136    pub all_features: bool,
137    pub no_default_features: bool,
138    pub locked: bool,
139    pub offline: bool,
140    pub arguments: Vec<String>,
141}
142
143#[derive(Clone)]
144pub struct TestOptions {
145    pub root: Option<PathBuf>,
146    pub profile: Option<String>,
147    pub package: Option<String>,
148    pub bin: Option<String>,
149    pub test: Option<String>,
150    pub target: Option<String>,
151    pub features: Vec<String>,
152    pub all_features: bool,
153    pub no_default_features: bool,
154    pub locked: bool,
155    pub offline: bool,
156    pub watch: bool,
157    pub watch_paths: Vec<PathBuf>,
158    pub keep_database: bool,
159    pub arguments: Vec<String>,
160}
161
162#[derive(Debug)]
163struct LinkedDevLaunch {
164    executable: PathBuf,
165    arguments: Vec<OsString>,
166    plan_id: String,
167    single_pass: bool,
168    descriptor_artifacts: usize,
169    reused_descriptor_artifacts: usize,
170    reused_final_artifacts: usize,
171    public_assets: Option<PathBuf>,
172    compiled_inputs: Option<BTreeSet<PathBuf>>,
173    /// Keeps `executable` from being pruned by another session while this
174    /// launch is current. Dropped before this session prunes it.
175    _snapshot_lease: Option<Arc<FinalSnapshotLease>>,
176}
177
178/// State that one `proa dev` watch session carries between rebuilds.
179///
180/// Tool versions are deliberately not cached: they run in parallel with
181/// `cargo metadata`, so caching saves no wall time, and a toolchain switch
182/// mid-session would otherwise key new artifacts under the old toolchain.
183#[derive(Debug, Default)]
184struct DevSessionCache {
185    allow_optimistic_empty: bool,
186    #[cfg(not(windows))]
187    wrapper_snapshot: Option<CachedWrapperSnapshot>,
188}
189
190#[cfg(not(windows))]
191#[derive(Debug, Clone)]
192struct CachedWrapperSnapshot {
193    source_path: PathBuf,
194    source_stamp: FileStamp,
195    snapshot_root: PathBuf,
196    snapshot_path: PathBuf,
197    fingerprint: String,
198}
199
200impl DevSessionCache {
201    fn for_dev_watch(root: &Path) -> Self {
202        Self {
203            allow_optimistic_empty: !project_mentions_rsjs_macros(root),
204            #[cfg(not(windows))]
205            wrapper_snapshot: None,
206        }
207    }
208}
209
210struct LinkedDevRebuild {
211    config: ProjectConfig,
212    snapshot: WatchSnapshot,
213    launch: LinkedDevLaunch,
214    hot_state: Option<crate::hot_static::HotState>,
215}
216
217pub fn dev(options: DevOptions) -> Result<()> {
218    // A one-shot run has no change cycles to summarize.
219    dev_ui::enable(options.verbose || options.no_restart);
220    let root = absolute_project_root(scaffold::resolve_root(options.root.clone())?)?;
221    let mut runner = crate::config::DevConfigRunner::default();
222    let mut config = crate::config::load_project_config_with_runner(&root, Some(&mut runner))?;
223    script::hint("dev", &config.scripts.dev, DEFAULT_DEV_COMMAND);
224    let listen = resolve_dev_address(options.host.as_deref(), options.port, |name| {
225        std::env::var(name).ok()
226    })?;
227    let address = (listen.host.as_str(), listen.port);
228    // Reject an impossible watch window before anything is built, bound, or
229    // spawned. A flag error should cost nothing to recover from.
230    let debounce = dev_watch_debounce(&options)?;
231    let command = dev_command(&options, &config);
232    install_dev_signal_handler();
233
234    dev_ui::header(&dev_url(address.0, address.1));
235    dev_ui::detail!("Proa dev root: {}", root.display());
236    for note in &listen.notes {
237        dev_ui::detail!("{note}");
238    }
239    dev_ui::detail!("Building your site. The first build downloads dependencies and compiles crates; this can take several minutes.");
240    if options.open {
241        dev_ui::detail!("The browser will open when the server is ready.");
242    }
243    task::run_lifecycle_tasks(&root, &config, &config.scripts.before.dev, &BTreeMap::new())?;
244
245    if options.no_restart {
246        if !options.no_assets {
247            build_assets(&root, &config)?;
248        }
249        let hot_state = hot_scan_or_rustc_diagnostics(
250            &root,
251            &config,
252            &command,
253            None,
254            options
255                .hot_static
256                .then(|| crate::hot_static::HotState::prepare(&root))
257                .transpose(),
258        )?;
259        let source = public_assets::configured_path(&config, !options.no_assets)?;
260        let launch =
261            run_linked_dev_cycle(&root, &config, &command, hot_state.as_ref(), source, None)?;
262        return run_linked_dev_foreground(&root, &launch, address.0, address.1, options.open);
263    }
264
265    // Live reload is a watch-mode feature. Without restarts there is nothing
266    // to announce, so a one-shot run never pays for the event server.
267    let reload = start_reload_server(address, &options);
268    let mut session = DevSessionCache::for_dev_watch(&root);
269
270    if !options.no_assets {
271        build_assets(&root, &config)?;
272    }
273    let mut watch_paths = dev_watch_paths(&config, &options)?;
274    let baseline = watch_snapshot(&root, &watch_paths)?;
275    let mut hot_state = hot_scan_or_rustc_diagnostics(
276        &root,
277        &config,
278        &command,
279        None,
280        options
281            .hot_static
282            .then(|| crate::hot_static::HotState::prepare(&root))
283            .transpose(),
284    )?;
285    let source = public_assets::configured_path(&config, !options.no_assets)?;
286    let mut launch = run_linked_dev_cycle(
287        &root,
288        &config,
289        &command,
290        hot_state.as_ref(),
291        source,
292        Some(&mut session),
293    )?;
294    let mut child = spawn_linked_dev(&root, &launch, address.0, address.1, reload.as_ref())?;
295    announce_dev_start(options.open, address.0, address.1, &mut child);
296
297    let clock = Instant::now();
298    let mut debouncer = DevWatchDebouncer::new(baseline, debounce);
299    let mut retry_catalog_at = Instant::now();
300    let mut last_build_failed = false;
301
302    loop {
303        if let Some(status) = child.process.try_wait().context("poll linked dev server")? {
304            clear_active_child_group();
305            return exit_status_to_result(status, "linked dev server");
306        }
307
308        thread::sleep(debouncer.next_poll_delay(clock.elapsed()));
309        let current = watch_snapshot(&root, &watch_paths)?;
310        // Observe only disappearance. Publishing atomically replaces the manifest,
311        // and neither that write nor ordinary Cargo activity should trigger a build.
312        let missing_catalog = launch
313            .public_assets
314            .as_ref()
315            .is_some_and(|output| !output.join(proa_assets::MANIFEST_FILE).is_file());
316        let trigger_snapshot = match debouncer.observe(clock.elapsed(), current) {
317            DevWatchDecision::Ready(changed) => changed,
318            // Disappearing output can trigger recovery on idle inputs, but a
319            // failed build already recorded those inputs. A later edit must
320            // take the normal debounced path before attempting another build.
321            DevWatchDecision::Idle
322                if missing_catalog && !last_build_failed && Instant::now() >= retry_catalog_at =>
323            {
324                retry_catalog_at = Instant::now() + Duration::from_secs(2);
325                if launch.executable.is_file() {
326                    let output = launch
327                        .public_assets
328                        .as_ref()
329                        .expect("missing active catalog");
330                    let source = public_assets::configured_path(&config, true)?;
331                    match public_assets::publish(&root, source, output) {
332                        Ok(Some(_)) => {
333                            dev_ui::detail!("restored the public asset catalog without Cargo");
334                            dev_ui::outcome("Public assets restored");
335                            // A recreated catalog has a new reader lock. Reopen it.
336                            child.restart(&root, &launch, address, None, reload.as_ref())?;
337                            retry_catalog_at = Instant::now();
338                            continue;
339                        }
340                        Ok(None) => {}
341                        Err(error) => {
342                            eprintln!("could not restore the public asset catalog: {error:#}");
343                            notify(reload.as_ref(), &ReloadEvent::Failed(format!("{error:#}")));
344                            continue;
345                        }
346                    }
347                }
348                // Rebuild when the executable or the default public directory vanished.
349                debouncer.committed.clone()
350            }
351            _ => continue,
352        };
353
354        notify(reload.as_ref(), &ReloadEvent::Building);
355        dev_ui::changed(&changed_paths(&debouncer.committed, &trigger_snapshot));
356        let mut failure_snapshot = trigger_snapshot;
357        // The cached runner rechecks rustc's recorded inputs and Cargo settings
358        // itself, so any edit that leaves them untouched skips the runner build.
359        let evaluated = crate::config::load_project_config_with_runner(&root, Some(&mut runner));
360        let inputs = evaluated.and_then(|next| {
361            prepare_dev_inputs_with_compiled_inputs(
362                &root,
363                next,
364                &options,
365                &debouncer.committed,
366                hot_state.as_ref(),
367                launch.compiled_inputs.as_ref(),
368                &mut failure_snapshot,
369                &mut watch_paths,
370                if last_build_failed {
371                    AssetState::Unknown
372                } else {
373                    AssetState::Current
374                },
375            )
376        });
377        let inputs = match inputs {
378            Ok(inputs) => inputs,
379            Err(error) => {
380                last_build_failed = true;
381                if dev_ui::pretty() {
382                    dev_ui::fail("Could not prepare the build", Some(&format!("{error:#}")));
383                } else {
384                    eprintln!(
385                        "dev preparation failed; keeping the last valid server running:\n{error:#}"
386                    );
387                }
388                notify(reload.as_ref(), &ReloadEvent::Failed(format!("{error:#}")));
389                debouncer.commit(failure_snapshot);
390                continue;
391            }
392        };
393        let PreparedDevInputs {
394            config: next_config,
395            snapshot,
396            css_only,
397            public_assets_only,
398            changed_asset_paths,
399            hot_update,
400            deferred_assets,
401        } = inputs;
402        if css_only && !missing_catalog {
403            dev_ui::detail!("stylesheet change stabilized; rebuilt assets without restarting");
404            dev_ui::outcome("Styles updated");
405            dev_ui::finish();
406            debouncer.commit(snapshot);
407            notify(reload.as_ref(), &ReloadEvent::Css);
408            continue;
409        }
410        if public_assets_only
411            && !last_build_failed
412            && serde_json::to_vec(&next_config).ok() == serde_json::to_vec(&config).ok()
413            && launch.executable.is_file()
414            && launch.compiled_inputs.as_ref().is_some_and(|inputs| {
415                changed_asset_paths
416                    .iter()
417                    .all(|path| !is_compiled_input(&root, inputs, path))
418            })
419        {
420            if let Some(output) = launch.public_assets.as_ref() {
421                let source = public_assets::configured_path(&next_config, !options.no_assets)?;
422                match public_assets::publish(&root, source, output) {
423                    Ok(Some(_)) => {
424                        let stylesheet_only = is_stylesheet_only_change(&changed_asset_paths);
425                        dev_ui::outcome(if stylesheet_only {
426                            "Styles updated"
427                        } else {
428                            "Assets updated"
429                        });
430                        // Only a server that registered as a live reader
431                        // follows this publication. One that loaded a fixed
432                        // catalog, was built against a framework release
433                        // without in-place reloading, has exited, or is still
434                        // starting would keep serving the previous files, so
435                        // it is restarted exactly as before.
436                        let can_hot_swap = !(stylesheet_only && options.no_css_hot_swap)
437                            && public_assets::has_live_reader(output);
438                        if can_hot_swap {
439                            dev_ui::detail!(
440                                "public assets changed; republished catalog in place without restarting"
441                            );
442                            dev_ui::finish();
443                            debouncer.commit(snapshot);
444                            notify(
445                                reload.as_ref(),
446                                if stylesheet_only {
447                                    &ReloadEvent::Css
448                                } else {
449                                    &ReloadEvent::Reload
450                                },
451                            );
452                        } else {
453                            dev_ui::detail!(
454                                "public assets changed; republished catalog without Cargo"
455                            );
456                            child.restart(&root, &launch, address, None, reload.as_ref())?;
457                            debouncer.commit(snapshot);
458                        }
459                        continue;
460                    }
461                    Ok(None) => {}
462                    Err(error) => {
463                        last_build_failed = true;
464                        if dev_ui::pretty() {
465                            dev_ui::fail(
466                                "Could not publish public assets",
467                                Some(&format!("{error:#}")),
468                            );
469                        } else {
470                            eprintln!(
471                                "could not republish the public asset catalog; keeping the last valid server running:\n{error:#}"
472                            );
473                        }
474                        notify(reload.as_ref(), &ReloadEvent::Failed(format!("{error:#}")));
475                        debouncer.commit(failure_snapshot);
476                        continue;
477                    }
478                }
479            }
480        }
481        if let Some(mut update) = hot_update.filter(|_| !missing_catalog) {
482            match update.activate() {
483                Ok(()) => {
484                    dev_ui::detail!(
485                        "static template change stabilized; published without Cargo or restart"
486                    );
487                    dev_ui::outcome("Updated");
488                    dev_ui::finish();
489                    hot_state = Some(update);
490                    debouncer.commit(snapshot);
491                    notify(reload.as_ref(), &ReloadEvent::Reload);
492                    continue;
493                }
494                Err(error) => {
495                    eprintln!("static publication failed; using the linked rebuild: {error:#}")
496                }
497            }
498        }
499        dev_ui::detail!("change stabilized; rebuilding linked RSJS dev server");
500        let rebuild = (|| -> Result<LinkedDevRebuild> {
501            let command = dev_command(&options, &next_config);
502            // Capture the exact source/config state handed to this cycle after
503            // asset generation. A change during Cargo will differ on the next
504            // poll and schedule another cycle rather than being swallowed.
505            let mut cycle_snapshot = watch_snapshot(&root, &watch_paths)?;
506            failure_snapshot = cycle_snapshot.clone();
507            // Stage after tasks/assets may have generated Rust sources,
508            // and after the committed snapshot. An edit during staging or
509            // Cargo must differ from that snapshot on the next poll.
510            let next_hot_state = hot_scan_or_rustc_diagnostics(
511                &root,
512                &next_config,
513                &command,
514                hot_state.as_ref(),
515                hot_state
516                    .as_ref()
517                    .map(|state| state.candidate(&root))
518                    .transpose(),
519            )?;
520            let source = public_assets::configured_path(&next_config, !options.no_assets)?;
521            let launch = run_linked_dev_cycle_with_assets(
522                &root,
523                &next_config,
524                &command,
525                next_hot_state.as_ref(),
526                source,
527                Some(&mut session),
528                deferred_assets.as_deref(),
529            );
530            if let (Some(_), Some(public)) = (&deferred_assets, source) {
531                // Advance generated public outputs (e.g. Tailwind's CSS)
532                // written while Cargo ran, whether or not Cargo succeeded, so
533                // the next poll does not schedule a cycle for output this one
534                // already produced.
535                match watch_snapshot(&root, &watch_paths) {
536                    Ok(post_assets) => {
537                        for output in declared_asset_outputs(&next_config) {
538                            if output.starts_with(public) {
539                                if let Some(stamp) = post_assets.get(&output) {
540                                    cycle_snapshot.insert(output.clone(), *stamp);
541                                    failure_snapshot.insert(output, *stamp);
542                                }
543                            }
544                        }
545                    }
546                    Err(error) if launch.is_ok() => return Err(error),
547                    Err(_) => {}
548                }
549            }
550            let launch = launch?;
551            Ok(LinkedDevRebuild {
552                config: next_config,
553                snapshot: cycle_snapshot,
554                launch,
555                hot_state: next_hot_state,
556            })
557        })();
558
559        match rebuild {
560            Ok(LinkedDevRebuild {
561                config: next_config,
562                snapshot: cycle_snapshot,
563                launch: next_launch,
564                hot_state: mut next_hot_state,
565            }) => {
566                dev_ui::detail!(
567                    "linked dev rebuild succeeded; gracefully stopping the previous server before activating plan {}",
568                    next_launch.plan_id
569                );
570                child.restart(
571                    &root,
572                    &next_launch,
573                    address,
574                    next_hot_state.as_mut(),
575                    reload.as_ref(),
576                )?;
577                // The previous server has exited. Release its snapshot lease,
578                // then remove that snapshot unless another command holds it,
579                // so repeated saves keep one dev executable on disk.
580                let previous = std::mem::replace(&mut launch, next_launch);
581                if previous.executable != launch.executable {
582                    let superseded = previous.executable.clone();
583                    drop(previous);
584                    prune_final_artifact_snapshot(&superseded);
585                }
586                config = next_config;
587                retry_catalog_at = Instant::now();
588                last_build_failed = false;
589                hot_state = next_hot_state;
590                debouncer = DevWatchDebouncer::new(cycle_snapshot, debounce);
591            }
592            Err(error) => {
593                last_build_failed = true;
594                if dev_ui::pretty() {
595                    // The compiler already printed its own diagnostics.
596                    let detail = format!("{error:#}");
597                    let compiler = detail.contains("Cargo compilation failed")
598                        || detail.contains("compiler diagnostic above");
599                    dev_ui::fail("Build failed", (!compiler).then_some(detail.as_str()));
600                } else {
601                    eprintln!(
602                        "linked dev rebuild failed; keeping the last valid server running:\n{error:#}"
603                    );
604                }
605                notify(reload.as_ref(), &ReloadEvent::Failed(format!("{error:#}")));
606                // Do not spin on unchanged broken input. The next source,
607                // feature, cfg, or configuration change schedules a new cycle.
608                debouncer.commit(failure_snapshot);
609            }
610        }
611    }
612}
613
614struct PreparedDevInputs {
615    config: ProjectConfig,
616    snapshot: WatchSnapshot,
617    css_only: bool,
618    public_assets_only: bool,
619    changed_asset_paths: Vec<PathBuf>,
620    hot_update: Option<crate::hot_static::HotState>,
621    deferred_assets: Option<Vec<PathBuf>>,
622}
623
624/// What is known about generated assets when a change cycle starts.
625#[derive(Clone, Copy, PartialEq, Eq)]
626enum AssetState {
627    /// The previous cycle ran to completion, asset commands included.
628    Current,
629    /// The previous cycle failed somewhere. An asset command may never have
630    /// produced output for the sources as they are now, so nothing is skipped.
631    Unknown,
632}
633
634#[cfg(all(test, unix))]
635#[allow(clippy::too_many_arguments)]
636fn prepare_dev_inputs(
637    root: &Path,
638    config: ProjectConfig,
639    options: &DevOptions,
640    committed: &WatchSnapshot,
641    hot_state: Option<&crate::hot_static::HotState>,
642    failure_snapshot: &mut WatchSnapshot,
643    watch_paths: &mut Vec<PathBuf>,
644    assets: AssetState,
645) -> Result<PreparedDevInputs> {
646    prepare_dev_inputs_with_compiled_inputs(
647        root,
648        config,
649        options,
650        committed,
651        hot_state,
652        None,
653        failure_snapshot,
654        watch_paths,
655        assets,
656    )
657}
658
659#[allow(clippy::too_many_arguments)]
660fn prepare_dev_inputs_with_compiled_inputs(
661    root: &Path,
662    config: ProjectConfig,
663    options: &DevOptions,
664    committed: &WatchSnapshot,
665    hot_state: Option<&crate::hot_static::HotState>,
666    compiled_inputs: Option<&BTreeSet<PathBuf>>,
667    failure_snapshot: &mut WatchSnapshot,
668    watch_paths: &mut Vec<PathBuf>,
669    assets: AssetState,
670) -> Result<PreparedDevInputs> {
671    // Failure snapshots must use the same watch set as the next poll, even
672    // when a config edit changes watched paths and preparation then fails.
673    *watch_paths = dev_watch_paths(&config, options)?;
674    let tasks =
675        task::run_lifecycle_tasks(root, &config, &config.scripts.before.dev, &BTreeMap::new());
676    // Include generated writes from pre-dev tasks, even if a task fails. Capture
677    // before scanning/publishing templates or running asset commands so edits
678    // during those operations still schedule another cycle.
679    let mut snapshot = watch_snapshot(root, watch_paths)?;
680    *failure_snapshot = snapshot.clone();
681    tasks?;
682    let changed = changed_paths(committed, &snapshot);
683    let public = public_assets::configured_path(&config, !options.no_assets)?;
684    let managed_public = public.is_some_and(|path| {
685        path != Path::new(crate::config::DEFAULT_PUBLIC_DIRECTORY) || root.join(path).exists()
686    });
687    let mut css_only = !managed_public
688        && !options.no_css_hot_swap
689        && !options.no_assets
690        && is_stylesheet_only_change(&changed);
691    let mut hot_update = if css_only {
692        None
693    } else if let Some(state) = hot_state {
694        match state.prepare_update(root, &changed) {
695            Ok(update) => update,
696            Err(error) => {
697                eprintln!("static update rejected; using the linked rebuild: {error:#}");
698                None
699            }
700        }
701    } else {
702        None
703    };
704    let generated_public_before = if hot_update.is_some() {
705        public
706            .filter(|public| !changed.iter().any(|path| path.starts_with(public)))
707            .map(|public| snapshot_generated_public_outputs(root, &config, public, &snapshot))
708            .transpose()?
709    } else {
710        None
711    };
712    let defer_assets = !options.no_assets
713        && !css_only
714        && hot_update.is_none()
715        && assets == AssetState::Current
716        && can_defer_assets_for_parallel_cargo(root, &config, public, &changed, compiled_inputs);
717    if !options.no_assets && !defer_assets {
718        let skippable = public.filter(|_| assets == AssetState::Current);
719        build_assets_for_change(root, &config, skippable, &changed)?;
720    }
721    let mut public_assets_only = false;
722    let mut changed_asset_paths = Vec::new();
723    if let Some(public) = public {
724        if !defer_assets {
725            let post_assets = if managed_public || root.join(public).exists() {
726                Some(watch_snapshot(root, watch_paths)?)
727            } else {
728                None
729            };
730            let post_changed = post_assets
731                .as_ref()
732                .map(|post_assets| changed_paths(committed, post_assets));
733            let changed_public: Vec<&PathBuf> = post_changed
734                .as_deref()
735                .unwrap_or(&changed)
736                .iter()
737                .filter(|path| path.starts_with(public))
738                .collect();
739            let public_changed = if changed_public.is_empty() {
740                false
741            } else if let (Some(before), Some(post_assets)) =
742                (&generated_public_before, &post_assets)
743            {
744                if all_unchanged_generated_outputs(root, &changed_public, before, post_assets)? {
745                    // Declared asset outputs (such as Tailwind's stylesheet) may be
746                    // rewritten with identical bytes and a newer mtime. Advance only
747                    // those verified stamps so authored saves are never swallowed.
748                    for path in &changed_public {
749                        if let Some(stamp) = post_assets.get(*path) {
750                            snapshot.insert((*path).clone(), *stamp);
751                        }
752                    }
753                    false
754                } else {
755                    true
756                }
757            } else {
758                true
759            };
760            if public_changed {
761                // The running server holds a fixed public catalog. Restart it when
762                // inputs (including generated files) change. Keep the pre-command
763                // snapshot for authored files outside `public/` so concurrent edits
764                // still schedule another cycle.
765                hot_update = None;
766                css_only = false;
767                if managed_public
768                    && !changed.is_empty()
769                    && changed
770                        .iter()
771                        .all(|path| is_css_or_public_or_asset_input(path, public, &config))
772                    && post_changed
773                        .as_deref()
774                        .unwrap_or(&changed)
775                        .iter()
776                        .all(|path| is_css_or_public_or_asset_input(path, public, &config))
777                {
778                    public_assets_only = true;
779                    changed_asset_paths = changed.clone();
780                    if let Some(post_changed) = &post_changed {
781                        for path in post_changed {
782                            if !changed_asset_paths.contains(path) {
783                                changed_asset_paths.push(path.clone());
784                            }
785                        }
786                    }
787                    if let Some(post_assets) = &post_assets {
788                        for path in &changed_public {
789                            if let Some(stamp) = post_assets.get(*path) {
790                                snapshot.insert((*path).clone(), *stamp);
791                            } else {
792                                snapshot.remove(*path);
793                            }
794                        }
795                    }
796                }
797            }
798        }
799    }
800    Ok(PreparedDevInputs {
801        config,
802        snapshot,
803        css_only,
804        public_assets_only,
805        changed_asset_paths,
806        hot_update,
807        deferred_assets: defer_assets.then_some(changed),
808    })
809}
810
811fn declared_asset_outputs(config: &ProjectConfig) -> Vec<PathBuf> {
812    let mut outputs = Vec::new();
813    if let Some(output) = crate::config::css_script_output(config) {
814        outputs.push(output);
815    }
816    for asset in config.build.assets() {
817        if !outputs.contains(&asset.output) {
818            outputs.push(asset.output.clone());
819        }
820    }
821    outputs
822}
823
824/// Asset commands (like Tailwind CSS) can run concurrently with Cargo on Rust
825/// edits when the previous build's dep-info proved none of the declared asset
826/// outputs are compiled into the binary (e.g. via `include_str!`).
827fn can_defer_assets_for_parallel_cargo(
828    root: &Path,
829    config: &ProjectConfig,
830    public: Option<&Path>,
831    changed: &[PathBuf],
832    compiled_inputs: Option<&BTreeSet<PathBuf>>,
833) -> bool {
834    let Some(inputs) = compiled_inputs else {
835        return false;
836    };
837    let outputs = declared_asset_outputs(config);
838    if outputs.is_empty() || changed.is_empty() {
839        return false;
840    }
841    let has_non_asset_change = changed.iter().any(|path| {
842        public.map_or_else(
843            || {
844                !path
845                    .extension()
846                    .and_then(OsStr::to_str)
847                    .is_some_and(|ext| ext.eq_ignore_ascii_case("css"))
848            },
849            |public| !is_css_or_public_or_asset_input(path, public, config),
850        )
851    });
852    has_non_asset_change
853        && outputs
854            .iter()
855            .all(|output| !is_compiled_input(root, inputs, output))
856}
857
858/// Whether a finished build's recorded inputs prove it embeds no declared
859/// asset output. Unknown inputs prove nothing.
860fn build_excludes_asset_outputs(
861    root: &Path,
862    config: &ProjectConfig,
863    final_root_inputs: Option<&[PathBuf]>,
864) -> bool {
865    collect_compiled_source_inputs_from_paths(final_root_inputs).is_some_and(|inputs| {
866        declared_asset_outputs(config)
867            .iter()
868            .all(|output| !is_compiled_input(root, &inputs, output))
869    })
870}
871
872/// Fast scheduling hint for `proa dev` watch mode: returns true if any `.rs`
873/// file under `src/` mentions RSJS macro/attribute tokens. Soundness never
874/// depends on this scan because `rsjs_macros` fails closed on unmapped units.
875fn project_mentions_rsjs_macros(root: &Path) -> bool {
876    let src = root.join("src");
877    if !src.is_dir() {
878        return true;
879    }
880    for entry in walkdir::WalkDir::new(src).follow_links(false) {
881        let Ok(entry) = entry else {
882            return true;
883        };
884        if !entry.file_type().is_file() || entry.path().extension() != Some(OsStr::new("rs")) {
885            continue;
886        }
887        let Ok(content) = fs::read_to_string(entry.path()) else {
888            return true;
889        };
890        if content.contains("#[rsjs")
891            || content.contains("rsjs::")
892            || content.contains("SharedState")
893        {
894            return true;
895        }
896    }
897    false
898}
899
900fn start_reload_server(address: (&str, u16), options: &DevOptions) -> Option<ReloadServer> {
901    if options.no_reload {
902        dev_ui::detail!("Proa dev live reload: off");
903        dev_ui::reload("off");
904        return None;
905    }
906
907    // Zero asks the operating system for a free port. A fixed offset from the
908    // dev port would quietly claim the port the developer's next site wants,
909    // and that site would then fail to bind with an error naming neither live
910    // reload nor the process holding it. Tabs do not need the port to be
911    // stable: one whose stream endpoint has moved reloads itself and picks up
912    // the current one from the page.
913    let requested = options.reload_port.unwrap_or_default();
914    if requested != 0 && requested == address.1 {
915        eprintln!(
916            "Proa dev live reload: off (--reload-port {requested} is the port the site itself uses)"
917        );
918        dev_ui::reload("off");
919        return None;
920    }
921    match ReloadServer::bind(address.0, requested) {
922        Ok(server) => {
923            dev_ui::detail!("Proa dev live reload: on (port {})", server.port());
924            dev_ui::reload("on");
925            Some(server)
926        }
927        Err(error) => {
928            // A dev loop that still rebuilds is far more useful than one that
929            // refuses to start because a port was unavailable.
930            eprintln!("Proa dev live reload: off ({error:#})");
931            dev_ui::reload("off");
932            None
933        }
934    }
935}
936
937/// Where `proa dev` asks the server to listen, and why.
938#[derive(Debug, PartialEq, Eq)]
939struct DevAddress {
940    host: String,
941    port: u16,
942    /// What an environment variable decided, or why one was passed over.
943    notes: Vec<String>,
944}
945
946/// Flags win, then the environment, then `127.0.0.1:3000`.
947///
948/// `PROA_HOST` and `PORT` are the variables the server itself reads, so a
949/// shell, container, or process manager that exports them gets the same
950/// address from `proa dev` as from `proa start`. `HOST` is honored too, but
951/// only when it can be a listen address: shells and toolchains export it for
952/// their own purposes (a machine name, a compiler target triple), and binding
953/// the dev server to whatever that happens to resolve to would be a surprise.
954fn resolve_dev_address(
955    host_flag: Option<&str>,
956    port_flag: Option<u16>,
957    env: impl Fn(&str) -> Option<String>,
958) -> Result<DevAddress> {
959    let set = |name: &str| {
960        env(name)
961            .map(|value| value.trim().to_owned())
962            .filter(|value| !value.is_empty())
963    };
964    let mut notes = Vec::new();
965    let host = if let Some(host) = host_flag {
966        host.to_owned()
967    } else if let Some(host) = set("PROA_HOST") {
968        notes.push(format!("Proa dev host: {host} (from PROA_HOST)"));
969        host
970    } else {
971        match set("HOST") {
972            Some(raw) => match normalize_listen_address(&raw) {
973                Some(normalized) => {
974                    if normalized == raw {
975                        notes.push(format!("Proa dev host: {normalized} (from HOST)"));
976                    } else {
977                        notes.push(format!("Proa dev host: {normalized} (from HOST={raw})"));
978                    }
979                    normalized
980                }
981                None => {
982                    notes.push(format!(
983                        "Proa dev host: ignoring HOST=`{raw}` because it is not an IP address or `localhost`; set PROA_HOST or pass --host to listen on a DNS name"
984                    ));
985                    "127.0.0.1".to_owned()
986                }
987            },
988            None => "127.0.0.1".to_owned(),
989        }
990    };
991    let port = match (port_flag, set("PORT")) {
992        (Some(port), _) => port,
993        (None, Some(value)) => {
994            let port = value
995                .parse::<u16>()
996                .ok()
997                .filter(|port| *port != 0)
998                .with_context(|| {
999                    format!(
1000                        "invalid PORT environment variable `{value}`: expected a TCP port number (1-65535); pass --port to override it"
1001                    )
1002                })?;
1003            notes.push(format!("Proa dev port: {port} (from PORT)"));
1004            port
1005        }
1006        (None, None) => 3000,
1007    };
1008    Ok(DevAddress { host, port, notes })
1009}
1010
1011/// Accept `HOST` values that name a listen address and normalize them to a
1012/// bare `IpAddr` string so generated servers (`PROA_HOST.parse::<IpAddr>()`)
1013/// can bind without failing on `localhost` or bracketed IPv6 literals.
1014fn normalize_listen_address(host: &str) -> Option<String> {
1015    if host.eq_ignore_ascii_case("localhost") {
1016        return Some("127.0.0.1".to_owned());
1017    }
1018    if let Some(inner) = host
1019        .strip_prefix('[')
1020        .and_then(|rest| rest.strip_suffix(']'))
1021    {
1022        return inner
1023            .parse::<std::net::Ipv6Addr>()
1024            .ok()
1025            .map(|ip| ip.to_string());
1026    }
1027    host.parse::<std::net::IpAddr>()
1028        .ok()
1029        .map(|ip| ip.to_string())
1030}
1031
1032fn dev_watch_debounce(options: &DevOptions) -> Result<Duration> {
1033    let Some(requested) = options.debounce_ms else {
1034        return Ok(DEV_WATCH_DEBOUNCE);
1035    };
1036    let requested = Duration::from_millis(requested);
1037    if requested < DEV_WATCH_MIN_DEBOUNCE {
1038        bail!(
1039            "`--debounce-ms {}` is below the {}ms file-watch poll interval; use {}ms or more",
1040            requested.as_millis(),
1041            DEV_WATCH_POLL.as_millis(),
1042            DEV_WATCH_MIN_DEBOUNCE.as_millis()
1043        );
1044    }
1045    Ok(requested)
1046}
1047
1048fn notify(reload: Option<&ReloadServer>, event: &ReloadEvent) {
1049    if let Some(reload) = reload {
1050        reload.broadcast(event);
1051    }
1052}
1053
1054fn dev_url(host: &str, port: u16) -> String {
1055    use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
1056
1057    match host.trim_matches(['[', ']']).parse::<IpAddr>() {
1058        Ok(IpAddr::V4(address)) => {
1059            let address = if address.is_unspecified() {
1060                Ipv4Addr::LOCALHOST
1061            } else {
1062                address
1063            };
1064            format!("http://{address}:{port}")
1065        }
1066        Ok(IpAddr::V6(address)) => {
1067            let address = if address.is_unspecified() {
1068                Ipv6Addr::LOCALHOST
1069            } else {
1070                address
1071            };
1072            format!("http://[{address}]:{port}")
1073        }
1074        Err(_) => format!("http://{host}:{port}"),
1075    }
1076}
1077
1078fn announce_dev_start(open: bool, host: &str, port: u16, child: &mut DevChild) {
1079    dev_ui::detail!("Waiting for the dev server to be ready...");
1080    if let Some(url) = child.ready_url(host, port) {
1081        dev_ui::detail!("Proa dev ready: {url}");
1082        dev_ui::ready(&url);
1083        if open {
1084            open_url(&url);
1085        }
1086    } else if let Ok(Some(status)) = child.process.try_wait() {
1087        if open || !status.success() {
1088            eprintln!("Proa dev server exited before accepting connections ({status}).");
1089        }
1090    } else {
1091        eprintln!("Proa dev server is still running and has not reported readiness within {}s (configured listener {host}:{port}).", DEV_READY_TIMEOUT.as_secs());
1092    }
1093}
1094
1095fn open_url(url: &str) {
1096    #[cfg(target_os = "macos")]
1097    let mut command = Command::new("open");
1098    #[cfg(target_os = "linux")]
1099    let mut command = Command::new("xdg-open");
1100    #[cfg(target_os = "windows")]
1101    let mut command = {
1102        let mut command = Command::new("rundll32.exe");
1103        command.arg("url.dll,FileProtocolHandler");
1104        command
1105    };
1106    if let Err(error) = command.arg(url).spawn() {
1107        eprintln!("Could not open the browser: {error}. Open {url} manually.");
1108    }
1109}
1110
1111/// Tell tabs to reload, preferably once the replacement server answers.
1112///
1113/// Reloading into a connection-refused error page is the failure mode that
1114/// makes naive live reload feel broken, so readiness is confirmed first.
1115fn announce_reload(reload: Option<&ReloadServer>, host: &str, port: u16, child: &mut DevChild) {
1116    if let Some(url) = child.ready_url(host, port) {
1117        dev_ui::detail!("Proa dev ready: {url}");
1118        dev_ui::ready(&url);
1119        notify(reload, &ReloadEvent::Reload);
1120        return;
1121    }
1122
1123    // A server that exits on boot is a result the developer needs to see.
1124    if let Ok(Some(status)) = child.process.try_wait() {
1125        let detail = format!("the rebuilt server exited with {status}");
1126        eprintln!("live reload: {detail}");
1127        notify(reload, &ReloadEvent::Failed(detail));
1128        return;
1129    }
1130
1131    let detail = format!("the rebuilt server has not reported readiness within {}s (configured listener {host}:{port})", DEV_READY_TIMEOUT.as_secs());
1132    eprintln!("live reload: {detail}");
1133    notify(reload, &ReloadEvent::Failed(detail));
1134}
1135
1136/// Paths whose stamp differs between two snapshots, including deletions.
1137fn changed_paths(before: &WatchSnapshot, after: &WatchSnapshot) -> Vec<PathBuf> {
1138    let mut changed: Vec<PathBuf> = after
1139        .iter()
1140        .filter(|(path, stamp)| before.get(*path) != Some(*stamp))
1141        .map(|(path, _)| path.clone())
1142        .collect();
1143    changed.extend(
1144        before
1145            .keys()
1146            .filter(|path| !after.contains_key(*path))
1147            .cloned(),
1148    );
1149    changed
1150}
1151
1152/// Whether a change set can be served by rebuilding assets alone.
1153///
1154/// Only stylesheets qualify. Anything else, including a Tailwind class edited
1155/// inside a Rust template, changes a compiled input and needs a real rebuild.
1156fn is_stylesheet_only_change(changed: &[PathBuf]) -> bool {
1157    !changed.is_empty()
1158        && changed.iter().all(|path| {
1159            path.extension()
1160                .and_then(OsStr::to_str)
1161                .is_some_and(|extension| extension.eq_ignore_ascii_case("css"))
1162        })
1163}
1164
1165fn is_css_or_public_or_asset_input(path: &Path, public: &Path, config: &ProjectConfig) -> bool {
1166    path.starts_with(public)
1167        || path
1168            .extension()
1169            .and_then(OsStr::to_str)
1170            .is_some_and(|extension| extension.eq_ignore_ascii_case("css"))
1171        || config.build.assets().iter().any(|asset| {
1172            path == asset.input || asset.config.as_deref().is_some_and(|cfg| path == cfg)
1173        })
1174}
1175
1176/// Collect the files and directories Cargo recorded as inputs of the final
1177/// dev executable, with links resolved.
1178///
1179/// Returns `None` when Cargo's dep-info is unavailable or a local build script
1180/// declares no inputs, so asset-only edits fall back to a full linked rebuild.
1181fn collect_compiled_source_inputs(output: &LinkedCargoOutput) -> Option<BTreeSet<PathBuf>> {
1182    collect_compiled_source_inputs_from_paths(output.final_root_inputs.as_deref())
1183}
1184
1185fn collect_compiled_source_inputs_from_paths(
1186    inputs: Option<&[PathBuf]>,
1187) -> Option<BTreeSet<PathBuf>> {
1188    Some(
1189        inputs?
1190            .iter()
1191            .map(|input| input.canonicalize().unwrap_or_else(|_| input.clone()))
1192            .collect(),
1193    )
1194}
1195
1196/// Whether a watched, root-relative path is (or is inside) a compiled input.
1197///
1198/// The watcher reports authored paths, and `public` may be a link to another
1199/// directory, so both sides are compared with links resolved. A path that no
1200/// longer resolves counts as an input.
1201fn is_compiled_input(root: &Path, inputs: &BTreeSet<PathBuf>, path: &Path) -> bool {
1202    let path = root.join(path);
1203    // A deleted file still resolves through its directory.
1204    let resolved = path.canonicalize().or_else(|_| {
1205        let parent = path.parent().unwrap_or(root).canonicalize()?;
1206        Ok::<_, io::Error>(parent.join(path.file_name().unwrap_or_default()))
1207    });
1208    match resolved {
1209        // A declared build-script input can be a directory.
1210        Ok(resolved) => inputs.iter().any(|input| resolved.starts_with(input)),
1211        Err(_) => true,
1212    }
1213}
1214
1215fn default_watch_paths() -> Vec<PathBuf> {
1216    // Cargo.lock can be rewritten by Cargo itself. Watching it restarts the
1217    // dev loop for a change caused by the build.
1218    [
1219        "src",
1220        "styles",
1221        "migrations",
1222        "Cargo.toml",
1223        "build.rs",
1224        crate::config::CONFIG_FILE,
1225        crate::config::LOCK_FILE,
1226    ]
1227    .into_iter()
1228    .map(PathBuf::from)
1229    .collect()
1230}
1231
1232fn dev_watch_paths(config: &ProjectConfig, options: &DevOptions) -> Result<Vec<PathBuf>> {
1233    let mut paths = default_watch_paths();
1234    for path in &options.watch {
1235        if !paths.contains(path) {
1236            paths.push(path.clone());
1237        }
1238    }
1239    if let Some(public) = public_assets::configured_path(config, !options.no_assets)? {
1240        if !paths.iter().any(|path| path == public) {
1241            paths.push(public.to_path_buf());
1242        }
1243    }
1244    Ok(paths)
1245}
1246
1247// The exact final server runs in its own process group so restarts can stop
1248// its whole subprocess tree. That also detaches it from the terminal's
1249// foreground group, so Ctrl-C / SIGTERM on `proa dev` must be forwarded to
1250// the child group by hand or the server would outlive the CLI and keep the
1251// port bound.
1252#[cfg(unix)]
1253static ACTIVE_CHILD_GROUP: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);
1254
1255fn set_active_child_group(child: &Child) {
1256    #[cfg(unix)]
1257    ACTIVE_CHILD_GROUP.store(child.id() as i32, std::sync::atomic::Ordering::SeqCst);
1258    #[cfg(not(unix))]
1259    let _ = child;
1260}
1261
1262fn clear_active_child_group() {
1263    #[cfg(unix)]
1264    ACTIVE_CHILD_GROUP.store(0, std::sync::atomic::Ordering::SeqCst);
1265}
1266
1267#[cfg(unix)]
1268extern "C" fn dev_signal_handler(signal: libc::c_int) {
1269    let pgid = ACTIVE_CHILD_GROUP.load(std::sync::atomic::Ordering::SeqCst);
1270    if pgid > 0 {
1271        unsafe { libc::kill(-pgid, libc::SIGTERM) };
1272    }
1273    unsafe { libc::_exit(128 + signal) };
1274}
1275
1276fn install_dev_signal_handler() {
1277    #[cfg(unix)]
1278    unsafe {
1279        libc::signal(
1280            libc::SIGINT,
1281            dev_signal_handler as extern "C" fn(libc::c_int) as libc::sighandler_t,
1282        );
1283        libc::signal(
1284            libc::SIGTERM,
1285            dev_signal_handler as extern "C" fn(libc::c_int) as libc::sighandler_t,
1286        );
1287    }
1288}
1289
1290fn default_release_export_path(
1291    target_dir: &Path,
1292    target_name: &str,
1293    target_triple: Option<&str>,
1294) -> PathBuf {
1295    let mut filename = OsString::from(target_name);
1296    let suffix = match target_triple {
1297        Some(triple) => {
1298            if triple.contains("windows") {
1299                ".exe"
1300            } else {
1301                ""
1302            }
1303        }
1304        None => std::env::consts::EXE_SUFFIX,
1305    };
1306    if !suffix.is_empty() && !target_name.to_ascii_lowercase().ends_with(suffix) {
1307        filename.push(suffix);
1308    }
1309    match target_triple {
1310        Some(triple) => target_dir.join(triple).join("release").join(filename),
1311        None => target_dir.join("release").join(filename),
1312    }
1313}
1314
1315pub fn build(mut options: BuildOptions) -> Result<()> {
1316    let root = absolute_project_root(scaffold::resolve_root(options.root.clone())?)?;
1317    let config = load_project_config(&root)?;
1318    script::hint("build", &config.scripts.build, DEFAULT_BUILD_COMMAND);
1319    if options.command.is_empty()
1320        && options.package.is_none()
1321        && options.bin.is_none()
1322        && options.example.is_none()
1323    {
1324        options.bin = configured_binary(&config);
1325    }
1326    let command = build_command(&options);
1327    // Validate and resolve the exact Cargo root before running configured asset
1328    // commands. An unsupported deployment command must fail without partially
1329    // executing a build.
1330    let prepared = prepare_linked_cargo_with_environment(
1331        &root,
1332        &command,
1333        LinkedCargoAction::Build,
1334        &rsjs_minify_environment(config.build.minify_rsjs),
1335    )?;
1336    let public_source = public_assets::configured_path(&config, !options.no_assets)?;
1337    let artifact_destination = options
1338        .artifact_out
1339        .as_deref()
1340        .map(|destination| resolve_artifact_output(&root, destination));
1341    if let Some(destination) = artifact_destination.as_deref() {
1342        public_assets::check_bundle_destination(&root, public_source, destination)?;
1343        warn_if_artifact_output_enters_source_closure(
1344            destination,
1345            &prepared.package_source_root,
1346            &prepared.request.descriptor.source_exclusion_directory,
1347        );
1348    }
1349
1350    task::run_lifecycle_tasks(
1351        &root,
1352        &config,
1353        &config.scripts.before.build,
1354        &BTreeMap::new(),
1355    )?;
1356    if !options.no_check {
1357        run_project_check(&root, &config)?;
1358    }
1359    if !options.no_assets {
1360        build_assets(&root, &config)?;
1361    }
1362
1363    println!("running linked RSJS Cargo build: {}", shellish(&command));
1364    let output = run_linked_cargo_cached(&prepared.request, &prepared.descriptor_cache_directory)
1365        .context("linked RSJS build failed")?;
1366    print_linked_cache_reuse(LinkedCargoAction::Build, &output);
1367    print_linked_cargo_output(LinkedCargoAction::Build, &prepared.request, &output);
1368    // An explicit export carries its own catalog beside the executable, so
1369    // only a build without one publishes into the target directory. Cargo's
1370    // own output directory never gets a bundle: a plain `cargo run` would
1371    // pick it up after the public files had moved on.
1372    let published_public_assets = match artifact_destination {
1373        Some(_) => None,
1374        None => public_assets::publish(&root, public_source, &prepared.public_output_directory)?,
1375    };
1376    let target_dir = &prepared.request.descriptor.source_exclusion_directory;
1377    let target_triple = prepared.target_triple.as_deref();
1378    let default_release_destination = (artifact_destination.is_none()
1379        && prepared.profile == "release"
1380        && prepared.request.root.role == ArtifactRole::RootExecutable)
1381        .then(|| {
1382            default_release_export_path(
1383                target_dir,
1384                &prepared.request.root.target_name,
1385                target_triple,
1386            )
1387        });
1388    let export_destination = artifact_destination
1389        .as_deref()
1390        .or(default_release_destination.as_deref());
1391    if let Some(destination) = export_destination {
1392        let source =
1393            select_final_root_executable(&prepared.request, &output, LinkedCargoAction::Build)?;
1394        // The default export never bundles, but an explicit export to the
1395        // same path may have: that catalog must not outlive its executable.
1396        let bundle = if artifact_destination.is_some() {
1397            // Storing the modules is what lets a static host serve them. The
1398            // server prepares its own when they are not there, so a failed
1399            // export costs that option and not the build.
1400            let framework =
1401                public_assets::export_framework_assets(&source, target_triple.is_some())
1402                    .unwrap_or_else(|error| {
1403                        eprintln!(
1404                            "warning: {error:#}; the bundle is written without them and the server will prepare them at startup"
1405                        );
1406                        None
1407                    });
1408            public_assets::bundle(&root, public_source, destination, framework.as_ref())?
1409        } else {
1410            public_assets::clear_bundle(destination)?
1411        };
1412        copy_executable_atomically(&source, destination).with_context(|| {
1413            format!(
1414                "failed to export linked executable `{}` to `{}`",
1415                source.display(),
1416                destination.display()
1417            )
1418        })?;
1419        let bundled_public_assets = bundle.directory.clone();
1420        // Before anything else can fail: the new executable is in place.
1421        bundle.finish()?;
1422        println!(
1423            "exported linked RSJS executable to {}",
1424            destination.display()
1425        );
1426        public_assets::record_start_manifest(
1427            target_dir,
1428            &prepared.request.root.package_id,
1429            &prepared.request.root.target_name,
1430            &prepared.profile,
1431            target_triple,
1432            destination,
1433            bundled_public_assets
1434                .as_deref()
1435                .or(published_public_assets.as_deref()),
1436        )?;
1437        print!(
1438            "{}",
1439            build_output_summary(
1440                destination,
1441                bundled_public_assets
1442                    .as_deref()
1443                    .or(published_public_assets.as_deref()),
1444                artifact_destination.is_some(),
1445            )
1446        );
1447    }
1448    Ok(())
1449}
1450
1451/// The closing lines of a build: what to run, and what to copy to deploy.
1452/// Without `--artifact-out` the executable and its catalog live in separate
1453/// target directories that only `proa start` joins.
1454// proa-perf-ok(scope): terminal text printed once per build, not HTML.
1455fn build_output_summary(executable: &Path, assets: Option<&Path>, deployable: bool) -> String {
1456    if deployable {
1457        return match assets {
1458            Some(assets) => format!(
1459                "deployable output, copy together:\n  {}\n  {}\n",
1460                executable.display(),
1461                assets.display()
1462            ),
1463            None => format!("deployable output: {}\n", executable.display()),
1464        };
1465    }
1466    let mut summary = format!("built {}\n", executable.display());
1467    if let Some(assets) = assets {
1468        summary.push_str(&format!(
1469            "  public assets {} (`proa start` serves them with it)\n",
1470            assets.display()
1471        ));
1472    }
1473    summary.push_str(
1474        "  to deploy, rerun with `--artifact-out <path>`: it writes <path> and <path>.assets, copied together\n",
1475    );
1476    summary
1477}
1478
1479pub fn check(mut options: CheckOptions) -> Result<()> {
1480    let root = absolute_project_root(scaffold::resolve_root(options.root.clone())?)?;
1481    let config = load_project_config(&root)?;
1482    if options.bin.is_none() {
1483        options.bin = config
1484            .application
1485            .as_ref()
1486            .map(|application| application.binary.as_str())
1487            .filter(|value| !value.is_empty())
1488            .map(ToString::to_string);
1489    }
1490    let command = check_command(&options);
1491    let prepared = prepare_linked_cargo_with_environment(
1492        &root,
1493        &command,
1494        LinkedCargoAction::Check,
1495        &rsjs_minify_environment(config.build.minify_rsjs),
1496    )?;
1497
1498    println!("running linked RSJS Cargo check: {}", shellish(&command));
1499    let output = run_linked_cargo_cached(&prepared.request, &prepared.descriptor_cache_directory)
1500        .context("linked RSJS check failed")?;
1501    print_linked_cache_reuse(LinkedCargoAction::Check, &output);
1502    print_linked_cargo_output(LinkedCargoAction::Check, &prepared.request, &output);
1503    Ok(())
1504}
1505
1506pub fn run(mut options: RunOptions) -> Result<()> {
1507    let root = absolute_project_root(scaffold::resolve_root(options.root.clone())?)?;
1508    let config = load_project_config(&root)?;
1509    if options.package.is_none() && options.bin.is_none() {
1510        options.bin = configured_binary(&config);
1511    }
1512    let command = run_command(&options);
1513    run_linked_execute_with_environment(
1514        &root,
1515        &command,
1516        LinkedCargoAction::Run,
1517        &config,
1518        &BTreeMap::new(),
1519    )
1520}
1521
1522pub fn test(mut options: TestOptions) -> Result<()> {
1523    install_test_signal_handler();
1524    TEST_INTERRUPTED.store(false, Ordering::SeqCst);
1525    if options.bin.is_some() && options.test.is_some() {
1526        bail!(
1527            "`cargo proa test` requires exactly one target selector: use either `--bin <name>` or `--test <name>`"
1528        );
1529    }
1530    let root = absolute_project_root(scaffold::resolve_root(options.root.clone())?)?;
1531    let explicit_target = options.bin.is_some() || options.test.is_some();
1532    let config = load_project_config(&root)?;
1533    if options.bin.is_none() && options.test.is_none() {
1534        options.bin = config
1535            .application
1536            .as_ref()
1537            .map(|application| application.binary.as_str())
1538            .filter(|value| !value.is_empty())
1539            .map(ToString::to_string);
1540        if options.bin.is_none() {
1541            bail!(
1542                "`cargo proa test` requires exactly one target selector: use either `--bin <name>` or `--test <name>`"
1543            );
1544        }
1545    }
1546    let mut commands = vec![test_command(&options)];
1547    if !explicit_target {
1548        let prepared = prepare_linked_cargo(&root, &commands[0], LinkedCargoAction::Test)?;
1549        for test in discover_integration_test_targets(&prepared.package_source_root)? {
1550            let mut integration = options.clone();
1551            integration.bin = None;
1552            integration.test = Some(test);
1553            commands.push(test_command(&integration));
1554        }
1555    }
1556    if options.watch {
1557        run_watched_tests(
1558            &root,
1559            &config,
1560            &commands,
1561            options.keep_database,
1562            &options.watch_paths,
1563        )
1564    } else {
1565        run_test_session(&root, &config, &commands, options.keep_database)
1566    }
1567}
1568
1569fn discover_integration_test_targets(package_source_root: &Path) -> Result<Vec<String>> {
1570    let directory = package_source_root.join("tests");
1571    let entries = match fs::read_dir(&directory) {
1572        Ok(entries) => entries,
1573        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
1574        Err(error) => return Err(error).with_context(|| format!("read {}", directory.display())),
1575    };
1576    let mut targets = Vec::new();
1577    for entry in entries {
1578        let entry = entry?;
1579        let path = entry.path();
1580        let is_rust_file = path.is_file() && path.extension() == Some(OsStr::new("rs"));
1581        let is_directory_target = path.is_dir() && path.join("main.rs").is_file();
1582        if !is_rust_file && !is_directory_target {
1583            continue;
1584        }
1585        let name = path
1586            .file_stem()
1587            .and_then(OsStr::to_str)
1588            .context("integration-test target names must be UTF-8")?;
1589        targets.push(name.to_string());
1590    }
1591    targets.sort();
1592    Ok(targets)
1593}
1594
1595#[derive(Debug)]
1596struct IsolatedTestDatabase {
1597    run_directory: PathBuf,
1598    path: PathBuf,
1599}
1600
1601impl IsolatedTestDatabase {
1602    fn create(root: &Path) -> Result<Self> {
1603        let run_directory = root.join("target/proa-tests").join(fresh_build_nonce());
1604        fs::create_dir_all(&run_directory)
1605            .with_context(|| format!("create {}", run_directory.display()))?;
1606        let database = Self {
1607            path: run_directory.join("test.db"),
1608            run_directory,
1609        };
1610        if let Err(error) = db::prepare_test_database(root, &database.path) {
1611            let _ = db::remove_test_database(&database.path);
1612            let _ = fs::remove_dir(&database.run_directory);
1613            return Err(error).context("prepare isolated test database");
1614        }
1615        println!("Test database  {}", database.path.display());
1616        Ok(database)
1617    }
1618
1619    fn url(&self) -> OsString {
1620        OsString::from(format!("sqlite://{}", self.path.display()))
1621    }
1622
1623    fn reset(&self, root: &Path) -> Result<()> {
1624        db::remove_test_database(&self.path)?;
1625        db::prepare_test_database(root, &self.path)
1626    }
1627
1628    fn cleanup(&self) -> Result<()> {
1629        db::remove_test_database(&self.path)?;
1630        match fs::remove_dir(&self.run_directory) {
1631            Ok(()) => Ok(()),
1632            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
1633            Err(error) => {
1634                Err(error).with_context(|| format!("remove {}", self.run_directory.display()))
1635            }
1636        }
1637    }
1638}
1639
1640fn project_uses_sqlite(config: &ProjectConfig) -> bool {
1641    config.database.as_ref().map(|database| database.driver)
1642        == Some(crate::config::DatabaseDriver::Sqlite)
1643}
1644
1645fn run_test_session(
1646    root: &Path,
1647    config: &ProjectConfig,
1648    commands: &[Vec<String>],
1649    keep_database: bool,
1650) -> Result<()> {
1651    let database = project_uses_sqlite(config)
1652        .then(|| IsolatedTestDatabase::create(root))
1653        .transpose()?;
1654    if database.is_none() && keep_database {
1655        eprintln!("No SQLite capability is configured; --keep-database is a no-op.");
1656    }
1657    let result = (|| {
1658        let environment = test_environment(root, database.as_ref())?;
1659        run_test_hooks(root, config, &environment)?;
1660        prepare_test_assets(root, config)?;
1661        run_test_targets(root, config, commands, &environment)
1662    })();
1663    finish_test_database(database.as_ref(), keep_database && result.is_err())?;
1664    result
1665}
1666
1667fn run_watched_tests(
1668    root: &Path,
1669    config: &ProjectConfig,
1670    commands: &[Vec<String>],
1671    keep_database: bool,
1672    watch_paths: &[PathBuf],
1673) -> Result<()> {
1674    let database = project_uses_sqlite(config)
1675        .then(|| IsolatedTestDatabase::create(root))
1676        .transpose()?;
1677    if database.is_none() && keep_database {
1678        eprintln!("No SQLite capability is configured; --keep-database is a no-op.");
1679    }
1680    let result = watched_test_loop(root, config, commands, database.as_ref(), watch_paths);
1681    let preserve = keep_database
1682        && match &result {
1683            Ok(last_failed) => *last_failed,
1684            Err(_) => true,
1685        };
1686    finish_test_database(database.as_ref(), preserve)?;
1687    result.map(|_| ())
1688}
1689
1690fn watched_test_loop(
1691    root: &Path,
1692    config: &ProjectConfig,
1693    commands: &[Vec<String>],
1694    database: Option<&IsolatedTestDatabase>,
1695    watch_paths: &[PathBuf],
1696) -> Result<bool> {
1697    let mut paths = default_watch_paths();
1698    paths.extend(["tests", ".env", ".env.test"].map(PathBuf::from));
1699    paths.extend(watch_paths.iter().cloned());
1700    if public_assets::configured_path(config, true)?.is_some() {
1701        paths.extend(config.paths.public.iter().cloned());
1702    }
1703    let migrations = config
1704        .database
1705        .as_ref()
1706        .and_then(|database| database.migrations.as_deref())
1707        .map(PathBuf::from)
1708        .unwrap_or_else(|| PathBuf::from("migrations"));
1709    paths.push(migrations.clone());
1710    paths.sort_unstable();
1711    paths.dedup();
1712    let hooks = &config.scripts.before.test;
1713    // Hook execution reports invalid task names or dependency cycles.
1714    let declared_hook_outputs = task::lifecycle_output_paths(config, hooks).unwrap_or_default();
1715    let mut successful_hook_outputs = declared_hook_outputs.clone();
1716    if !hooks.is_empty() {
1717        successful_hook_outputs.extend(config.paths.public.as_deref());
1718    }
1719    let css_output = crate::config::css_script_output(config);
1720    let asset_outputs: Vec<_> = config
1721        .paths
1722        .public
1723        .iter()
1724        .flat_map(|_| {
1725            config
1726                .build
1727                .assets()
1728                .iter()
1729                .map(|asset| asset.output.as_path())
1730                .chain(css_output.as_deref())
1731        })
1732        .collect();
1733    let mut baseline = watch_snapshot(root, &paths)?;
1734    let mut last_failed;
1735
1736    loop {
1737        let environment = test_environment(root, database)?;
1738        let mut prepared = run_test_hooks(root, config, &environment);
1739        let hook_outputs = if prepared.is_ok() {
1740            // Asset publication and tests will see the prepared public inputs.
1741            &successful_hook_outputs
1742        } else {
1743            // No tests run after a failed hook. Keep a concurrent fix to an
1744            // authored fixture pending so the watcher retries preparation.
1745            &declared_hook_outputs
1746        };
1747        refresh_test_watch_outputs(root, &paths, hook_outputs, &mut baseline)?;
1748        if prepared.is_ok() {
1749            prepared = prepare_test_assets(root, config);
1750            refresh_test_watch_outputs(root, &paths, &asset_outputs, &mut baseline)?;
1751        }
1752        match prepared.and_then(|()| run_test_targets(root, config, commands, &environment)) {
1753            Ok(()) => last_failed = false,
1754            Err(error) => {
1755                last_failed = true;
1756                eprintln!("test run failed; watching for changes:\n{error:#}");
1757            }
1758        }
1759        if TEST_INTERRUPTED.load(Ordering::SeqCst) {
1760            break;
1761        }
1762        println!("Watching for test input changes · press Ctrl-C to stop");
1763        let changed = loop {
1764            thread::sleep(Duration::from_millis(200));
1765            if TEST_INTERRUPTED.load(Ordering::SeqCst) {
1766                break Vec::new();
1767            }
1768            let snapshot = watch_snapshot(root, &paths)?;
1769            let changed = changed_paths(&baseline, &snapshot);
1770            if !changed.is_empty() {
1771                thread::sleep(DEV_WATCH_DEBOUNCE);
1772                baseline = watch_snapshot(root, &paths)?;
1773                break changed;
1774            }
1775        };
1776        if TEST_INTERRUPTED.load(Ordering::SeqCst) {
1777            break;
1778        }
1779        if changed.iter().any(|path| {
1780            path.strip_prefix(root)
1781                .unwrap_or(path)
1782                .starts_with(&migrations)
1783        }) {
1784            if let Some(database) = &database {
1785                database.reset(root)?;
1786                println!("Test database reset after migration change");
1787            }
1788        }
1789    }
1790    Ok(last_failed)
1791}
1792
1793fn refresh_test_watch_outputs(
1794    root: &Path,
1795    watch_paths: &[PathBuf],
1796    outputs: &[&Path],
1797    baseline: &mut WatchSnapshot,
1798) -> Result<()> {
1799    if outputs.is_empty() {
1800        return Ok(());
1801    }
1802    let prepared = watch_snapshot(root, watch_paths)?;
1803    // Consume preparation writes for these paths. The next test build sees
1804    // edits made after this snapshot.
1805    for output in outputs {
1806        if output.as_os_str().is_empty() {
1807            continue;
1808        }
1809        let output = root.join(output);
1810        let path = output.strip_prefix(root).unwrap_or(&output);
1811        baseline.retain(|file, _| !file.starts_with(path));
1812        baseline.extend(
1813            prepared
1814                .iter()
1815                .filter(|(file, _)| file.starts_with(path))
1816                .map(|(file, stamp)| (file.clone(), *stamp)),
1817        );
1818    }
1819    Ok(())
1820}
1821
1822fn run_test_hooks(
1823    root: &Path,
1824    config: &ProjectConfig,
1825    environment: &BTreeMap<OsString, OsString>,
1826) -> Result<()> {
1827    if TEST_INTERRUPTED.load(Ordering::SeqCst) {
1828        bail!("test interrupted");
1829    }
1830    task::run_lifecycle_tasks(root, config, &config.scripts.before.test, environment)
1831}
1832
1833fn prepare_test_assets(root: &Path, config: &ProjectConfig) -> Result<()> {
1834    if public_assets::configured_path(config, true)?.is_some() {
1835        build_assets(root, config)?;
1836    }
1837    Ok(())
1838}
1839
1840fn run_test_targets(
1841    root: &Path,
1842    config: &ProjectConfig,
1843    commands: &[Vec<String>],
1844    environment: &BTreeMap<OsString, OsString>,
1845) -> Result<()> {
1846    for command in commands {
1847        run_linked_execute_with_environment(
1848            root,
1849            command,
1850            LinkedCargoAction::Test,
1851            config,
1852            environment,
1853        )?;
1854    }
1855    Ok(())
1856}
1857
1858fn finish_test_database(database: Option<&IsolatedTestDatabase>, preserve: bool) -> Result<()> {
1859    let Some(database) = database else {
1860        return Ok(());
1861    };
1862    if preserve {
1863        println!(
1864            "Preserved failing test database at {}",
1865            database.path.display()
1866        );
1867        Ok(())
1868    } else {
1869        database.cleanup()
1870    }
1871}
1872
1873fn test_environment(
1874    root: &Path,
1875    database: Option<&IsolatedTestDatabase>,
1876) -> Result<BTreeMap<OsString, OsString>> {
1877    let mut loaded = BTreeMap::<String, String>::new();
1878    merge_test_env_file(&root.join(".env"), &mut loaded)?;
1879    merge_test_env_file(&root.join(".env.test"), &mut loaded)?;
1880    let mut environment = loaded
1881        .into_iter()
1882        .filter(|(name, _)| env::var_os(name).is_none())
1883        .map(|(name, value)| (OsString::from(name), OsString::from(value)))
1884        .collect::<BTreeMap<_, _>>();
1885    if let Some(database) = database {
1886        environment.insert(OsString::from("DATABASE_URL"), database.url());
1887    }
1888    Ok(environment)
1889}
1890
1891fn merge_test_env_file(path: &Path, values: &mut BTreeMap<String, String>) -> Result<()> {
1892    let source = match fs::read_to_string(path) {
1893        Ok(source) => source,
1894        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
1895        Err(error) => return Err(error).with_context(|| format!("read {}", path.display())),
1896    };
1897    for (index, line) in source.lines().enumerate() {
1898        let line = line.trim();
1899        if line.is_empty() || line.starts_with('#') {
1900            continue;
1901        }
1902        let line = line.strip_prefix("export ").unwrap_or(line);
1903        let (name, value) = line.split_once('=').with_context(|| {
1904            format!("{}:{} is not a NAME=value entry", path.display(), index + 1)
1905        })?;
1906        let name = name.trim();
1907        if name.is_empty()
1908            || !name.bytes().enumerate().all(|(index, byte)| {
1909                byte == b'_' || byte.is_ascii_alphabetic() || index > 0 && byte.is_ascii_digit()
1910            })
1911        {
1912            bail!(
1913                "{}:{} has an invalid environment name",
1914                path.display(),
1915                index + 1
1916            );
1917        }
1918        values.insert(
1919            name.to_string(),
1920            value.trim().trim_matches(['\'', '"']).to_string(),
1921        );
1922    }
1923    Ok(())
1924}
1925
1926#[cfg(unix)]
1927extern "C" fn test_signal_handler(_signal: libc::c_int) {
1928    TEST_INTERRUPTED.store(true, Ordering::SeqCst);
1929}
1930
1931fn install_test_signal_handler() {
1932    #[cfg(unix)]
1933    unsafe {
1934        libc::signal(
1935            libc::SIGINT,
1936            test_signal_handler as extern "C" fn(libc::c_int) as libc::sighandler_t,
1937        );
1938        libc::signal(
1939            libc::SIGTERM,
1940            test_signal_handler as extern "C" fn(libc::c_int) as libc::sighandler_t,
1941        );
1942    }
1943}
1944
1945// Both Cargo phases observe the same setting. Rustc records option_env! as a
1946// dependency, so changing the flag rebuilds its consumers in the same target.
1947fn rsjs_minify_environment(enabled: bool) -> BTreeMap<OsString, OsString> {
1948    BTreeMap::from([(
1949        "PROA_RSJS_MINIFY".into(),
1950        if enabled { "1" } else { "0" }.into(),
1951    )])
1952}
1953
1954fn run_linked_execute_with_environment(
1955    root: &Path,
1956    command: &[String],
1957    action: LinkedCargoAction,
1958    config: &ProjectConfig,
1959    environment: &BTreeMap<OsString, OsString>,
1960) -> Result<()> {
1961    let mut compile_environment = environment.clone();
1962    compile_environment.extend(rsjs_minify_environment(config.build.minify_rsjs));
1963    let mut prepared =
1964        prepare_linked_cargo_with_environment(root, command, action, &compile_environment)?;
1965    let public_source = public_assets::configured_path(config, true)?;
1966    let defer_execution = action == LinkedCargoAction::Run || public_source.is_some();
1967    if defer_execution {
1968        public_assets::defer_execution(&mut prepared, action);
1969    }
1970    if action == LinkedCargoAction::Run && public_source.is_some() {
1971        task::run_lifecycle_tasks(root, config, &config.scripts.before.build, &BTreeMap::new())?;
1972        build_assets(root, config)?;
1973    }
1974    println!(
1975        "running linked RSJS Cargo {}: {}",
1976        action.command_name(),
1977        shellish(command)
1978    );
1979    let output = run_linked_cargo_cached(&prepared.request, &prepared.descriptor_cache_directory)
1980        .with_context(|| format!("linked RSJS {} failed", action.command_name()))?;
1981    print_linked_cache_reuse(action, &output);
1982    print_linked_cargo_output(action, &prepared.request, &output);
1983    if defer_execution {
1984        let executable = select_final_root_executable(&prepared.request, &output, action)?;
1985        let public_output =
1986            public_assets::publish(root, public_source, &prepared.public_output_directory)?;
1987        let mut command = Command::new(executable);
1988        let execution_root = if action == LinkedCargoAction::Test {
1989            &prepared.package_source_root
1990        } else {
1991            root
1992        };
1993        command
1994            .current_dir(execution_root)
1995            .args(&prepared.runtime_args)
1996            .envs(environment);
1997        public_assets::runtime_environment(&mut command, public_output.as_deref());
1998        let status = command
1999            .status()
2000            .with_context(|| format!("start final linked {}", action.command_name()))?;
2001        exit_status_to_result(status, action.command_name())?;
2002    }
2003    Ok(())
2004}
2005
2006fn print_linked_cache_reuse(action: LinkedCargoAction, output: &LinkedCargoOutput) {
2007    let descriptor_artifacts = output.descriptor.cargo_artifacts.len();
2008    let reused_descriptor_artifacts = output
2009        .descriptor
2010        .cargo_artifacts
2011        .iter()
2012        .filter(|artifact| artifact.fresh)
2013        .count();
2014    let final_artifacts = output.final_cargo.cargo_artifacts.len();
2015    let reused_final_artifacts = output
2016        .final_cargo
2017        .cargo_artifacts
2018        .iter()
2019        .filter(|artifact| artifact.fresh)
2020        .count();
2021    println!(
2022        "linked RSJS {} cache: descriptor {reused_descriptor_artifacts}/{descriptor_artifacts} Cargo artifacts reused; final {reused_final_artifacts}/{final_artifacts} reused",
2023        action.command_name(),
2024    );
2025}
2026
2027/// Hot-template scanning parses every source file with syn, whose syntax
2028/// errors are far less useful than rustc's. When the scan fails, run Cargo
2029/// with the active manifest anyway so a half-written file reports rustc's
2030/// diagnostics; the scan error surfaces only if Cargo accepted the source.
2031fn hot_scan_or_rustc_diagnostics<T>(
2032    root: &Path,
2033    config: &ProjectConfig,
2034    command: &[String],
2035    active: Option<&crate::hot_static::HotState>,
2036    scan: Result<T>,
2037) -> Result<T> {
2038    scan.or_else(|scan_error| {
2039        run_linked_dev_cycle(root, config, command, active, None, None)?;
2040        Err(scan_error)
2041    })
2042}
2043
2044enum DevCargoBuild {
2045    SinglePass(crate::rsjs::pipeline::OptimisticLinkedCargoOutput),
2046    Full(LinkedCargoOutput),
2047}
2048
2049impl DevCargoBuild {
2050    fn final_root_inputs(&self) -> Option<&[PathBuf]> {
2051        match self {
2052            Self::SinglePass(output) => output.final_root_inputs.as_deref(),
2053            Self::Full(output) => output.final_root_inputs.as_deref(),
2054        }
2055    }
2056
2057    fn executable(&self) -> Option<&Path> {
2058        match self {
2059            Self::SinglePass(output) => output.final_root_artifact.executable.as_deref(),
2060            Self::Full(output) => output.final_root_artifact.executable.as_deref(),
2061        }
2062    }
2063}
2064
2065/// Build the dev server, trying the single-pass empty-plan build first when
2066/// the session allows it and falling back to the full linked pipeline.
2067fn run_dev_cargo(
2068    prepared: &PreparedLinkedCargo,
2069    mut session: Option<&mut DevSessionCache>,
2070) -> Result<DevCargoBuild> {
2071    let try_optimistic = session
2072        .as_deref()
2073        .is_some_and(|cache| cache.allow_optimistic_empty);
2074    if try_optimistic {
2075        dev_ui::stage("Compiling");
2076        dev_ui::detail!("Building site: compiling Rust...");
2077        match try_run_optimistic_empty_linked_cargo(&prepared.request)
2078            .context("linked RSJS dev build failed")?
2079        {
2080            OptimisticLinkedCargoOutcome::Succeeded(output) => {
2081                return Ok(DevCargoBuild::SinglePass(output));
2082            }
2083            OptimisticLinkedCargoOutcome::NeedsFullLinkedPass => {
2084                if let Some(cache) = session.as_deref_mut() {
2085                    cache.allow_optimistic_empty = false;
2086                }
2087                dev_ui::detail!("Browser island detected; running full two-pass linked build...");
2088            }
2089        }
2090    }
2091    let output = run_linked_cargo_cached_with_progress(
2092        &prepared.request,
2093        &prepared.descriptor_cache_directory,
2094        |stage| match stage {
2095            LinkedCargoStage::Descriptor => {
2096                dev_ui::stage("Compiling");
2097                dev_ui::detail!("Building site (1/2): resolving dependencies and compiling Rust...")
2098            }
2099            LinkedCargoStage::Link => {
2100                dev_ui::stage("Linking");
2101                dev_ui::detail!("Linking browser components...")
2102            }
2103            LinkedCargoStage::Final => {
2104                dev_ui::stage("Finishing");
2105                dev_ui::detail!("Building site (2/2): compiling the final server...")
2106            }
2107        },
2108    )
2109    .context("linked RSJS dev build failed")?;
2110    if let Some(cache) = session {
2111        cache.allow_optimistic_empty = output.semantic.is_empty();
2112    }
2113    Ok(DevCargoBuild::Full(output))
2114}
2115
2116fn run_linked_dev_cycle(
2117    root: &Path,
2118    config: &ProjectConfig,
2119    command: &[String],
2120    hot: Option<&crate::hot_static::HotState>,
2121    public_source: Option<&Path>,
2122    session: Option<&mut DevSessionCache>,
2123) -> Result<LinkedDevLaunch> {
2124    run_linked_dev_cycle_with_assets(root, config, command, hot, public_source, session, None)
2125}
2126
2127fn run_linked_dev_cycle_with_assets(
2128    root: &Path,
2129    config: &ProjectConfig,
2130    command: &[String],
2131    hot: Option<&crate::hot_static::HotState>,
2132    public_source: Option<&Path>,
2133    mut session: Option<&mut DevSessionCache>,
2134    deferred_asset_changes: Option<&[PathBuf]>,
2135) -> Result<LinkedDevLaunch> {
2136    let _progress = DevBuildProgress::start();
2137    dev_ui::detail!("running linked RSJS Cargo dev build: {}", shellish(command));
2138    dev_ui::detail!("Preparing the Cargo project and build cache...");
2139    let mut environment = hot.map(|state| state.environment()).unwrap_or_default();
2140    environment.extend(rsjs_minify_environment(config.build.minify_rsjs));
2141
2142    let (prepared, build, assets) = thread::scope(|scope| {
2143        let assets = deferred_asset_changes.map(|changed| {
2144            scope.spawn(move || build_assets_for_change(root, config, public_source, changed))
2145        });
2146        let prepared = prepare_linked_cargo_with_environment_and_session(
2147            root,
2148            command,
2149            LinkedCargoAction::Dev,
2150            &environment,
2151            session.as_deref_mut(),
2152        );
2153        let build = prepared
2154            .as_ref()
2155            .ok()
2156            .map(|prepared| run_dev_cargo(prepared, session.as_deref_mut()));
2157        let assets = assets.map(|handle| {
2158            handle
2159                .join()
2160                .map_err(|_| anyhow::anyhow!("background asset build thread panicked"))
2161                .and_then(|result| result)
2162        });
2163        (prepared, build, assets)
2164    });
2165
2166    let prepared = prepared?;
2167    let mut build = build.expect("Cargo runs once preparation succeeds")?;
2168    if let Some(assets) = assets {
2169        assets?;
2170    }
2171    // The previous build proved no asset output was compiled in, but this edit
2172    // may have added an `include_str!` of one that Cargo read while the asset
2173    // command was still writing it. Cargo dates each compilation from its
2174    // start, so one more pass rebuilds exactly when that happened.
2175    if deferred_asset_changes.is_some()
2176        && !build_excludes_asset_outputs(root, config, build.final_root_inputs())
2177    {
2178        dev_ui::detail!("this build reads a generated asset; rebuilding now that assets are final");
2179        let first = std::mem::replace(&mut build, run_dev_cargo(&prepared, session)?);
2180        let stale = first
2181            .executable()
2182            .filter(|path| Some(*path) != build.executable())
2183            .map(Path::to_path_buf);
2184        drop(first);
2185        if let Some(stale) = stale {
2186            prune_final_artifact_snapshot(&stale);
2187        }
2188    }
2189
2190    match build {
2191        DevCargoBuild::SinglePass(output) => {
2192            let executable = select_attested_root_executable(
2193                &prepared.request,
2194                output.final_cargo.plan_id,
2195                output.semantic.plan_id,
2196                &output.semantic_plan_path,
2197                &output.final_root_artifact,
2198                LinkedCargoAction::Dev,
2199            )?;
2200            let public_assets =
2201                public_assets::publish(root, public_source, &prepared.public_output_directory)?;
2202            let reused_final_artifacts = output
2203                .final_cargo
2204                .cargo_artifacts
2205                .iter()
2206                .filter(|artifact| artifact.fresh)
2207                .count();
2208            dev_ui::detail!(
2209                "linked RSJS dev plan {} (single-pass; final cache: {reused_final_artifacts}/{} reused)",
2210                output.semantic.plan_id,
2211                output.final_cargo.cargo_artifacts.len(),
2212            );
2213            let compiled_inputs =
2214                collect_compiled_source_inputs_from_paths(output.final_root_inputs.as_deref());
2215            Ok(LinkedDevLaunch {
2216                executable,
2217                arguments: prepared.runtime_args,
2218                plan_id: output.semantic.plan_id.to_string(),
2219                single_pass: true,
2220                descriptor_artifacts: 0,
2221                reused_descriptor_artifacts: 0,
2222                reused_final_artifacts,
2223                public_assets,
2224                compiled_inputs,
2225                _snapshot_lease: output.final_root_lease,
2226            })
2227        }
2228        DevCargoBuild::Full(output) => {
2229            let executable =
2230                select_final_root_executable(&prepared.request, &output, LinkedCargoAction::Dev)?;
2231            let public_assets =
2232                public_assets::publish(root, public_source, &prepared.public_output_directory)?;
2233            let descriptor_artifacts = output.descriptor.cargo_artifacts.len();
2234            let reused_descriptor_artifacts = output
2235                .descriptor
2236                .cargo_artifacts
2237                .iter()
2238                .filter(|artifact| artifact.fresh)
2239                .count();
2240            let reused_final_artifacts = output
2241                .final_cargo
2242                .cargo_artifacts
2243                .iter()
2244                .filter(|artifact| artifact.fresh)
2245                .count();
2246            dev_ui::detail!(
2247                "linked RSJS dev plan {} (descriptor cache: {reused_descriptor_artifacts}/{descriptor_artifacts} Cargo artifacts reused; final cache: {reused_final_artifacts}/{} reused)",
2248                output.semantic.plan_id,
2249                output.final_cargo.cargo_artifacts.len(),
2250            );
2251
2252            let compiled_inputs = collect_compiled_source_inputs(&output);
2253            Ok(LinkedDevLaunch {
2254                executable,
2255                arguments: prepared.runtime_args,
2256                plan_id: output.semantic.plan_id.to_string(),
2257                single_pass: false,
2258                descriptor_artifacts,
2259                reused_descriptor_artifacts,
2260                reused_final_artifacts,
2261                public_assets,
2262                compiled_inputs,
2263                _snapshot_lease: output.final_root_lease.clone(),
2264            })
2265        }
2266    }
2267}
2268
2269// Cargo can be quiet while downloading, linking, or validating cached build
2270// artifacts. Keep the dev terminal visibly active until the entire build ends.
2271struct DevBuildProgress {
2272    done: std::sync::mpsc::Sender<()>,
2273    thread: Option<thread::JoinHandle<()>>,
2274}
2275
2276impl DevBuildProgress {
2277    fn start() -> Self {
2278        use std::sync::mpsc::{self, RecvTimeoutError};
2279
2280        let (done, receiver) = mpsc::channel();
2281        let pretty = dev_ui::pretty();
2282        let interval = if pretty {
2283            dev_ui::SPIN_INTERVAL
2284        } else {
2285            Duration::from_secs(10)
2286        };
2287        let thread = thread::spawn(move || {
2288            let started = Instant::now();
2289            while matches!(
2290                receiver.recv_timeout(interval),
2291                Err(RecvTimeoutError::Timeout)
2292            ) {
2293                if pretty {
2294                    dev_ui::spin(started);
2295                } else {
2296                    eprintln!(
2297                        "Still building your site ({}s elapsed)...",
2298                        started.elapsed().as_secs()
2299                    );
2300                }
2301            }
2302            if pretty {
2303                dev_ui::clear_spinner();
2304            }
2305        });
2306        Self {
2307            done,
2308            thread: Some(thread),
2309        }
2310    }
2311}
2312
2313impl Drop for DevBuildProgress {
2314    fn drop(&mut self) {
2315        let _ = self.done.send(());
2316        if let Some(thread) = self.thread.take() {
2317            let _ = thread.join();
2318        }
2319    }
2320}
2321
2322fn select_final_root_executable(
2323    request: &LinkedCargoRequest,
2324    output: &LinkedCargoOutput,
2325    action: LinkedCargoAction,
2326) -> Result<PathBuf> {
2327    select_attested_root_executable(
2328        request,
2329        output.final_cargo.plan_id,
2330        output.semantic.plan_id,
2331        &output.semantic_plan_path,
2332        &output.final_root_artifact,
2333        action,
2334    )
2335}
2336
2337fn select_attested_root_executable(
2338    request: &LinkedCargoRequest,
2339    final_plan_id: rsjs_ir::abi::PlanId,
2340    semantic_plan_id: rsjs_ir::abi::PlanId,
2341    semantic_plan_path: &Path,
2342    artifact: &crate::rsjs::build::CargoCompilerArtifact,
2343    action: LinkedCargoAction,
2344) -> Result<PathBuf> {
2345    if final_plan_id != semantic_plan_id {
2346        bail!(
2347            "linked {} final Cargo consumed plan {}, but the semantic linker produced {}",
2348            action.command_name(),
2349            final_plan_id,
2350            semantic_plan_id
2351        );
2352    }
2353    if !semantic_plan_path.is_file() {
2354        bail!(
2355            "linked {} semantic plan disappeared before executable selection: `{}`",
2356            action.command_name(),
2357            semantic_plan_path.display()
2358        );
2359    }
2360
2361    if artifact.package_id != request.root.package_id
2362        || artifact.target.name != request.root.target_name
2363        || artifact.target.kind != request.root.target_kinds
2364    {
2365        bail!(
2366            "attested final root no longer matches linked {} package `{}` target `{}`",
2367            action.command_name(),
2368            request.root.package_id,
2369            request.root.target_name
2370        );
2371    }
2372    let executable = artifact.executable.clone().ok_or_else(|| {
2373        anyhow::anyhow!(
2374            "final linked Cargo build emitted no executable for package `{}` binary `{}`",
2375            request.root.package_id,
2376            request.root.target_name
2377        )
2378    })?;
2379    if !executable.is_absolute() || !executable.is_file() {
2380        bail!(
2381            "final linked Cargo executable is not an existing absolute file: `{}`",
2382            executable.display()
2383        );
2384    }
2385    Ok(executable)
2386}
2387
2388fn resolve_artifact_output(root: &Path, requested: &Path) -> PathBuf {
2389    if requested.is_absolute() {
2390        requested.to_path_buf()
2391    } else {
2392        root.join(requested)
2393    }
2394}
2395
2396fn warn_if_artifact_output_enters_source_closure(
2397    destination: &Path,
2398    package_source_root: &Path,
2399    source_exclusion: &Path,
2400) {
2401    if artifact_output_enters_source_closure(destination, package_source_root, source_exclusion) {
2402        eprintln!(
2403            "warning[proa/artifact-out-source-closure]: artifact output `{}` is inside selected package `{}` and will participate in its next source-closure check; use the Cargo target directory or a path outside the package for warm rebuilds",
2404            destination.display(),
2405            package_source_root.display()
2406        );
2407    }
2408}
2409
2410fn artifact_output_enters_source_closure(
2411    destination: &Path,
2412    package_source_root: &Path,
2413    source_exclusion: &Path,
2414) -> bool {
2415    let Some(destination) = normalize_absolute_lexical_path(destination) else {
2416        return destination.starts_with(package_source_root);
2417    };
2418    let Some(package_source_root) = normalize_absolute_lexical_path(package_source_root) else {
2419        return false;
2420    };
2421    let Some(source_exclusion) = normalize_absolute_lexical_path(source_exclusion) else {
2422        return false;
2423    };
2424    if !destination.starts_with(&package_source_root) || destination.starts_with(&source_exclusion)
2425    {
2426        return false;
2427    }
2428    let Ok(relative) = destination.strip_prefix(&package_source_root) else {
2429        return false;
2430    };
2431    let mut components = relative
2432        .components()
2433        .filter_map(|component| match component {
2434            std::path::Component::Normal(value) => Some(value),
2435            _ => None,
2436        });
2437    let Some(first) = components.next() else {
2438        return true;
2439    };
2440    if matches!(
2441        first.to_str(),
2442        Some(".git" | ".hg" | ".svn" | ".jj" | "target" | "node_modules")
2443    ) {
2444        return false;
2445    }
2446    !components.any(|component| component == OsStr::new("node_modules"))
2447}
2448
2449fn normalize_absolute_lexical_path(path: &Path) -> Option<PathBuf> {
2450    use std::path::Component;
2451
2452    if !path.is_absolute() {
2453        return None;
2454    }
2455    let mut normalized = PathBuf::new();
2456    for component in path.components() {
2457        match component {
2458            Component::Prefix(_) | Component::RootDir | Component::Normal(_) => {
2459                normalized.push(component.as_os_str());
2460            }
2461            Component::CurDir => {}
2462            Component::ParentDir => {
2463                if !normalized.pop() {
2464                    return None;
2465                }
2466            }
2467        }
2468    }
2469    Some(normalized)
2470}
2471
2472fn copy_executable_atomically(source: &Path, destination: &Path) -> io::Result<()> {
2473    if source == destination {
2474        return Ok(());
2475    }
2476    if destination.is_dir() {
2477        return Err(io::Error::new(
2478            io::ErrorKind::InvalidInput,
2479            format!(
2480                "artifact output must name a file, but `{}` is a directory",
2481                destination.display()
2482            ),
2483        ));
2484    }
2485
2486    let parent = destination.parent().ok_or_else(|| {
2487        io::Error::new(
2488            io::ErrorKind::InvalidInput,
2489            format!(
2490                "artifact output `{}` has no parent directory",
2491                destination.display()
2492            ),
2493        )
2494    })?;
2495    fs::create_dir_all(parent)?;
2496
2497    let file_name = destination.file_name().ok_or_else(|| {
2498        io::Error::new(
2499            io::ErrorKind::InvalidInput,
2500            format!(
2501                "artifact output `{}` does not name a file",
2502                destination.display()
2503            ),
2504        )
2505    })?;
2506    let (temporary, mut temporary_file) = loop {
2507        let nonce = RSJS_BUILD_NONCE.fetch_add(1, Ordering::Relaxed);
2508        let candidate = parent.join(format!(
2509            ".{}.proa-export-{}-{nonce}",
2510            file_name.to_string_lossy(),
2511            std::process::id()
2512        ));
2513        match fs::OpenOptions::new()
2514            .create_new(true)
2515            .write(true)
2516            .open(&candidate)
2517        {
2518            Ok(file) => break (candidate, file),
2519            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
2520            Err(error) => return Err(error),
2521        }
2522    };
2523
2524    let copy_result = (|| {
2525        let mut source_file = fs::File::open(source)?;
2526        let source_permissions = source_file.metadata()?.permissions();
2527        io::copy(&mut source_file, &mut temporary_file)?;
2528        temporary_file.set_permissions(source_permissions)?;
2529        temporary_file.sync_all()?;
2530        drop(temporary_file);
2531        replace_file(&temporary, destination)
2532    })();
2533
2534    if copy_result.is_err() {
2535        let _ = fs::remove_file(&temporary);
2536    }
2537    copy_result
2538}
2539
2540#[cfg(not(windows))]
2541fn replace_file(source: &Path, destination: &Path) -> io::Result<()> {
2542    fs::rename(source, destination)
2543}
2544
2545#[cfg(windows)]
2546fn replace_file(source: &Path, destination: &Path) -> io::Result<()> {
2547    use std::os::windows::ffi::OsStrExt;
2548    use windows_sys::Win32::Storage::FileSystem::{
2549        MoveFileExW, MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH,
2550    };
2551
2552    let source: Vec<u16> = source.as_os_str().encode_wide().chain(Some(0)).collect();
2553    let destination: Vec<u16> = destination
2554        .as_os_str()
2555        .encode_wide()
2556        .chain(Some(0))
2557        .collect();
2558    let moved = unsafe {
2559        MoveFileExW(
2560            source.as_ptr(),
2561            destination.as_ptr(),
2562            MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
2563        )
2564    };
2565    if moved == 0 {
2566        Err(io::Error::last_os_error())
2567    } else {
2568        Ok(())
2569    }
2570}
2571
2572fn configured_binary(config: &ProjectConfig) -> Option<String> {
2573    config
2574        .application
2575        .as_ref()
2576        .map(|application| application.binary.as_str())
2577        .filter(|value| !value.is_empty())
2578        .map(ToString::to_string)
2579}
2580
2581fn snapshot_generated_public_outputs(
2582    root: &Path,
2583    config: &ProjectConfig,
2584    public: &Path,
2585    snapshot: &WatchSnapshot,
2586) -> Result<BTreeMap<PathBuf, [u8; 32]>> {
2587    let mut digests = BTreeMap::new();
2588    let css_output = crate::config::css_script_output(config);
2589    for output in config
2590        .build
2591        .assets()
2592        .iter()
2593        .map(|asset| asset.output.as_path())
2594        .chain(css_output.as_deref())
2595    {
2596        if output.as_os_str().is_empty() || !output.starts_with(public) {
2597            continue;
2598        }
2599        let Some(&expected_stamp) = snapshot.get(output) else {
2600            continue;
2601        };
2602        let full = root.join(output);
2603        let Ok(metadata) = fs::symlink_metadata(&full) else {
2604            continue;
2605        };
2606        if !metadata.file_type().is_file() || FileStamp::from_metadata(&metadata) != expected_stamp
2607        {
2608            // File changed after `snapshot` was taken; do not consume it.
2609            continue;
2610        }
2611        let bytes = fs::read(&full).with_context(|| format!("read {}", full.display()))?;
2612        let post_read =
2613            fs::symlink_metadata(&full).with_context(|| format!("stat {}", full.display()))?;
2614        if !post_read.file_type().is_file()
2615            || FileStamp::from_metadata(&post_read) != expected_stamp
2616        {
2617            continue;
2618        }
2619        digests.insert(output.to_path_buf(), Sha256::digest(&bytes).into());
2620    }
2621    Ok(digests)
2622}
2623
2624fn all_unchanged_generated_outputs(
2625    root: &Path,
2626    changed_public: &[&PathBuf],
2627    before: &BTreeMap<PathBuf, [u8; 32]>,
2628    post_assets: &WatchSnapshot,
2629) -> Result<bool> {
2630    for path in changed_public {
2631        let Some(expected_digest) = before.get(*path) else {
2632            return Ok(false);
2633        };
2634        let Some(&expected_stamp) = post_assets.get(*path) else {
2635            return Ok(false);
2636        };
2637        let full = root.join(path);
2638        let Ok(metadata) = fs::symlink_metadata(&full) else {
2639            return Ok(false);
2640        };
2641        if !metadata.file_type().is_file() || FileStamp::from_metadata(&metadata) != expected_stamp
2642        {
2643            return Ok(false);
2644        }
2645        let bytes = fs::read(&full).with_context(|| format!("read {}", full.display()))?;
2646        let post_read =
2647            fs::symlink_metadata(&full).with_context(|| format!("stat {}", full.display()))?;
2648        if !post_read.file_type().is_file()
2649            || FileStamp::from_metadata(&post_read) != expected_stamp
2650            || Sha256::digest(&bytes).as_slice() != expected_digest
2651        {
2652            return Ok(false);
2653        }
2654    }
2655    Ok(true)
2656}
2657
2658fn dev_command(options: &DevOptions, config: &ProjectConfig) -> Vec<String> {
2659    let mut command = if options.command.is_empty() {
2660        let mut command = vec!["cargo".into(), "run".into()];
2661        if let Some(bin) = configured_binary(config) {
2662            command.push("--bin".into());
2663            command.push(bin);
2664        }
2665        command
2666    } else {
2667        options.command.clone()
2668    };
2669    if options.offline {
2670        let cargo_end = command
2671            .iter()
2672            .position(|arg| arg == "--")
2673            .unwrap_or(command.len());
2674        if !command[..cargo_end].iter().any(|arg| arg == "--offline") {
2675            command.insert(cargo_end, "--offline".into());
2676        }
2677    }
2678    command
2679}
2680
2681fn build_command(options: &BuildOptions) -> Vec<String> {
2682    let mut command = if !options.command.is_empty() {
2683        options.command.clone()
2684    } else if let Some(profile) = &options.profile {
2685        vec![
2686            "cargo".into(),
2687            "build".into(),
2688            "--profile".into(),
2689            profile.clone(),
2690        ]
2691    } else {
2692        vec!["cargo".into(), "build".into(), "--release".into()]
2693    };
2694
2695    if let Some(package) = &options.package {
2696        command.push("-p".into());
2697        command.push(package.clone());
2698    }
2699    if let Some(bin) = &options.bin {
2700        command.push("--bin".into());
2701        command.push(bin.clone());
2702    }
2703    if let Some(example) = &options.example {
2704        command.push("--example".into());
2705        command.push(example.clone());
2706    }
2707    if let Some(target) = &options.target {
2708        command.push("--target".into());
2709        command.push(target.clone());
2710    }
2711    if !options.features.is_empty() {
2712        command.push("--features".into());
2713        command.push(options.features.join(","));
2714    }
2715    if options.all_features {
2716        command.push("--all-features".into());
2717    }
2718    if options.no_default_features {
2719        command.push("--no-default-features".into());
2720    }
2721    if options.locked {
2722        command.push("--locked".into());
2723    }
2724    if options.offline {
2725        command.push("--offline".into());
2726    }
2727
2728    command
2729}
2730
2731fn check_command(options: &CheckOptions) -> Vec<String> {
2732    let mut command = vec!["cargo".into(), "check".into()];
2733    append_cargo_selection(
2734        &mut command,
2735        options.profile.as_deref(),
2736        options.package.as_deref(),
2737        options.bin.as_deref(),
2738        options.target.as_deref(),
2739        &options.features,
2740        options.all_features,
2741        options.no_default_features,
2742        options.locked,
2743        options.offline,
2744    );
2745    command
2746}
2747
2748fn run_command(options: &RunOptions) -> Vec<String> {
2749    let mut command = vec!["cargo".into(), "run".into()];
2750    append_cargo_selection(
2751        &mut command,
2752        options.profile.as_deref(),
2753        options.package.as_deref(),
2754        options.bin.as_deref(),
2755        options.target.as_deref(),
2756        &options.features,
2757        options.all_features,
2758        options.no_default_features,
2759        options.locked,
2760        options.offline,
2761    );
2762    append_runtime_arguments(&mut command, &options.arguments);
2763    command
2764}
2765
2766fn test_command(options: &TestOptions) -> Vec<String> {
2767    let mut command = vec!["cargo".into(), "test".into()];
2768    append_cargo_selection(
2769        &mut command,
2770        options.profile.as_deref(),
2771        options.package.as_deref(),
2772        options.bin.as_deref(),
2773        options.target.as_deref(),
2774        &options.features,
2775        options.all_features,
2776        options.no_default_features,
2777        options.locked,
2778        options.offline,
2779    );
2780    if let Some(test) = &options.test {
2781        command.push("--test".into());
2782        command.push(test.clone());
2783    }
2784    append_runtime_arguments(&mut command, &options.arguments);
2785    command
2786}
2787
2788fn append_runtime_arguments(command: &mut Vec<String>, arguments: &[String]) {
2789    if !arguments.is_empty() {
2790        command.push("--".into());
2791        command.extend(arguments.iter().cloned());
2792    }
2793}
2794
2795fn append_cargo_selection(
2796    command: &mut Vec<String>,
2797    profile: Option<&str>,
2798    package: Option<&str>,
2799    bin: Option<&str>,
2800    target: Option<&str>,
2801    features: &[String],
2802    all_features: bool,
2803    no_default_features: bool,
2804    locked: bool,
2805    offline: bool,
2806) {
2807    if let Some(profile) = profile {
2808        command.push("--profile".into());
2809        command.push(profile.into());
2810    }
2811    if let Some(package) = package {
2812        command.push("-p".into());
2813        command.push(package.into());
2814    }
2815    if let Some(bin) = bin {
2816        command.push("--bin".into());
2817        command.push(bin.into());
2818    }
2819    if let Some(target) = target {
2820        command.push("--target".into());
2821        command.push(target.into());
2822    }
2823    if !features.is_empty() {
2824        command.push("--features".into());
2825        command.push(features.join(","));
2826    }
2827    if all_features {
2828        command.push("--all-features".into());
2829    }
2830    if no_default_features {
2831        command.push("--no-default-features".into());
2832    }
2833    if locked {
2834        command.push("--locked".into());
2835    }
2836    if offline {
2837        command.push("--offline".into());
2838    }
2839}
2840
2841#[derive(Debug, Clone, PartialEq, Eq)]
2842struct ParsedCargoInvocation {
2843    cargo: OsString,
2844    cargo_args: Vec<OsString>,
2845    runtime_args: Vec<OsString>,
2846    package: Option<String>,
2847    bin: Option<String>,
2848    example: Option<String>,
2849    test: Option<String>,
2850    profile: String,
2851    target: Option<String>,
2852    features: BTreeSet<String>,
2853    locked: bool,
2854    offline: bool,
2855    metadata_flags: Vec<OsString>,
2856    selection_args: Vec<String>,
2857}
2858
2859#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2860enum LinkedCargoAction {
2861    Build,
2862    Check,
2863    Dev,
2864    Run,
2865    Test,
2866}
2867
2868impl LinkedCargoAction {
2869    const fn command_name(self) -> &'static str {
2870        match self {
2871            Self::Build => "build",
2872            Self::Check => "check",
2873            Self::Dev => "dev",
2874            Self::Run => "run",
2875            Self::Test => "test",
2876        }
2877    }
2878
2879    const fn subcommand(self) -> &'static str {
2880        match self {
2881            Self::Build => "build",
2882            Self::Check => "check",
2883            Self::Dev => "run",
2884            Self::Run => "run",
2885            Self::Test => "test",
2886        }
2887    }
2888
2889    const fn final_subcommand(self) -> &'static str {
2890        match self {
2891            Self::Build => "build",
2892            Self::Check => "check",
2893            Self::Dev => "build",
2894            Self::Run => "run",
2895            Self::Test => "test",
2896        }
2897    }
2898
2899    const fn descriptor_subcommand(self) -> &'static str {
2900        match self {
2901            Self::Test => "test",
2902            Self::Check => "check",
2903            Self::Build | Self::Dev | Self::Run => "build",
2904        }
2905    }
2906
2907    const fn permits_runtime_arguments(self) -> bool {
2908        matches!(self, Self::Dev | Self::Run | Self::Test)
2909    }
2910
2911    const fn final_cargo_executes(self) -> bool {
2912        matches!(self, Self::Run | Self::Test)
2913    }
2914
2915    const fn root_role(self) -> ArtifactRole {
2916        match self {
2917            Self::Test => ArtifactRole::RootTest,
2918            Self::Build | Self::Check | Self::Dev | Self::Run => ArtifactRole::RootExecutable,
2919        }
2920    }
2921
2922    const fn descriptor_identity_marker(self) -> &'static str {
2923        match self {
2924            Self::Test => "proa:descriptor-mode=test-no-run",
2925            Self::Check => "proa:descriptor-mode=check",
2926            Self::Build | Self::Dev | Self::Run => "proa:descriptor-mode=build",
2927        }
2928    }
2929}
2930
2931#[derive(Debug)]
2932struct PreparedLinkedCargo {
2933    request: LinkedCargoRequest,
2934    profile: String,
2935    target_triple: Option<String>,
2936    runtime_args: Vec<OsString>,
2937    descriptor_cache_directory: PathBuf,
2938    package_source_root: PathBuf,
2939    public_output_directory: PathBuf,
2940    // Windows cannot safely relocate arbitrary PE executables without a
2941    // complete delay-import contract. Hold a no-write/no-delete sharing lock
2942    // instead so the fingerprinted wrapper path cannot be replaced before
2943    // Cargo opens it. Other hosts execute a content-addressed snapshot.
2944    _wrapper_lock: Option<fs::File>,
2945}
2946
2947#[derive(Debug, Deserialize)]
2948struct CargoMetadata {
2949    packages: Vec<CargoMetadataPackage>,
2950    workspace_members: Vec<String>,
2951    #[serde(default)]
2952    workspace_default_members: Vec<String>,
2953    target_directory: PathBuf,
2954}
2955
2956#[derive(Debug, Deserialize)]
2957struct CargoMetadataPackage {
2958    id: String,
2959    name: String,
2960    version: String,
2961    manifest_path: PathBuf,
2962    targets: Vec<CargoMetadataTarget>,
2963}
2964
2965#[derive(Debug, Deserialize)]
2966struct CargoMetadataTarget {
2967    name: String,
2968    kind: Vec<String>,
2969}
2970
2971#[derive(Debug)]
2972struct ExactCargoRoot {
2973    package_id: String,
2974    package_name: String,
2975    package_source_root: PathBuf,
2976    target_name: String,
2977    target_kinds: BTreeSet<String>,
2978    requested_target_kind: String,
2979}
2980
2981fn prepare_linked_cargo(
2982    root: &Path,
2983    command: &[String],
2984    action: LinkedCargoAction,
2985) -> Result<PreparedLinkedCargo> {
2986    prepare_linked_cargo_with_environment(root, command, action, &BTreeMap::new())
2987}
2988
2989fn prepare_linked_cargo_with_environment(
2990    root: &Path,
2991    command: &[String],
2992    action: LinkedCargoAction,
2993    environment: &BTreeMap<OsString, OsString>,
2994) -> Result<PreparedLinkedCargo> {
2995    prepare_linked_cargo_with_environment_and_session(root, command, action, environment, None)
2996}
2997
2998fn prepare_linked_cargo_with_environment_and_session(
2999    root: &Path,
3000    command: &[String],
3001    action: LinkedCargoAction,
3002    environment: &BTreeMap<OsString, OsString>,
3003    session: Option<&mut DevSessionCache>,
3004) -> Result<PreparedLinkedCargo> {
3005    let wrapper =
3006        crate::util::current_executable().context("resolve the cargo-proa wrapper executable")?;
3007    prepare_linked_cargo_with_wrapper_and_environment_and_session(
3008        root,
3009        command,
3010        action,
3011        wrapper,
3012        environment,
3013        session,
3014    )
3015}
3016
3017#[cfg(test)]
3018fn prepare_linked_cargo_with_wrapper(
3019    root: &Path,
3020    command: &[String],
3021    action: LinkedCargoAction,
3022    wrapper: PathBuf,
3023) -> Result<PreparedLinkedCargo> {
3024    prepare_linked_cargo_with_wrapper_and_environment_and_session(
3025        root,
3026        command,
3027        action,
3028        wrapper,
3029        &BTreeMap::new(),
3030        None,
3031    )
3032}
3033
3034fn prepare_linked_cargo_with_wrapper_and_environment_and_session(
3035    root: &Path,
3036    command: &[String],
3037    action: LinkedCargoAction,
3038    wrapper: PathBuf,
3039    environment: &BTreeMap<OsString, OsString>,
3040    session: Option<&mut DevSessionCache>,
3041) -> Result<PreparedLinkedCargo> {
3042    if !wrapper.is_absolute() {
3043        bail!(
3044            "the cargo-proa wrapper executable is not absolute: `{}`",
3045            wrapper.display()
3046        );
3047    }
3048    let parsed = parse_cargo_command(command, action)?;
3049    let mut timer = crate::rsjs::timing::StageTimer::new();
3050    // Query every current tool and Cargo's authoritative metadata on each
3051    // cycle. They are independent subprocesses; overlapping them avoids
3052    // adding their startup costs together without caching mutable tool state.
3053    let (metadata, cargo_version, rustc_version) = thread::scope(|scope| {
3054        let cargo = scope.spawn(|| tool_version(&parsed.cargo, &["-Vv"], "Cargo", root));
3055        let rustc = scope.spawn(|| selected_rustc_version(root));
3056        let metadata = load_cargo_metadata(root, &parsed);
3057        let cargo = cargo
3058            .join()
3059            .map_err(|_| anyhow::anyhow!("Cargo version query thread panicked"))
3060            .and_then(|result| result);
3061        let rustc = rustc
3062            .join()
3063            .map_err(|_| anyhow::anyhow!("rustc version query thread panicked"))
3064            .and_then(|result| result);
3065        (metadata, cargo, rustc)
3066    });
3067    let metadata = metadata?;
3068    let cargo_version = cargo_version?;
3069    let rustc_version = rustc_version?;
3070    timer.mark("prepare Cargo metadata and tool versions");
3071    let selected_root = select_exact_cargo_root(&metadata, &parsed, action)?;
3072    let public_output_directory =
3073        public_assets::output_directory(&metadata.target_directory, &selected_root, &parsed)?;
3074    if !metadata.target_directory.is_absolute() {
3075        bail!(
3076            "Cargo metadata returned a relative target directory `{}`; the linked RSJS pipeline requires an exact absolute artifact namespace",
3077            metadata.target_directory.display()
3078        );
3079    }
3080    let wrapper_snapshot_root = metadata
3081        .target_directory
3082        .join("proa-rsjs")
3083        .join("wrapper-snapshots-v1");
3084    let (wrapper, wrapper_lock, wrapper_fingerprint) = prepare_wrapper_with_session(
3085        &metadata.target_directory,
3086        &wrapper_snapshot_root,
3087        &wrapper,
3088        session,
3089    )?;
3090    timer.mark("prepare wrapper snapshot and fingerprint");
3091    let package_source_root = selected_root.package_source_root.clone();
3092    let cli_producer = cli_tool_producer_version()?;
3093    let mut selection_args = parsed.selection_args.clone();
3094    // A binary compiled as a test harness is a different Cargo/rustc unit from
3095    // the same binary compiled normally. Keep that mode in the pre-Cargo
3096    // identity so persistent descriptor targets and caches cannot alias.
3097    selection_args.push(action.descriptor_identity_marker().to_string());
3098    // Producer semver is insufficient during local development and rolling
3099    // upgrades: the same absolute executable path can be atomically replaced
3100    // with different wrapper behavior. Bind every persistent descriptor and
3101    // final Cargo namespace to the exact wrapper bytes that will be invoked.
3102    selection_args.push(format!(
3103        "proa:wrapper-executable-fingerprint={wrapper_fingerprint}"
3104    ));
3105    let shared_target_scope = shared_cargo_target_scope(
3106        &wrapper_fingerprint,
3107        &cargo_version,
3108        &rustc_version,
3109        cli_producer,
3110    );
3111    let invocation_spec = InvocationSpec {
3112        roots: BTreeSet::from([RequestedRootTarget {
3113            package: selected_root.package_id.clone(),
3114            target_kind: selected_root.requested_target_kind.clone(),
3115            target_name: Some(selected_root.target_name.clone()),
3116        }]),
3117        target_triple: parsed.target.clone(),
3118        features: parsed.features.clone(),
3119        profile: parsed.profile.clone(),
3120        cargo_config: BTreeMap::new(),
3121        locked: parsed.locked,
3122        offline: parsed.offline,
3123        selection_args,
3124        // Test fixture values are supplied identically to descriptor and final
3125        // Cargo below, but are not semantic target selectors. Cargo build
3126        // scripts and the wrapper's observed-environment sidecars still
3127        // invalidate units that actually consume one of these values.
3128        environment: declared_build_environment(),
3129        toolchain: BuildToolchain {
3130            cargo: cargo_version,
3131            rustc: rustc_version,
3132            proa: cli_producer,
3133            compiler_abi: RSJS_COMPILER_ABI,
3134            transport_version: TRANSPORT_FORMAT_VERSION,
3135        },
3136    };
3137    let invocation = invocation_spec
3138        .invocation_id()
3139        .context("derive the pre-descriptor RSJS invocation identity")?;
3140
3141    // Windows linkers and native build tools can still impose MAX_PATH even
3142    // when Rust accepts long paths. Keep full cache identities, but spend fewer
3143    // characters on descriptive directory labels before Cargo adds its tree.
3144    //
3145    // Cargo already isolates profiles, features, target triples, and bin/test
3146    // roots inside one `--target-dir`, and the descriptor cache keys every unit
3147    // and snapshot by its exact Cargo coordinate. Share one Cargo target and
3148    // content-addressed descriptor cache per wrapper+toolchain scope so `dev`,
3149    // `test` (across multiple integration tests), `check`, and `build` reuse
3150    // compiled dependencies instead of multiplying `target/` by every target.
3151    let namespace = metadata.target_directory.join(TOOL_NAMESPACE_DIR);
3152    let build_root = namespace.join(invocation.to_string());
3153    let shared_root = namespace
3154        .join(if cfg!(windows) { "s" } else { "shared" })
3155        .join(&shared_target_scope);
3156    let source_exclusion_directory = metadata.target_directory.clone();
3157    let nonce = fresh_build_nonce();
3158    let descriptor_staging = build_root
3159        .join(if cfg!(windows) {
3160            "s"
3161        } else {
3162            "descriptor-staging"
3163        })
3164        .join(&nonce);
3165    let descriptor_target = shared_root.join(if cfg!(windows) {
3166        format!("d{DESCRIPTOR_TARGET_POLICY_VERSION}-{DESCRIPTOR_UNIT_SIDECAR_SCHEMA_VERSION}-{PERSISTENT_DESCRIPTOR_TARGET_LAYOUT_VERSION}")
3167    } else {
3168        format!("descriptor-target-policy-v{DESCRIPTOR_TARGET_POLICY_VERSION}-sidecar-v{DESCRIPTOR_UNIT_SIDECAR_SCHEMA_VERSION}-persistent-v{PERSISTENT_DESCRIPTOR_TARGET_LAYOUT_VERSION}")
3169    });
3170    let descriptor_cache_directory = shared_root.join(if cfg!(windows) {
3171        format!("c{DESCRIPTOR_CACHE_SCHEMA_VERSION}")
3172    } else {
3173        format!("descriptor-cache-v{DESCRIPTOR_CACHE_SCHEMA_VERSION}")
3174    });
3175    let plan_directory = namespace.join(if cfg!(windows) { "p" } else { "plans" });
3176    let final_target_root = namespace
3177        .join(if cfg!(windows) { "f" } else { "final-target" })
3178        .join(&shared_target_scope);
3179    let mut descriptor_cargo_args = parsed.cargo_args.clone();
3180    // The wrapper adds one explicit object output even when Cargo selected
3181    // `check`, so linked checks can keep descriptor and final rustc unit
3182    // coordinates identical. Tests require their exact `cfg(test)`/harness
3183    // compilation, so both phases use `cargo test`. The descriptor harness
3184    // never runs. Managed tests launch the final harness after publication.
3185    descriptor_cargo_args[0] = OsString::from(action.descriptor_subcommand());
3186    if action == LinkedCargoAction::Test {
3187        descriptor_cargo_args.push("--no-run".into());
3188    }
3189    let mut final_cargo_args = parsed.cargo_args.clone();
3190    final_cargo_args[0] = OsString::from(action.final_subcommand());
3191    if action.final_cargo_executes() && !parsed.runtime_args.is_empty() {
3192        final_cargo_args.push("--".into());
3193        final_cargo_args.extend(parsed.runtime_args.iter().cloned());
3194    }
3195
3196    Ok(PreparedLinkedCargo {
3197        request: LinkedCargoRequest {
3198            descriptor: DescriptorCargoRequest {
3199                cargo: parsed.cargo,
3200                wrapper,
3201                working_directory: root.to_path_buf(),
3202                staging_directory: descriptor_staging,
3203                target_directory: descriptor_target,
3204                source_exclusion_directory,
3205                cargo_args: descriptor_cargo_args,
3206                environment: environment.clone(),
3207            },
3208            root: DescriptorRootSelector {
3209                package_id: selected_root.package_id,
3210                target_name: selected_root.target_name,
3211                target_kinds: selected_root.target_kinds,
3212                role: action.root_role(),
3213                artifact_path: None,
3214            },
3215            invocation,
3216            producer: RSJS_COMPILER_PRODUCER,
3217            runtime_protocol: RSJS_RUNTIME_PROTOCOL,
3218            plan_directory,
3219            final_target_root,
3220            final_cargo_args,
3221            final_environment: environment.clone(),
3222        },
3223        profile: parsed.profile,
3224        target_triple: parsed.target,
3225        runtime_args: parsed.runtime_args,
3226        descriptor_cache_directory,
3227        package_source_root,
3228        public_output_directory,
3229        _wrapper_lock: wrapper_lock,
3230    })
3231}
3232
3233fn shared_cargo_target_scope(
3234    wrapper_fingerprint: &str,
3235    cargo_version: &str,
3236    rustc_version: &str,
3237    cli_producer: ProducerVersion,
3238) -> String {
3239    let mut hash = Sha256::new();
3240    hash.update(b"proa.rsjs.shared-cargo-target-scope.v1\0");
3241    let producer = format!(
3242        "{}.{}.{}",
3243        cli_producer.major, cli_producer.minor, cli_producer.patch
3244    );
3245    let abi = format!("{}.{}", RSJS_COMPILER_ABI.major, RSJS_COMPILER_ABI.minor);
3246    let transport = TRANSPORT_FORMAT_VERSION.to_string();
3247    for field in [
3248        wrapper_fingerprint,
3249        cargo_version,
3250        rustc_version,
3251        &producer,
3252        &abi,
3253        &transport,
3254    ] {
3255        hash.update((field.len() as u64).to_le_bytes());
3256        hash.update(field.as_bytes());
3257    }
3258    let digest = hash.finalize();
3259    format!("{:x}", base16ct::HexDisplay(&digest[..8]))
3260}
3261
3262#[cfg(not(windows))]
3263fn prepare_wrapper_with_session(
3264    source_exclusion: &Path,
3265    snapshot_root: &Path,
3266    wrapper: &Path,
3267    session: Option<&mut DevSessionCache>,
3268) -> Result<(PathBuf, Option<fs::File>, String)> {
3269    let source_stamp = fs::metadata(wrapper)
3270        .ok()
3271        .map(|m| FileStamp::from_metadata(&m));
3272    if let (Some(cache), Some(stamp)) = (session.as_deref(), source_stamp) {
3273        if let Some(cached) = &cache.wrapper_snapshot {
3274            if cached.source_path == wrapper
3275                && cached.source_stamp == stamp
3276                && cached.snapshot_root == snapshot_root
3277                && cached.snapshot_path.is_file()
3278            {
3279                return Ok((
3280                    cached.snapshot_path.clone(),
3281                    None,
3282                    cached.fingerprint.clone(),
3283                ));
3284            }
3285        }
3286    }
3287    let (snapshot, lock) = prepare_wrapper_executable(source_exclusion, snapshot_root, wrapper)?;
3288    let fingerprint = wrapper_executable_fingerprint(&snapshot)?;
3289    if let (Some(cache), Some(stamp)) = (session, source_stamp) {
3290        cache.wrapper_snapshot = Some(CachedWrapperSnapshot {
3291            source_path: wrapper.to_path_buf(),
3292            source_stamp: stamp,
3293            snapshot_root: snapshot_root.to_path_buf(),
3294            snapshot_path: snapshot.clone(),
3295            fingerprint: fingerprint.clone(),
3296        });
3297    }
3298    Ok((snapshot, lock, fingerprint))
3299}
3300
3301#[cfg(windows)]
3302fn prepare_wrapper_with_session(
3303    source_exclusion: &Path,
3304    snapshot_root: &Path,
3305    wrapper: &Path,
3306    _session: Option<&mut DevSessionCache>,
3307) -> Result<(PathBuf, Option<fs::File>, String)> {
3308    let (resolved, lock) = prepare_wrapper_executable(source_exclusion, snapshot_root, wrapper)?;
3309    let fingerprint = wrapper_executable_fingerprint(&resolved)?;
3310    Ok((resolved, lock, fingerprint))
3311}
3312
3313#[cfg(not(windows))]
3314fn prepare_wrapper_executable(
3315    source_exclusion: &Path,
3316    snapshot_root: &Path,
3317    wrapper: &Path,
3318) -> Result<(PathBuf, Option<fs::File>)> {
3319    let snapshot = snapshot_wrapper_executable(source_exclusion, snapshot_root, wrapper)
3320        .context("publish the cargo-proa wrapper into its content-addressed snapshot")?;
3321    Ok((snapshot, None))
3322}
3323
3324#[cfg(windows)]
3325fn prepare_wrapper_executable(
3326    _source_exclusion: &Path,
3327    _snapshot_root: &Path,
3328    wrapper: &Path,
3329) -> Result<(PathBuf, Option<fs::File>)> {
3330    use std::os::windows::fs::OpenOptionsExt as _;
3331    use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
3332
3333    let wrapper = fs::canonicalize(wrapper)
3334        .with_context(|| format!("resolve cargo-proa wrapper `{}`", wrapper.display()))?;
3335    let lock = fs::OpenOptions::new()
3336        .read(true)
3337        .share_mode(FILE_SHARE_READ)
3338        .open(&wrapper)
3339        .with_context(|| {
3340            format!(
3341                "lock cargo-proa wrapper `{}` against replacement during linked compilation",
3342                wrapper.display()
3343            )
3344        })?;
3345    Ok((wrapper, Some(lock)))
3346}
3347
3348fn wrapper_executable_fingerprint(path: &Path) -> Result<String> {
3349    use std::fmt::Write as _;
3350    use std::io::Read as _;
3351
3352    let mut executable = fs::File::open(path)
3353        .with_context(|| format!("open cargo-proa wrapper executable `{}`", path.display()))?;
3354    let metadata = executable
3355        .metadata()
3356        .with_context(|| format!("inspect cargo-proa wrapper executable `{}`", path.display()))?;
3357    if !metadata.is_file() {
3358        bail!(
3359            "cargo-proa wrapper executable is not a regular file: `{}`",
3360            path.display()
3361        );
3362    }
3363
3364    let mut hasher = Sha256::new();
3365    hasher.update(RSJS_WRAPPER_EXECUTABLE_FINGERPRINT_DOMAIN);
3366    let mut buffer = [0_u8; 64 * 1024];
3367    loop {
3368        let read = executable
3369            .read(&mut buffer)
3370            .with_context(|| format!("hash cargo-proa wrapper executable `{}`", path.display()))?;
3371        if read == 0 {
3372            break;
3373        }
3374        hasher.update(&buffer[..read]);
3375    }
3376
3377    let digest: [u8; 32] = hasher.finalize().into();
3378    let mut encoded = String::with_capacity("sha256:".len() + digest.len() * 2);
3379    encoded.push_str("sha256:");
3380    for byte in digest {
3381        let _ = write!(encoded, "{byte:02x}");
3382    }
3383    Ok(encoded)
3384}
3385
3386#[cfg(test)]
3387fn parse_cargo_build_command(command: &[String]) -> Result<ParsedCargoInvocation> {
3388    parse_cargo_command(command, LinkedCargoAction::Build)
3389}
3390
3391fn parse_cargo_command(
3392    command: &[String],
3393    action: LinkedCargoAction,
3394) -> Result<ParsedCargoInvocation> {
3395    let Some((program, raw_args)) = command.split_first() else {
3396        bail!(
3397            "linked Cargo {} command cannot be empty",
3398            action.subcommand()
3399        );
3400    };
3401    if !is_cargo_program(program) {
3402        bail!(
3403            "`cargo proa {command}` requires a Cargo {cargo_action} command for the linked RSJS pipeline; found `{}`. Custom non-Cargo commands are not supported yet",
3404            shellish(command),
3405            command = action.command_name(),
3406            cargo_action = action.subcommand(),
3407        );
3408    }
3409    if raw_args.first().map(String::as_str) != Some(action.subcommand()) {
3410        bail!(
3411            "`cargo proa {command}` currently supports only `cargo {cargo_action}`; found `{}`. Other Cargo subcommands do not yet have linked-root semantics for this workflow",
3412            shellish(command),
3413            command = action.command_name(),
3414            cargo_action = action.subcommand(),
3415        );
3416    }
3417
3418    let mut package = None;
3419    let mut bin = None;
3420    let mut example = None;
3421    let mut test = None;
3422    let mut explicit_profile = None;
3423    let mut release = false;
3424    let mut target = None;
3425    let mut features = BTreeSet::new();
3426    let mut locked = false;
3427    let mut offline = false;
3428    let mut metadata_flags = Vec::new();
3429    let mut selection_args = Vec::new();
3430    let mut runtime_args = Vec::new();
3431    let mut cargo_arg_count = raw_args.len();
3432    let mut index = 1;
3433    while index < raw_args.len() {
3434        let argument = &raw_args[index];
3435        match argument.as_str() {
3436            "--message-format" | "--target-dir" => {
3437                let value = raw_args.get(index + 1).cloned();
3438                bail!(
3439                    "Cargo argument `{argument}{}` is reserved by the linked RSJS pipeline; remove it so cargo-proa can isolate descriptor and final artifacts",
3440                    value
3441                        .as_deref()
3442                        .map(|value| format!(" {value}"))
3443                        .unwrap_or_default()
3444                );
3445            }
3446            value
3447                if value.starts_with("--message-format=") || value.starts_with("--target-dir=") =>
3448            {
3449                bail!(
3450                    "Cargo argument `{value}` is reserved by the linked RSJS pipeline; remove it so cargo-proa can own Cargo messages and artifact namespaces"
3451                );
3452            }
3453            "--workspace" | "--all" | "--exclude" | "--bins" | "--examples" | "--tests"
3454            | "--benches" | "--all-targets" | "--lib" | "--bench" => {
3455                bail!(
3456                    "Cargo target-selection argument `{argument}` can produce multiple or unsupported roots. The linked RSJS pipeline requires one exact package plus binary, example, or integration-test target"
3457                );
3458            }
3459            "--manifest-path" | "--config" | "--artifact-dir" => {
3460                bail!(
3461                    "Cargo argument `{argument}` is not supported by the first linked RSJS pipeline contract; select the project with `--root` and let cargo-proa own build configuration/output paths"
3462                );
3463            }
3464            value
3465                if value.starts_with("--manifest-path=")
3466                    || value.starts_with("--config=")
3467                    || value.starts_with("--artifact-dir=") =>
3468            {
3469                bail!(
3470                    "Cargo argument `{value}` is not supported by the first linked RSJS pipeline contract; select the project with `--root` and let cargo-proa own build configuration/output paths"
3471                );
3472            }
3473            "--" => {
3474                if !action.permits_runtime_arguments() {
3475                    bail!(
3476                        "arguments after `--` are supported only by `cargo proa dev`, `cargo proa run`, and `cargo proa test`; descriptor and final compiler inputs for this workflow must be derived by cargo-proa"
3477                    );
3478                }
3479                cargo_arg_count = index;
3480                runtime_args.extend(raw_args[index + 1..].iter().map(OsString::from));
3481                break;
3482            }
3483            "-p" | "--package" => {
3484                let value = required_cargo_value(raw_args, &mut index, argument)?;
3485                set_once(&mut package, value, "Cargo package")?;
3486            }
3487            value if value.starts_with("--package=") => {
3488                set_once(
3489                    &mut package,
3490                    nonempty_option_value(value, "--package=")?,
3491                    "Cargo package",
3492                )?;
3493            }
3494            value if value.starts_with("-p") && value.len() > 2 => {
3495                set_once(&mut package, value[2..].to_string(), "Cargo package")?;
3496            }
3497            "--bin" => {
3498                let value = required_cargo_value(raw_args, &mut index, argument)?;
3499                set_once(&mut bin, value, "Cargo binary")?;
3500            }
3501            value if value.starts_with("--bin=") => {
3502                set_once(
3503                    &mut bin,
3504                    nonempty_option_value(value, "--bin=")?,
3505                    "Cargo binary",
3506                )?;
3507            }
3508            "--example" if action != LinkedCargoAction::Test => {
3509                let value = required_cargo_value(raw_args, &mut index, argument)?;
3510                set_once(&mut example, value, "Cargo example")?;
3511            }
3512            value if action != LinkedCargoAction::Test && value.starts_with("--example=") => {
3513                set_once(
3514                    &mut example,
3515                    nonempty_option_value(value, "--example=")?,
3516                    "Cargo example",
3517                )?;
3518            }
3519            "--example" => {
3520                bail!(
3521                    "Cargo target-selection argument `--example` is not supported by `cargo proa test`; use `--bin <name>` or `--test <name>`"
3522                );
3523            }
3524            value if value.starts_with("--example=") => {
3525                bail!(
3526                    "Cargo target-selection argument `{value}` is not supported by `cargo proa test`; use `--bin <name>` or `--test <name>`"
3527                );
3528            }
3529            "--test" if action == LinkedCargoAction::Test => {
3530                let value = required_cargo_value(raw_args, &mut index, argument)?;
3531                set_once(&mut test, value, "Cargo integration test")?;
3532            }
3533            value if action == LinkedCargoAction::Test && value.starts_with("--test=") => {
3534                set_once(
3535                    &mut test,
3536                    nonempty_option_value(value, "--test=")?,
3537                    "Cargo integration test",
3538                )?;
3539            }
3540            "--test" => {
3541                bail!(
3542                    "Cargo target-selection argument `--test` is valid only for `cargo proa test`"
3543                );
3544            }
3545            value if value.starts_with("--test=") => {
3546                bail!(
3547                    "Cargo target-selection argument `{value}` is valid only for `cargo proa test`"
3548                );
3549            }
3550            "--profile" => {
3551                let value = required_cargo_value(raw_args, &mut index, argument)?;
3552                set_once(&mut explicit_profile, value, "Cargo profile")?;
3553            }
3554            value if value.starts_with("--profile=") => {
3555                set_once(
3556                    &mut explicit_profile,
3557                    nonempty_option_value(value, "--profile=")?,
3558                    "Cargo profile",
3559                )?;
3560            }
3561            "--release" => {
3562                if release {
3563                    bail!("Cargo profile selector `--release` was supplied more than once");
3564                }
3565                release = true;
3566            }
3567            "--target" => {
3568                let value = required_cargo_value(raw_args, &mut index, argument)?;
3569                set_once(&mut target, value, "Cargo target")?;
3570            }
3571            value if value.starts_with("--target=") => {
3572                set_once(
3573                    &mut target,
3574                    nonempty_option_value(value, "--target=")?,
3575                    "Cargo target",
3576                )?;
3577            }
3578            "--features" | "-F" => {
3579                let value = required_cargo_value(raw_args, &mut index, argument)?;
3580                extend_features(&mut features, &value)?;
3581            }
3582            value if value.starts_with("--features=") => {
3583                extend_features(&mut features, &nonempty_option_value(value, "--features=")?)?;
3584            }
3585            value if value.starts_with("-F") && value.len() > 2 => {
3586                extend_features(&mut features, &value[2..])?;
3587            }
3588            "--all-features" | "--no-default-features" => {
3589                metadata_flags.push(argument.clone().into());
3590                selection_args.push(argument.clone());
3591            }
3592            "--locked" => {
3593                locked = true;
3594                metadata_flags.push(argument.clone().into());
3595            }
3596            "--offline" => {
3597                offline = true;
3598                metadata_flags.push(argument.clone().into());
3599            }
3600            "--frozen" => {
3601                locked = true;
3602                offline = true;
3603                metadata_flags.push(argument.clone().into());
3604            }
3605            "-q"
3606            | "--quiet"
3607            | "-v"
3608            | "-vv"
3609            | "--verbose"
3610            | "--keep-going"
3611            | "--future-incompat-report"
3612            | "--timings"
3613            | "--ignore-rust-version" => {
3614                selection_args.push(argument.clone());
3615            }
3616            "--jobs" | "-j" | "--color" => {
3617                let value = required_cargo_value(raw_args, &mut index, argument)?;
3618                selection_args.push(argument.clone());
3619                selection_args.push(value);
3620            }
3621            value
3622                if value.starts_with("--jobs=")
3623                    || value.starts_with("--color=")
3624                    || value.starts_with("--timings=")
3625                    || (value.starts_with("-j") && value.len() > 2) =>
3626            {
3627                selection_args.push(value.to_string());
3628            }
3629            other => {
3630                bail!(
3631                    "Cargo {action} argument `{other}` is not yet classified by the linked RSJS pipeline. Remove it or use one of the supported package/bin/example/profile/feature/target/offline/locked/output flags",
3632                    action = action.subcommand(),
3633                );
3634            }
3635        }
3636        index += 1;
3637    }
3638
3639    if release && explicit_profile.is_some() {
3640        bail!("Cargo profile is ambiguous: use either `--release` or `--profile`, not both");
3641    }
3642    if bin.is_some() && example.is_some() {
3643        bail!(
3644            "linked Cargo target selection is ambiguous: use either `--bin <name>` or `--example <name>`, not both"
3645        );
3646    }
3647    if action == LinkedCargoAction::Test && bin.is_some() == test.is_some() {
3648        bail!(
3649            "linked Cargo test requires exactly one target selector: use either `--bin <name>` or `--test <name>`"
3650        );
3651    }
3652    let profile = explicit_profile.unwrap_or_else(|| {
3653        if release {
3654            "release".to_string()
3655        } else if action == LinkedCargoAction::Test {
3656            "test".to_string()
3657        } else {
3658            "dev".to_string()
3659        }
3660    });
3661
3662    Ok(ParsedCargoInvocation {
3663        cargo: OsString::from(program),
3664        cargo_args: raw_args[..cargo_arg_count]
3665            .iter()
3666            .map(OsString::from)
3667            .collect(),
3668        runtime_args,
3669        package,
3670        bin,
3671        example,
3672        test,
3673        profile,
3674        target,
3675        features,
3676        locked,
3677        offline,
3678        metadata_flags,
3679        selection_args,
3680    })
3681}
3682
3683fn required_cargo_value(arguments: &[String], index: &mut usize, option: &str) -> Result<String> {
3684    *index += 1;
3685    let Some(value) = arguments.get(*index) else {
3686        bail!("Cargo option `{option}` requires a value");
3687    };
3688    if value.is_empty() || value.starts_with('-') {
3689        bail!("Cargo option `{option}` requires a nonempty value");
3690    }
3691    Ok(value.clone())
3692}
3693
3694fn nonempty_option_value(argument: &str, prefix: &str) -> Result<String> {
3695    let value = &argument[prefix.len()..];
3696    if value.is_empty() {
3697        bail!(
3698            "Cargo option `{}` requires a nonempty value",
3699            &prefix[..prefix.len() - 1]
3700        );
3701    }
3702    Ok(value.to_string())
3703}
3704
3705fn set_once(slot: &mut Option<String>, value: String, label: &str) -> Result<()> {
3706    if let Some(previous) = slot {
3707        bail!(
3708            "{label} selection is ambiguous: both `{previous}` and `{value}` were supplied; select exactly one"
3709        );
3710    }
3711    *slot = Some(value);
3712    Ok(())
3713}
3714
3715fn extend_features(features: &mut BTreeSet<String>, value: &str) -> Result<()> {
3716    let parsed = value
3717        .split([',', ' '])
3718        .filter(|feature| !feature.is_empty())
3719        .collect::<Vec<_>>();
3720    if parsed.is_empty() {
3721        bail!("Cargo `--features` requires at least one feature name");
3722    }
3723    features.extend(parsed.into_iter().map(str::to_string));
3724    Ok(())
3725}
3726
3727fn is_cargo_program(program: &str) -> bool {
3728    Path::new(program)
3729        .file_name()
3730        .and_then(OsStr::to_str)
3731        .is_some_and(|name| matches!(name, "cargo" | "cargo.exe"))
3732}
3733
3734fn load_cargo_metadata(root: &Path, parsed: &ParsedCargoInvocation) -> Result<CargoMetadata> {
3735    let manifest = root.join("Cargo.toml");
3736    let mut command = Command::new(&parsed.cargo);
3737    command
3738        .current_dir(root)
3739        .args([
3740            OsStr::new("metadata"),
3741            OsStr::new("--format-version=1"),
3742            OsStr::new("--no-deps"),
3743            OsStr::new("--manifest-path"),
3744        ])
3745        .arg(&manifest)
3746        .args(&parsed.metadata_flags);
3747    let output = command.output().with_context(|| {
3748        format!(
3749            "run Cargo metadata with `{}` for exact RSJS root selection",
3750            Path::new(&parsed.cargo).display()
3751        )
3752    })?;
3753    if !output.status.success() {
3754        bail!(
3755            "Cargo metadata failed while selecting the exact RSJS root ({status}):\n{stderr}",
3756            status = output.status,
3757            stderr = String::from_utf8_lossy(&output.stderr).trim()
3758        );
3759    }
3760    serde_json::from_slice(&output.stdout).context("parse Cargo metadata for RSJS root selection")
3761}
3762
3763fn select_exact_cargo_root(
3764    metadata: &CargoMetadata,
3765    parsed: &ParsedCargoInvocation,
3766    action: LinkedCargoAction,
3767) -> Result<ExactCargoRoot> {
3768    let (requested_target_kind, requested_target_name) = match action {
3769        LinkedCargoAction::Test => match (&parsed.bin, &parsed.test) {
3770            (Some(name), None) => ("bin", name.as_str()),
3771            (None, Some(name)) => ("test", name.as_str()),
3772            _ => {
3773                bail!(
3774                    "linked Cargo test requires exactly one target selector: use either `--bin <name>` or `--test <name>`"
3775                )
3776            }
3777        },
3778        LinkedCargoAction::Build
3779        | LinkedCargoAction::Check
3780        | LinkedCargoAction::Dev
3781        | LinkedCargoAction::Run => match (&parsed.bin, &parsed.example) {
3782            (Some(name), None) => ("bin", name.as_str()),
3783            (None, Some(name)) => ("example", name.as_str()),
3784            (None, None) => ("bin", ""),
3785            (Some(_), Some(_)) => {
3786                bail!(
3787                    "linked Cargo target selection is ambiguous: use either `--bin <name>` or `--example <name>`, not both"
3788                )
3789            }
3790        },
3791    };
3792    let workspace_members = metadata
3793        .workspace_members
3794        .iter()
3795        .map(String::as_str)
3796        .collect::<BTreeSet<_>>();
3797    let default_members = metadata
3798        .workspace_default_members
3799        .iter()
3800        .map(String::as_str)
3801        .collect::<BTreeSet<_>>();
3802    if parsed.package.is_none() && default_members.len() != 1 {
3803        bail!(
3804            "Cargo defaults select {} workspace packages; the linked RSJS pipeline accepts one exact package and target. Pass `-p <package>` plus `--bin <name>`, `--example <name>`, or `--test <name>`",
3805            default_members.len(),
3806        );
3807    }
3808    let mut packages = metadata
3809        .packages
3810        .iter()
3811        .filter(|package| workspace_members.contains(package.id.as_str()))
3812        .filter(|package| match &parsed.package {
3813            Some(selector) => cargo_package_matches(package, selector),
3814            None => default_members.contains(package.id.as_str()),
3815        })
3816        .collect::<Vec<_>>();
3817    packages.sort_by(|left, right| left.id.cmp(&right.id));
3818
3819    if packages.is_empty() {
3820        match &parsed.package {
3821            Some(package) => bail!(
3822                "Cargo metadata contains no exact workspace package matching `-p {package}`; package specs must resolve to one workspace package"
3823            ),
3824            None => bail!(
3825                "Cargo metadata has no default workspace member to use as an RSJS root; pass `-p <package>` plus an exact target"
3826            ),
3827        }
3828    }
3829    if parsed.package.is_some() && packages.len() != 1 {
3830        bail!(
3831            "Cargo package selector `{}` matches {} workspace packages; pass one unambiguous package ID and exact target",
3832            parsed.package.as_deref().unwrap_or_default(),
3833            packages.len()
3834        );
3835    }
3836
3837    let mut candidates = Vec::new();
3838    for package in packages {
3839        if !package.manifest_path.is_absolute() {
3840            bail!(
3841                "Cargo package `{}` has a relative manifest path `{}`; exact source-closure diagnostics require an absolute package root",
3842                package.name,
3843                package.manifest_path.display()
3844            );
3845        }
3846        let package_source_root = package.manifest_path.parent().ok_or_else(|| {
3847            anyhow::anyhow!(
3848                "Cargo package `{}` manifest path `{}` has no parent directory",
3849                package.name,
3850                package.manifest_path.display()
3851            )
3852        })?;
3853        for target in &package.targets {
3854            let kinds = target.kind.iter().cloned().collect::<BTreeSet<_>>();
3855            if !kinds.contains(requested_target_kind) {
3856                continue;
3857            }
3858            if !requested_target_name.is_empty() && requested_target_name != target.name {
3859                continue;
3860            }
3861            candidates.push(ExactCargoRoot {
3862                package_id: package.id.clone(),
3863                package_name: package.name.clone(),
3864                package_source_root: package_source_root.to_path_buf(),
3865                target_name: target.name.clone(),
3866                target_kinds: kinds,
3867                requested_target_kind: requested_target_kind.to_string(),
3868            });
3869        }
3870    }
3871    candidates.sort_by(|left, right| {
3872        (&left.package_id, &left.target_name).cmp(&(&right.package_id, &right.target_name))
3873    });
3874
3875    match candidates.len() {
3876        0 => {
3877            if !requested_target_name.is_empty() {
3878                bail!(
3879                    "Cargo metadata contains no `{requested_target_kind}` target named `{requested_target_name}` in the selected package set"
3880                );
3881            }
3882            bail!(
3883                "the selected Cargo package set has no `{requested_target_kind}` target; the linked RSJS pipeline requires one executable root"
3884            );
3885        }
3886        1 => Ok(candidates.remove(0)),
3887        count => {
3888            let rendered = candidates
3889                .iter()
3890                .map(|candidate| format!("{}::{}", candidate.package_name, candidate.target_name))
3891                .collect::<Vec<_>>()
3892                .join(", ");
3893            bail!(
3894                "Cargo selection resolves to {count} `{requested_target_kind}` roots ({rendered}); cargo-proa will not guess. Pass an exact package and target"
3895            );
3896        }
3897    }
3898}
3899
3900fn cargo_package_matches(package: &CargoMetadataPackage, selector: &str) -> bool {
3901    selector == package.id
3902        || selector == package.name
3903        || selector == format!("{}@{}", package.name, package.version)
3904        || selector == format!("{}:{}", package.name, package.version)
3905}
3906
3907fn parse_producer_version(version: &str) -> Result<ProducerVersion> {
3908    let core = version.split_once('-').map_or(version, |(core, _)| core);
3909    let mut parts = core.split('.');
3910    let major = parse_version_part(parts.next(), "major", version)?;
3911    let minor = parse_version_part(parts.next(), "minor", version)?;
3912    let patch = parse_version_part(parts.next(), "patch", version)?;
3913    if parts.next().is_some() {
3914        bail!("unsupported cargo-proa producer version `{version}`");
3915    }
3916    Ok(ProducerVersion::new(major, minor, patch))
3917}
3918
3919fn cli_tool_producer_version() -> Result<ProducerVersion> {
3920    parse_producer_version(env!("CARGO_PKG_VERSION"))
3921}
3922
3923fn parse_version_part(part: Option<&str>, name: &str, version: &str) -> Result<u16> {
3924    part.ok_or_else(|| anyhow::anyhow!("cargo-proa version `{version}` has no {name} component"))?
3925        .parse::<u16>()
3926        .with_context(|| format!("parse cargo-proa {name} version from `{version}`"))
3927}
3928
3929fn tool_version(
3930    program: &OsStr,
3931    args: &[&str],
3932    label: &str,
3933    working_directory: &Path,
3934) -> Result<String> {
3935    let output = Command::new(program)
3936        .args(args)
3937        .current_dir(working_directory)
3938        .output()
3939        .with_context(|| {
3940            format!(
3941                "query {label} version from `{}`",
3942                Path::new(program).display()
3943            )
3944        })?;
3945    if !output.status.success() {
3946        bail!(
3947            "{label} version query failed with {}: {}",
3948            output.status,
3949            String::from_utf8_lossy(&output.stderr).trim()
3950        );
3951    }
3952    let version = String::from_utf8(output.stdout)
3953        .with_context(|| format!("{label} version output is not UTF-8"))?
3954        .trim()
3955        .to_string();
3956    if version.is_empty() {
3957        bail!("{label} version query returned empty output");
3958    }
3959    Ok(version)
3960}
3961
3962fn selected_rustc_version(working_directory: &Path) -> Result<String> {
3963    let rustc = std::env::var_os("RUSTC").unwrap_or_else(|| OsString::from("rustc"));
3964    tool_version(&rustc, &["-vV"], "rustc", working_directory)
3965}
3966
3967fn declared_build_environment() -> BTreeMap<String, DeclaredEnvironmentInput> {
3968    [
3969        "RUSTC",
3970        "RUSTFLAGS",
3971        "CARGO_ENCODED_RUSTFLAGS",
3972        "CARGO_BUILD_TARGET",
3973        "RUSTUP_TOOLCHAIN",
3974    ]
3975    .into_iter()
3976    .map(|name| {
3977        let value = std::env::var_os(name).map(|value| os_value_bytes(&value));
3978        (
3979            name.to_string(),
3980            DeclaredEnvironmentInput {
3981                name: name.to_string(),
3982                value_hash: SemanticHash::derive(&value),
3983            },
3984        )
3985    })
3986    .collect()
3987}
3988
3989#[cfg(unix)]
3990fn os_value_bytes(value: &OsStr) -> Vec<u8> {
3991    use std::os::unix::ffi::OsStrExt;
3992    value.as_bytes().to_vec()
3993}
3994
3995#[cfg(windows)]
3996fn os_value_bytes(value: &OsStr) -> Vec<u8> {
3997    use std::os::windows::ffi::OsStrExt;
3998    value.encode_wide().flat_map(u16::to_le_bytes).collect()
3999}
4000
4001#[cfg(not(any(unix, windows)))]
4002fn os_value_bytes(value: &OsStr) -> Vec<u8> {
4003    value.to_string_lossy().into_owned().into_bytes()
4004}
4005
4006fn absolute_project_root(root: PathBuf) -> Result<PathBuf> {
4007    let root = if root.is_absolute() {
4008        root
4009    } else {
4010        std::env::current_dir()?.join(root)
4011    };
4012    fs::canonicalize(&root)
4013        .with_context(|| format!("resolve absolute Proa project root `{}`", root.display()))
4014}
4015
4016fn fresh_build_nonce() -> String {
4017    let elapsed = SystemTime::now()
4018        .duration_since(UNIX_EPOCH)
4019        .unwrap_or_default()
4020        .as_nanos();
4021    let sequence = RSJS_BUILD_NONCE.fetch_add(1, Ordering::Relaxed);
4022    format!("{}-{elapsed}-{sequence}", std::process::id())
4023}
4024
4025fn print_linked_cargo_output(
4026    action: LinkedCargoAction,
4027    request: &LinkedCargoRequest,
4028    output: &LinkedCargoOutput,
4029) {
4030    println!(
4031        "linked RSJS plan {} for package `{}` binary `{}`",
4032        output.semantic.plan_id, request.root.package_id, request.root.target_name
4033    );
4034    match action {
4035        LinkedCargoAction::Build => println!(
4036            "final Cargo artifacts: {}",
4037            output.final_cargo.target_directory.display()
4038        ),
4039        LinkedCargoAction::Check => println!(
4040            "final Cargo check artifacts: {}",
4041            output.final_cargo.target_directory.display()
4042        ),
4043        LinkedCargoAction::Dev => println!(
4044            "final Cargo dev artifacts: {}",
4045            output.final_cargo.target_directory.display()
4046        ),
4047        LinkedCargoAction::Run => println!(
4048            "final Cargo run artifacts: {}",
4049            output.final_cargo.target_directory.display()
4050        ),
4051        LinkedCargoAction::Test => println!(
4052            "final Cargo test artifacts: {}",
4053            output.final_cargo.target_directory.display()
4054        ),
4055    }
4056}
4057
4058fn run_project_check(root: &Path, config: &ProjectConfig) -> Result<()> {
4059    let report = scaffold::site_check_with_config(root.to_path_buf(), config)?;
4060    scaffold::print_site_check(&report, false)?;
4061    if !report.errors.is_empty() {
4062        bail!("Proa site check failed");
4063    }
4064
4065    let src = root.join("src");
4066    if src.exists() {
4067        let paths = vec![src];
4068        let format_summary = crate::fmt::format_paths_with_options(&paths, true, true)?;
4069        for diagnostic in &format_summary.diagnostics {
4070            eprint!("{diagnostic}");
4071        }
4072        if !format_summary.changed.is_empty() {
4073            for path in &format_summary.changed {
4074                eprintln!("{}: Proa macro formatting differs", path.display());
4075            }
4076            bail!("Proa formatting check failed");
4077        }
4078        if format_summary
4079            .diagnostics
4080            .iter()
4081            .any(|diag| diag.severity == Severity::Error)
4082        {
4083            bail!("Proa formatting failed");
4084        }
4085
4086        let diagnostics = crate::lint::lint_paths(&paths, crate::lint::LintOptions::default())?;
4087        for diagnostic in &diagnostics {
4088            if diagnostic.severity.rank() >= Severity::Warning.rank() {
4089                eprint!("{diagnostic}");
4090            }
4091        }
4092        if diagnostics
4093            .iter()
4094            .any(|diag| matches!(diag.severity, Severity::Error | Severity::Warning))
4095        {
4096            bail!("Proa check failed");
4097        }
4098    }
4099
4100    Ok(())
4101}
4102
4103pub fn build_assets_for_project(root: &Path) -> Result<()> {
4104    let config = load_project_config(root)?;
4105    build_assets(root, &config)
4106}
4107
4108fn build_assets(root: &Path, config: &ProjectConfig) -> Result<()> {
4109    build_assets_for_change(root, config, None, &[])
4110}
4111
4112fn build_assets_for_change(
4113    root: &Path,
4114    config: &ProjectConfig,
4115    public: Option<&Path>,
4116    changed: &[PathBuf],
4117) -> Result<()> {
4118    if let Some(output) = crate::config::css_script_output(config) {
4119        prepare_asset_output(root, &output)?;
4120        let status = script::command(root, "css", &config.scripts.css, &[])?
4121            .status()
4122            .context("run scripts.css")?;
4123        exit_status_to_result(status, "scripts.css")?;
4124    }
4125    for asset in config.build.assets() {
4126        if let Some(public) = public {
4127            if should_skip_managed_tailwind_asset(root, public, asset, changed) {
4128                continue;
4129            }
4130        }
4131        build_asset(root, asset)?;
4132    }
4133    Ok(())
4134}
4135
4136fn should_skip_managed_tailwind_asset(
4137    root: &Path,
4138    public: &Path,
4139    asset: &AssetConfig,
4140    changed: &[PathBuf],
4141) -> bool {
4142    // Only skip the built-in managed Tailwind invocation; custom asset commands
4143    // may read undeclared files anywhere in `public/`.
4144    if asset.kind != "tailwind" || !asset.command.is_empty() || changed.is_empty() {
4145        return false;
4146    }
4147    if !root.join(&asset.output).is_file() {
4148        return false;
4149    }
4150    changed
4151        .iter()
4152        .all(|path| path.starts_with(public) && is_opaque_to_tailwind(path))
4153}
4154
4155/// Whether Tailwind can be trusted never to read this file.
4156///
4157/// Tailwind scans every file it does not recognize as binary, whatever the
4158/// extension: JSON, SVG, plain text, and templates in any language can all
4159/// contribute class names, and stylesheets can be imported. Skipping it is
4160/// therefore safe only for formats on its own binary list. Anything else,
4161/// including a file with no extension, runs Tailwind as before.
4162fn is_opaque_to_tailwind(path: &Path) -> bool {
4163    path.extension().and_then(OsStr::to_str).is_some_and(|ext| {
4164        matches!(
4165            ext.to_ascii_lowercase().as_str(),
4166            "png"
4167                | "jpg"
4168                | "jpeg"
4169                | "gif"
4170                | "webp"
4171                | "avif"
4172                | "ico"
4173                | "bmp"
4174                | "tif"
4175                | "tiff"
4176                | "heic"
4177                | "woff"
4178                | "woff2"
4179                | "ttf"
4180                | "otf"
4181                | "eot"
4182                | "mp3"
4183                | "wav"
4184                | "ogg"
4185                | "flac"
4186                | "aac"
4187                | "m4a"
4188                | "mp4"
4189                | "m4v"
4190                | "mov"
4191                | "webm"
4192                | "avi"
4193                | "mkv"
4194                | "pdf"
4195                | "zip"
4196                | "gz"
4197                | "wasm"
4198        )
4199    })
4200}
4201
4202fn build_asset(root: &Path, asset: &AssetConfig) -> Result<()> {
4203    let command = asset_command(root, asset)?;
4204    if command.is_empty() {
4205        return Ok(());
4206    }
4207
4208    if asset.kind == "tailwind"
4209        && asset.command.is_empty()
4210        && command
4211            .first()
4212            .is_some_and(|program| program == "tailwindcss")
4213        && !program_available("tailwindcss")
4214    {
4215        if root.join(&asset.output).is_file() {
4216            eprintln!(
4217                "warning: managed Tailwind binary is not cached; preserving prebuilt {}",
4218                asset.output.display()
4219            );
4220            return Ok(());
4221        }
4222        bail!(
4223            "Tailwind output `{}` is missing and the managed compiler is unavailable",
4224            asset.output.display()
4225        );
4226    }
4227
4228    prepare_asset_output(root, &asset.output)?;
4229    run_command_status(root, &command, "asset command")
4230}
4231
4232fn prepare_asset_output(root: &Path, output: &Path) -> Result<()> {
4233    if let Some(output_parent) = output.parent() {
4234        let output_parent = root.join(output_parent);
4235        fs::create_dir_all(&output_parent)
4236            .with_context(|| format!("create {}", output_parent.display()))?;
4237    }
4238
4239    dev_ui::detail!("building asset: {}", output.display());
4240    Ok(())
4241}
4242
4243fn asset_command(root: &Path, asset: &AssetConfig) -> Result<Vec<String>> {
4244    if !asset.command.is_empty() {
4245        return Ok(asset.command.clone());
4246    }
4247
4248    match asset.kind.as_str() {
4249        "tailwind" => {
4250            if !root.join(&asset.input).exists() {
4251                eprintln!(
4252                    "warning: tailwind input `{}` not found; skipping asset build for `{}`",
4253                    asset.input.display(),
4254                    asset.output.display()
4255                );
4256                return Ok(Vec::new());
4257            }
4258
4259            let mut command = vec![
4260                "tailwindcss".into(),
4261                "-i".into(),
4262                asset.input.display().to_string(),
4263                "-o".into(),
4264                asset.output.display().to_string(),
4265            ];
4266            if let Some(config) = &asset.config {
4267                if root.join(config).exists() {
4268                    command.push("-c".into());
4269                    command.push(config.display().to_string());
4270                }
4271            }
4272            Ok(command)
4273        }
4274        "command" if asset.command.is_empty() => Ok(Vec::new()),
4275        other => bail!("unknown asset kind `{other}` in proa.config.rs"),
4276    }
4277}
4278
4279fn program_available(program: &str) -> bool {
4280    let Some(search_path) = env::var_os("PATH") else {
4281        return false;
4282    };
4283    env::split_paths(&search_path).any(|directory| {
4284        let candidate = directory.join(program);
4285        candidate.is_file() || cfg!(windows) && directory.join(format!("{program}.exe")).is_file()
4286    })
4287}
4288
4289fn run_linked_dev_foreground(
4290    root: &Path,
4291    launch: &LinkedDevLaunch,
4292    host: &str,
4293    port: u16,
4294    open: bool,
4295) -> Result<()> {
4296    let mut child = spawn_linked_dev(root, launch, host, port, None)?;
4297    announce_dev_start(open, host, port, &mut child);
4298    let status = child.process.wait().context("wait for linked dev server");
4299    clear_active_child_group();
4300    exit_status_to_result(status?, "linked dev server")
4301}
4302
4303struct DevChild {
4304    process: Child,
4305    readiness: Option<readiness::ReadyChannel>,
4306}
4307
4308impl DevChild {
4309    fn ready_url(&mut self, host: &str, port: u16) -> Option<String> {
4310        reload::wait_until_serving(
4311            host,
4312            port,
4313            DEV_READY_TIMEOUT,
4314            &mut || matches!(self.process.try_wait(), Ok(None)),
4315            self.readiness.as_mut(),
4316        )
4317    }
4318
4319    fn restart(
4320        &mut self,
4321        root: &Path,
4322        launch: &LinkedDevLaunch,
4323        address: (&str, u16),
4324        hot: Option<&mut crate::hot_static::HotState>,
4325        reload: Option<&ReloadServer>,
4326    ) -> Result<()> {
4327        stop_child(&mut self.process)?;
4328        clear_active_child_group();
4329        if let Some(hot) = hot {
4330            hot.activate()?;
4331        }
4332        *self = spawn_linked_dev(root, launch, address.0, address.1, reload)?;
4333        announce_reload(reload, address.0, address.1, self);
4334        Ok(())
4335    }
4336}
4337
4338fn spawn_linked_dev(
4339    root: &Path,
4340    launch: &LinkedDevLaunch,
4341    host: &str,
4342    port: u16,
4343    reload: Option<&ReloadServer>,
4344) -> Result<DevChild> {
4345    print_linked_dev_launch(launch);
4346    public_assets::cleanup(launch.public_assets.as_deref());
4347    let session = reload.map(|server| (server.port(), server.token().to_owned()));
4348    let mut cmd = linked_dev_command(root, launch, host, port, session.as_ref());
4349    cmd.env_remove("PROA_DEV_READY");
4350    let readiness = readiness::ReadyChannel::bind(&mut cmd, host, port)
4351        .map_err(|error| {
4352            eprintln!(
4353                "Dev URL reporting unavailable ({error}). Checking the configured TCP listener."
4354            );
4355        })
4356        .ok();
4357    // Put the dev command in its own process group so restarts can stop the
4358    // whole server tree and release its port before activating the next plan.
4359    #[cfg(unix)]
4360    {
4361        use std::os::unix::process::CommandExt;
4362        cmd.process_group(0);
4363    }
4364    let process = cmd.spawn().with_context(|| {
4365        format!(
4366            "spawn linked dev executable `{}`",
4367            launch.executable.display()
4368        )
4369    })?;
4370    set_active_child_group(&process);
4371    Ok(DevChild { process, readiness })
4372}
4373
4374fn linked_dev_command(
4375    root: &Path,
4376    launch: &LinkedDevLaunch,
4377    host: &str,
4378    port: u16,
4379    session: Option<&(u16, String)>,
4380) -> Command {
4381    let mut cmd = Command::new(&launch.executable);
4382    cmd.args(&launch.arguments);
4383    cmd.current_dir(root);
4384    cmd.env("HOST", host);
4385    cmd.env("PROA_HOST", host);
4386    cmd.env("PORT", port.to_string());
4387    public_assets::runtime_environment(&mut cmd, launch.public_assets.as_deref());
4388    // These two are the whole contract with `proa_framework_axum::serve`, which
4389    // injects the live-reload client only when both are present. A stale
4390    // value inherited from the environment must never survive into a run with
4391    // live reload switched off.
4392    match session {
4393        Some((reload_port, token)) => {
4394            cmd.env(reload::RELOAD_PORT_ENV, reload_port.to_string());
4395            cmd.env(reload::RELOAD_TOKEN_ENV, token);
4396        }
4397        None => {
4398            cmd.env_remove(reload::RELOAD_PORT_ENV);
4399            cmd.env_remove(reload::RELOAD_TOKEN_ENV);
4400        }
4401    }
4402    cmd
4403}
4404
4405fn print_linked_dev_launch(launch: &LinkedDevLaunch) {
4406    if launch.single_pass {
4407        dev_ui::detail!(
4408            "starting final linked server `{}` with plan {} (single-pass, final cache {} reused)",
4409            launch.executable.display(),
4410            launch.plan_id,
4411            launch.reused_final_artifacts,
4412        );
4413    } else {
4414        dev_ui::detail!(
4415            "starting final linked server `{}` with plan {} (descriptor cache {}/{}, final cache {} reused)",
4416            launch.executable.display(),
4417            launch.plan_id,
4418            launch.reused_descriptor_artifacts,
4419            launch.descriptor_artifacts,
4420            launch.reused_final_artifacts,
4421        );
4422    }
4423}
4424
4425fn run_command_status(root: &Path, command: &[String], label: &str) -> Result<()> {
4426    dev_ui::detail!("running {}", shellish(command));
4427    let mut base = command_base(root, command)?;
4428    // The interactive dev view shows a tool's own output only when it fails.
4429    let run = if dev_ui::pretty() {
4430        // `output()` would close stdin. A command may still prompt on it.
4431        base.stdin(std::process::Stdio::inherit())
4432            .output()
4433            .map(|output| {
4434                if !output.status.success() {
4435                    let _ = io::Write::write_all(&mut io::stderr(), &output.stdout);
4436                    let _ = io::Write::write_all(&mut io::stderr(), &output.stderr);
4437                }
4438                output.status
4439            })
4440    } else {
4441        base.status()
4442    };
4443    let status = match run {
4444        Ok(status) => status,
4445        // A missing program surfaces as a bare "No such file or directory",
4446        // which reads as a missing input file rather than a tool that was
4447        // never installed. Name the program and say how to get it.
4448        Err(error) if error.kind() == io::ErrorKind::NotFound => {
4449            let program = command.first().map(String::as_str).unwrap_or(label);
4450            bail!("{}", missing_program_message(program));
4451        }
4452        Err(error) => return Err(error).with_context(|| format!("run `{}`", shellish(command))),
4453    };
4454    exit_status_to_result(status, label)
4455}
4456
4457fn missing_program_message(program: &str) -> String {
4458    let hint = match program {
4459        "tailwindcss" => {
4460            if cfg!(windows) {
4461                "\n  Install the standalone Tailwind CSS CLI v4 for Windows as tailwindcss.exe\n  \
4462                 and add its directory to PATH, then reopen your terminal.\n  \
4463                 See https://proa.so/docs/cli/new-site#tailwind-prerequisite"
4464            } else {
4465                "\n  Install Tailwind CSS CLI v4 with the Proa installer:\n  \
4466                 curl -fsSL https://proa.so/install.sh | \
4467                 sh -s -- --tailwind-only\n  \
4468                 Or, on macOS or Linux with Homebrew: brew install tailwindcss"
4469            }
4470        }
4471        _ => "\n  Install it and make sure it is on PATH, or set an explicit `command` for this asset in proa.config.rs.",
4472    };
4473    format!("`{program}` was not found on PATH.{hint}")
4474}
4475
4476fn command_base(root: &Path, command: &[String]) -> Result<Command> {
4477    let Some((program, args)) = command.split_first() else {
4478        bail!("command cannot be empty")
4479    };
4480    let mut cmd = Command::new(program);
4481    cmd.args(args);
4482    cmd.current_dir(root);
4483    Ok(cmd)
4484}
4485
4486fn exit_status_to_result(status: ExitStatus, label: &str) -> Result<()> {
4487    if status.success() {
4488        Ok(())
4489    } else {
4490        bail!("{label} exited with {status}")
4491    }
4492}
4493
4494fn stop_child(child: &mut Child) -> Result<()> {
4495    if child.try_wait()?.is_some() {
4496        return Ok(());
4497    }
4498
4499    #[cfg(unix)]
4500    {
4501        // Signal the whole process group: TERM first so the server can shut
4502        // down gracefully and release its port, then KILL if it lingers.
4503        let group = -(child.id() as i32);
4504        unsafe { libc::kill(group, libc::SIGTERM) };
4505        let deadline = Instant::now() + Duration::from_secs(2);
4506        loop {
4507            if child.try_wait()?.is_some() {
4508                return Ok(());
4509            }
4510            if Instant::now() >= deadline {
4511                break;
4512            }
4513            // Most servers exit promptly on TERM. Observe that exit without
4514            // imposing a whole watch-poll interval before activating the build.
4515            thread::sleep(Duration::from_millis(5));
4516        }
4517        unsafe { libc::kill(group, libc::SIGKILL) };
4518        let _ = child.wait();
4519        Ok(())
4520    }
4521
4522    #[cfg(not(unix))]
4523    {
4524        child.kill().context("stop dev command")?;
4525        let _ = child.wait();
4526        Ok(())
4527    }
4528}
4529
4530type WatchSnapshot = BTreeMap<PathBuf, FileStamp>;
4531
4532#[derive(Debug, Clone, PartialEq, Eq)]
4533enum DevWatchDecision {
4534    Idle,
4535    Debouncing,
4536    Ready(WatchSnapshot),
4537}
4538
4539#[derive(Debug)]
4540struct DevWatchDebouncer {
4541    committed: WatchSnapshot,
4542    pending: Option<(WatchSnapshot, Duration)>,
4543    delay: Duration,
4544}
4545
4546impl DevWatchDebouncer {
4547    fn new(committed: WatchSnapshot, delay: Duration) -> Self {
4548        Self {
4549            committed,
4550            pending: None,
4551            delay,
4552        }
4553    }
4554
4555    fn next_poll_delay(&self, now: Duration) -> Duration {
4556        let Some((_, first_seen)) = self.pending.as_ref() else {
4557            return DEV_WATCH_POLL;
4558        };
4559        // Wake at the end of the quiet window instead of rounding it up to
4560        // another whole poll interval. A fresh snapshot still authorizes the
4561        // rebuild; changed bytes reset the full window in observe().
4562        self.delay
4563            .saturating_sub(now.saturating_sub(*first_seen))
4564            .clamp(Duration::from_millis(1), DEV_WATCH_POLL)
4565    }
4566
4567    fn observe(&mut self, now: Duration, snapshot: WatchSnapshot) -> DevWatchDecision {
4568        if snapshot == self.committed {
4569            self.pending = None;
4570            return DevWatchDecision::Idle;
4571        }
4572
4573        match &mut self.pending {
4574            Some((pending, first_seen)) if *pending == snapshot => {
4575                if now.saturating_sub(*first_seen) >= self.delay {
4576                    DevWatchDecision::Ready(snapshot)
4577                } else {
4578                    DevWatchDecision::Debouncing
4579                }
4580            }
4581            pending => {
4582                *pending = Some((snapshot, now));
4583                DevWatchDecision::Debouncing
4584            }
4585        }
4586    }
4587
4588    fn commit(&mut self, snapshot: WatchSnapshot) {
4589        self.committed = snapshot;
4590        self.pending = None;
4591    }
4592}
4593
4594fn watch_snapshot(root: &Path, paths: &[PathBuf]) -> Result<WatchSnapshot> {
4595    let mut snapshot = BTreeMap::new();
4596    for rel in paths {
4597        let path = root.join(rel);
4598        if path.exists() {
4599            collect_file_stamps(root, &path, &mut snapshot)?;
4600        }
4601    }
4602    Ok(snapshot)
4603}
4604
4605fn collect_file_stamps(
4606    root: &Path,
4607    path: &Path,
4608    snapshot: &mut BTreeMap<PathBuf, FileStamp>,
4609) -> Result<()> {
4610    let mut metadata = match fs::symlink_metadata(path) {
4611        Ok(metadata) => metadata,
4612        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
4613        Err(error) => return Err(error).with_context(|| format!("stat {}", path.display())),
4614    };
4615    if metadata.file_type().is_symlink() {
4616        let Ok(target) = fs::canonicalize(path) else {
4617            // Observe a broken symlink's own stamp instead of aborting the
4618            // watcher. Publication can then reject invalid public inputs while
4619            // keeping the last valid server running.
4620            let rel = path.strip_prefix(root).unwrap_or(path).to_path_buf();
4621            snapshot.insert(rel, FileStamp::from_metadata(&metadata));
4622            return Ok(());
4623        };
4624        if path
4625            .ancestors()
4626            .skip(1)
4627            .any(|parent| fs::canonicalize(parent).is_ok_and(|parent| parent == target))
4628        {
4629            // Observe the cycle's link instead of traversing it. Publication
4630            // can then reject invalid public inputs without losing the server.
4631            let rel = path.strip_prefix(root).unwrap_or(path).to_path_buf();
4632            snapshot.insert(rel, FileStamp::from_metadata(&metadata));
4633            return Ok(());
4634        }
4635        // Preserve ordinary source-link watching. Only link traversal needs
4636        // canonicalization; regular source trees retain one metadata read.
4637        metadata = match fs::metadata(path) {
4638            Ok(metadata) => metadata,
4639            Err(_) => {
4640                let rel = path.strip_prefix(root).unwrap_or(path).to_path_buf();
4641                snapshot.insert(rel, FileStamp::from_metadata(&metadata));
4642                return Ok(());
4643            }
4644        };
4645    }
4646    if metadata.is_dir() {
4647        if should_ignore_dir(path) {
4648            return Ok(());
4649        }
4650        let entries = match fs::read_dir(path) {
4651            Ok(entries) => entries,
4652            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
4653            Err(error) => return Err(error).with_context(|| format!("read {}", path.display())),
4654        };
4655        for entry in entries {
4656            collect_file_stamps(root, &entry?.path(), snapshot)?;
4657        }
4658    } else if metadata.is_file() {
4659        let rel = path.strip_prefix(root).unwrap_or(path).to_path_buf();
4660        snapshot.insert(rel, FileStamp::from_metadata(&metadata));
4661    }
4662    Ok(())
4663}
4664
4665fn should_ignore_dir(path: &Path) -> bool {
4666    matches!(
4667        path.file_name().and_then(|name| name.to_str()),
4668        Some("target" | "node_modules" | ".git")
4669    )
4670}
4671
4672#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4673struct FileStamp {
4674    len: u64,
4675    modified_nanos: u128,
4676}
4677
4678impl FileStamp {
4679    fn from_metadata(metadata: &fs::Metadata) -> Self {
4680        let modified_nanos = metadata
4681            .modified()
4682            .ok()
4683            .and_then(|modified| modified.duration_since(UNIX_EPOCH).ok())
4684            .map(|duration| duration.as_nanos())
4685            .unwrap_or(0);
4686
4687        Self {
4688            len: metadata.len(),
4689            modified_nanos,
4690        }
4691    }
4692}
4693
4694fn shellish(command: &[String]) -> String {
4695    command.join(" ")
4696}
4697
4698#[cfg(test)]
4699mod tests;