Skip to main content

nativeview_cli/cargo_env/
app_context.rs

1//! `AppContext` & `NvSdkRoot` resolution for `nv build` / `nv run` / `nv dev`.
2
3use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};
4use std::env;
5use std::ffi::OsStr;
6use std::path::{Path, PathBuf};
7
8use super::sdk::{default_sdk_cache_dir, SdkManifest, CLI_VERSION, SDK_MANIFEST_FILENAME};
9use super::{
10    absolutize_path_from, find_package, load_full_cargo_metadata_in, select_cdylib_package,
11    CargoMetadata, CargoPackageInfo,
12};
13
14const DEFAULT_ROOT_WORKSPACE_APP: &str = "nativeview-studio-workspace";
15
16/// Selector identifying which NV app crate to build, run, or watch.
17#[derive(Debug, Default, Clone, PartialEq, Eq)]
18pub struct AppSelector {
19    pub app_path: Option<PathBuf>,
20    pub package: Option<String>,
21}
22
23/// Resolved NV SDK root (either a packaged read-only SDK containing `sdk-manifest.json` or a
24/// local monorepo checkout containing `hosts/` and `packages/core/abi`).
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct NvSdkRoot(pub PathBuf);
27
28impl NvSdkRoot {
29    pub fn path(&self) -> &Path {
30        &self.0
31    }
32
33    /// Returns `true` when this root is a packaged read-only SDK tarball (`sdk-manifest.json`).
34    pub fn is_packaged_sdk(&self) -> bool {
35        self.0.join(SDK_MANIFEST_FILENAME).is_file()
36    }
37
38    /// Loads `sdk-manifest.json` when present (packaged SDK), returning `Ok(None)` for checkouts.
39    pub fn manifest(&self) -> Result<Option<SdkManifest>, String> {
40        SdkManifest::load_from_dir(&self.0)
41    }
42
43    /// Returns `true` when `sdk-manifest.json` exists and declares `prebuilt_codegen: true`.
44    pub fn has_prebuilt_codegen(&self) -> bool {
45        self.manifest()
46            .ok()
47            .flatten()
48            .is_some_and(|m| m.prebuilt_codegen)
49    }
50}
51
52/// Resolved NV app crate metadata including transitive `[package.metadata.nativeview] host_module` names
53/// and transitive non-dev path-dependency package directories.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct AppContext {
56    pub manifest_path: PathBuf,
57    pub manifest_dir: PathBuf,
58    pub workspace_root: PathBuf,
59    pub target_directory: PathBuf,
60    pub package_id: String,
61    pub package_name: String,
62    pub package_version: String,
63    pub lib_name: String,
64    pub has_web_feature: bool,
65    pub has_lockfile: bool,
66    pub host_modules: Vec<String>,
67    pub path_deps: Vec<PathBuf>,
68}
69
70impl AppContext {
71    pub fn manifest_app_info(&self) -> crate::manifest::ManifestAppInfo {
72        crate::manifest::ManifestAppInfo {
73            package_name: self.package_name.clone(),
74            package_version: self.package_version.clone(),
75            lib_name: self.lib_name.clone(),
76        }
77    }
78
79    /// Root directory used for worktree-scoped `nv dev` session discovery (`session.json`):
80    /// shares `sdk_root` for in-SDK apps (including standalone `[workspace]` examples) so
81    /// `nv dev wait` / `nv dev status` find the session from either the repo root or example dir,
82    /// while external user projects stay scoped to their own `workspace_root`.
83    pub fn dev_session_root(&self, sdk_root: Option<&NvSdkRoot>) -> PathBuf {
84        if let Some(sdk) = sdk_root
85            && !sdk.is_packaged_sdk()
86            && path_starts_with_or_canonical(&self.manifest_dir, sdk.path())
87        {
88            sdk.path().to_path_buf()
89        } else {
90            self.workspace_root.clone()
91        }
92    }
93}
94
95/// Walks non-dev `path_deps` transitively from `root_manifest_dir` across `meta.packages` and
96/// returns canonicalized dependency package directories (excluding `root_manifest_dir` itself).
97pub fn collect_transitive_path_deps(
98    meta: &CargoMetadata,
99    root_manifest_dir: &Path,
100) -> Vec<PathBuf> {
101    let mut by_manifest_dir: HashMap<PathBuf, Vec<PathBuf>> = HashMap::new();
102    for pkg in &meta.packages {
103        let Some(dir) = pkg.manifest_dir() else {
104            continue;
105        };
106        let canon_dir = std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
107        let dep_dirs: Vec<PathBuf> = pkg
108            .path_deps
109            .iter()
110            .map(|dp| std::fs::canonicalize(dp).unwrap_or_else(|_| dp.clone()))
111            .collect();
112        by_manifest_dir.insert(canon_dir, dep_dirs);
113    }
114
115    let start = std::fs::canonicalize(root_manifest_dir)
116        .unwrap_or_else(|_| root_manifest_dir.to_path_buf());
117    let mut visited = HashSet::new();
118    let mut queue = VecDeque::new();
119    visited.insert(start.clone());
120    queue.push_back(start.clone());
121
122    let mut deps = Vec::new();
123    while let Some(dir) = queue.pop_front() {
124        if dir != start {
125            deps.push(dir.clone());
126        }
127        if let Some(children) = by_manifest_dir.get(&dir) {
128            for child in children {
129                if visited.insert(child.clone()) {
130                    queue.push_back(child.clone());
131                }
132            }
133        }
134    }
135    deps
136}
137
138/// Returns `true` when `dir` looks like a valid NV SDK root (either a packaged SDK containing
139/// `sdk-manifest.json` or a local monorepo checkout containing `hosts/` and `packages/core/abi`).
140pub fn is_nv_sdk_root(dir: &Path) -> bool {
141    dir.join(SDK_MANIFEST_FILENAME).is_file()
142        || (dir.join("hosts").is_dir() && dir.join("packages").join("core").join("abi").is_dir())
143}
144
145fn find_sdk_ancestor(start: &Path) -> Option<PathBuf> {
146    start.ancestors().find(|d| is_nv_sdk_root(d)).map(Path::to_path_buf)
147}
148
149/// Walks the resolved Cargo dependency graph from `root_pkg_id` and collects all unique sorted
150/// `[package.metadata.nativeview] host_module` tokens across reachable packages.
151pub fn collect_host_modules(meta: &CargoMetadata, root_pkg_id: &str) -> Vec<String> {
152    let by_id: HashMap<&str, &CargoPackageInfo> =
153        meta.packages.iter().map(|p| (p.id.as_str(), p)).collect();
154    let mut visited = HashSet::new();
155    let mut queue = VecDeque::new();
156    let mut modules = BTreeSet::new();
157
158    if visited.insert(root_pkg_id) {
159        queue.push_back(root_pkg_id);
160    }
161    while let Some(id) = queue.pop_front() {
162        if let Some(pkg) = by_id.get(id)
163            && let Some(m) = pkg.host_module.as_deref()
164        {
165            let normalized: String = m.chars().map(|c| c.to_ascii_lowercase()).collect();
166            modules.insert(normalized);
167        }
168        if let Some(deps) = meta.resolve_deps.get(id) {
169            for dep in deps {
170                if visited.insert(dep.as_str()) {
171                    queue.push_back(dep.as_str());
172                }
173            }
174        }
175    }
176    modules.into_iter().collect()
177}
178
179/// Resolves `NvSdkRoot` via precedence:
180/// 1. Explicit `--sdk-root`
181/// 2. `$NV_SDK_ROOT`
182/// 3. Ancestor of resolved `nativeview-abi` dependency's `manifest_path`
183/// 4. Ancestor walk from `app_manifest_dir` (monorepo checkout)
184/// 5. Version-pinned read-only SDK cache (`$XDG_CACHE_HOME/nativeview/sdk/vX.Y.Z/`)
185/// 6. Compile-time `CARGO_MANIFEST_DIR/../../..` if valid on disk
186/// 7. Actionable error pointing to `nv sdk install`
187pub fn resolve_sdk_root(
188    sdk_override: Option<&Path>,
189    env_sdk_root: Option<&str>,
190    meta: &CargoMetadata,
191    app_manifest_dir: &Path,
192    cwd: &Path,
193) -> Result<NvSdkRoot, String> {
194    if let Some(explicit) = sdk_override {
195        let abs = absolutize_path_from(explicit, cwd);
196        return if is_nv_sdk_root(&abs) {
197            Ok(NvSdkRoot(abs))
198        } else {
199            Err(format!(
200                "--sdk-root '{}' is not a valid NV SDK root (expected sdk-manifest.json or hosts/ + packages/core/abi)",
201                abs.display()
202            ))
203        };
204    }
205    if let Some(env_val) = env_sdk_root.map(str::trim).filter(|s| !s.is_empty()) {
206        let abs = absolutize_path_from(Path::new(env_val), cwd);
207        return if is_nv_sdk_root(&abs) {
208            Ok(NvSdkRoot(abs))
209        } else {
210            Err(format!(
211                "NV_SDK_ROOT '{}' is not a valid NV SDK root (expected sdk-manifest.json or hosts/ + packages/core/abi)",
212                abs.display()
213            ))
214        };
215    }
216    if let Some(abi_pkg) = meta.packages.iter().find(|p| p.name == "nativeview-abi")
217        && let Some(root) = find_sdk_ancestor(&abi_pkg.manifest_path)
218    {
219        return Ok(NvSdkRoot(root));
220    }
221    if let Some(root) = find_sdk_ancestor(app_manifest_dir) {
222        return Ok(NvSdkRoot(root));
223    }
224    let cached = default_sdk_cache_dir(CLI_VERSION);
225    if is_nv_sdk_root(&cached) {
226        return Ok(NvSdkRoot(cached));
227    }
228    let compile_root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("..").join("..").join("..");
229    if let Ok(canon) = std::fs::canonicalize(&compile_root)
230        && is_nv_sdk_root(&canon)
231    {
232        return Ok(NvSdkRoot(canon));
233    }
234    Err(
235        "could not locate NV SDK root; run `nv sdk install`, pass --sdk-root <DIR>, or set NV_SDK_ROOT"
236            .to_owned(),
237    )
238}
239
240fn paths_equal_or_canonical(a: &Path, b: &Path) -> bool {
241    a == b
242        || match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
243            (Ok(ca), Ok(cb)) => ca == cb,
244            _ => false,
245        }
246}
247
248fn path_starts_with_or_canonical(child: &Path, parent: &Path) -> bool {
249    child.starts_with(parent)
250        || match (std::fs::canonicalize(child), std::fs::canonicalize(parent)) {
251            (Ok(cc), Ok(cp)) => cc.starts_with(cp),
252            _ => false,
253        }
254}
255
256/// Resolves the effective Cargo `target_directory` for an app:
257/// - Honors explicit non-blank `CARGO_TARGET_DIR` (already resolved into `meta_target_dir` by Cargo).
258/// - NEVER writes `target/` inside a packaged read-only SDK (`sdk-manifest.json`).
259/// - Shares `<sdk_root>/target` ONLY for in-SDK standalone workspaces (`manifest_dir` inside
260///   a monorepo checkout `sdk_root`) whose `meta_target_dir` is still the default `<workspace_root>/target`.
261pub fn resolve_app_target_directory(
262    meta_target_dir: &Path,
263    meta_workspace_root: &Path,
264    manifest_dir: &Path,
265    sdk_root: &Path,
266    env_cargo_target_dir: Option<&OsStr>,
267) -> PathBuf {
268    let has_env = env_cargo_target_dir.is_some_and(|v| {
269        v.to_str().map(|s| !s.trim().is_empty()).unwrap_or(!v.is_empty())
270    });
271    let is_packaged = sdk_root.join(SDK_MANIFEST_FILENAME).is_file();
272    if !has_env
273        && !is_packaged
274        && path_starts_with_or_canonical(manifest_dir, sdk_root)
275        && paths_equal_or_canonical(meta_target_dir, &meta_workspace_root.join("target"))
276    {
277        return sdk_root.join("target");
278    }
279    meta_target_dir.to_path_buf()
280}
281
282fn resolve_manifest_path_from_app_path(app_path: &Path, cwd: &Path) -> Result<PathBuf, String> {
283    let abs = absolutize_path_from(app_path, cwd);
284    if abs.is_dir() {
285        let manifest = abs.join("Cargo.toml");
286        if manifest.is_file() {
287            return Ok(manifest);
288        }
289        return Err(format!("no Cargo.toml found in '{}'", abs.display()));
290    }
291    if abs.is_file() {
292        return Ok(abs);
293    }
294    Err(format!("app path does not exist: '{}'", app_path.display()))
295}
296
297/// Resolves [`AppContext`] and an optional [`NvSdkRoot`] (never failing when no SDK is installed,
298/// so standalone `[features] web` apps work with zero `NV_SDK_ROOT`).
299pub fn resolve_app_and_optional_sdk(
300    selector: &AppSelector,
301    sdk_override: Option<&Path>,
302    cwd: &Path,
303    filter_platform: Option<&str>,
304) -> Result<(AppContext, Option<NvSdkRoot>), String> {
305    let explicit_manifest = match selector.app_path.as_deref() {
306        Some(p) => Some(resolve_manifest_path_from_app_path(p, cwd)?),
307        None => None,
308    };
309
310    let cwd_manifest = cwd.join("Cargo.toml");
311    let query_manifest = explicit_manifest.as_deref().or_else(|| {
312        cwd_manifest.is_file().then_some(cwd_manifest.as_path())
313    });
314
315    let meta = load_full_cargo_metadata_in(query_manifest, cwd, filter_platform)?;
316    let pkg = select_app_package(&meta, selector.package.as_deref(), explicit_manifest.as_deref(), cwd)?;
317    let manifest_dir = pkg
318        .manifest_dir()
319        .ok_or_else(|| format!("invalid manifest path '{}'", pkg.manifest_path.display()))?
320        .to_path_buf();
321    let lib_name = pkg
322        .cdylib_name
323        .clone()
324        .ok_or_else(|| format!("package '{}' has no `cdylib` library target", pkg.name))?;
325
326    let env_sdk = env::var("NV_SDK_ROOT").ok();
327    let sdk_root = if sdk_override.is_some()
328        || env_sdk.as_deref().is_some_and(|s| !s.trim().is_empty())
329    {
330        Some(resolve_sdk_root(sdk_override, env_sdk.as_deref(), &meta, &manifest_dir, cwd)?)
331    } else {
332        resolve_sdk_root(None, None, &meta, &manifest_dir, cwd).ok()
333    };
334
335    let env_target = env::var_os("CARGO_TARGET_DIR");
336    let target_directory = match sdk_root.as_ref() {
337        Some(sdk) => resolve_app_target_directory(
338            &meta.target_directory,
339            &meta.workspace_root,
340            &manifest_dir,
341            sdk.path(),
342            env_target.as_deref(),
343        ),
344        None => meta.target_directory.clone(),
345    };
346    let host_modules = collect_host_modules(&meta, &pkg.id);
347    let path_deps = collect_transitive_path_deps(&meta, &manifest_dir);
348    let has_lockfile = meta.workspace_root.join("Cargo.lock").is_file();
349
350    let ctx = AppContext {
351        manifest_path: pkg.manifest_path.clone(),
352        manifest_dir,
353        workspace_root: meta.workspace_root.clone(),
354        target_directory,
355        package_id: pkg.id.clone(),
356        package_name: pkg.name.clone(),
357        package_version: pkg.version.clone(),
358        lib_name,
359        has_web_feature: pkg.has_feature("web"),
360        has_lockfile,
361        host_modules,
362        path_deps,
363    };
364    Ok((ctx, sdk_root))
365}
366
367/// Resolves both [`AppContext`] and [`NvSdkRoot`] from CLI selector, optional `--sdk-root`, `cwd`,
368/// and optional `--filter-platform` triple.
369pub fn resolve_app_and_sdk(
370    selector: &AppSelector,
371    sdk_override: Option<&Path>,
372    cwd: &Path,
373    filter_platform: Option<&str>,
374) -> Result<(AppContext, NvSdkRoot), String> {
375    let (ctx, sdk_opt) = resolve_app_and_optional_sdk(selector, sdk_override, cwd, filter_platform)?;
376    let sdk_root = sdk_opt.ok_or_else(|| {
377        "could not locate NV SDK root; run `nv sdk install`, pass --sdk-root <DIR>, or set NV_SDK_ROOT"
378            .to_owned()
379    })?;
380    Ok((ctx, sdk_root))
381}
382
383fn select_app_package<'a>(
384    meta: &'a CargoMetadata,
385    package: Option<&str>,
386    explicit_manifest: Option<&Path>,
387    cwd: &Path,
388) -> Result<&'a CargoPackageInfo, String> {
389    if package.is_some() || explicit_manifest.is_some() {
390        return select_cdylib_package(meta, package, explicit_manifest);
391    }
392    let cwd_manifest = cwd.join("Cargo.toml");
393    if cwd_manifest.is_file()
394        && let Ok(pkg) = select_cdylib_package(meta, None, Some(&cwd_manifest))
395    {
396        return Ok(pkg);
397    }
398    if let Some(default_pkg) = find_package(meta, DEFAULT_ROOT_WORKSPACE_APP)
399        && default_pkg.cdylib_name.is_some()
400    {
401        return Ok(default_pkg);
402    }
403    select_cdylib_package(meta, None, Some(&meta.workspace_root.join("Cargo.toml")))
404}