nativeview-cli 0.1.0-rc.1

Developer CLI (`nv`) for Native View Engine: dev hot-reload, builds, pairing, SDK management, app scaffolding, and docs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
//! Cargo build/rustc invocation and `--message-format=json-render-diagnostics` artifact extraction.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::{Command as ProcessCommand, Stdio};

use super::{
    absolutize_path, find_package, load_cargo_metadata, preserve_relative_cargo_target_dir,
    select_cdylib_package, CargoMetadata,
};

/// Result of resolving and building a Cargo package's `cdylib`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BuiltCdylib {
    pub package_name: String,
    pub lib_name: String,
    pub dylib_path: PathBuf,
}

/// Artifact kind built by [`build_artifact`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArtifactKind {
    Cdylib,
    Staticlib,
    Bin,
}

/// Declarative specification for building any Cargo `cdylib`, `staticlib`, or `bin` artifact.
#[derive(Debug, Clone)]
pub struct BuildArtifactSpec {
    pub manifest_path: Option<PathBuf>,
    pub working_dir: PathBuf,
    pub package: String,
    pub package_id: String,
    pub artifact_name: String,
    pub kind: ArtifactKind,
    pub crate_type_override: Option<&'static str>,
    pub target_triple: Option<String>,
    pub no_default_features: bool,
    pub features: Vec<String>,
    pub release: bool,
    pub locked: bool,
    pub target_dir: Option<PathBuf>,
    pub env: BTreeMap<String, String>,
    pub expected_suffix: String,
}

impl BuildArtifactSpec {
    /// Builds the `cargo` argument list (excluding `cargo` itself and `--message-format=...`).
    pub fn cargo_args(&self) -> Vec<String> {
        self.cargo_base_args(false)
    }

    /// Builds the full `cargo rustc ... -- <rustc_args>` argument list for display or dry-run plans.
    pub fn cargo_args_with_rustc(&self, rustc_args: &[String]) -> Vec<String> {
        let mut args = self.cargo_base_args(!rustc_args.is_empty());
        if !rustc_args.is_empty() {
            args.push("--".to_owned());
            args.extend(rustc_args.iter().cloned());
        }
        args
    }

    fn cargo_base_args(&self, force_rustc: bool) -> Vec<String> {
        let use_rustc = force_rustc || self.crate_type_override.is_some();
        let mut args = vec![if use_rustc { "rustc" } else { "build" }.to_owned()];
        if let Some(mp) = &self.manifest_path {
            args.push("--manifest-path".to_owned());
            args.push(mp.display().to_string());
        }
        if self.locked {
            args.push("--locked".to_owned());
        }
        if self.release {
            args.push("--release".to_owned());
        }
        args.push("-p".to_owned());
        args.push(self.package.clone());
        match self.kind {
            ArtifactKind::Cdylib | ArtifactKind::Staticlib => {
                args.push("--lib".to_owned());
                if let Some(ct) = self.crate_type_override {
                    args.push("--crate-type".to_owned());
                    args.push(ct.to_owned());
                }
            }
            ArtifactKind::Bin => {
                args.push("--bin".to_owned());
                args.push(self.artifact_name.clone());
            }
        }
        if self.no_default_features {
            args.push("--no-default-features".to_owned());
        }
        if !self.features.is_empty() {
            args.push("--features".to_owned());
            args.push(self.features.join(","));
        }
        if let Some(triple) = &self.target_triple {
            args.push("--target".to_owned());
            args.push(triple.clone());
        }
        args
    }
}

fn artifact_matches_package(msg: &serde_json::Value, package_id: &str, target_name: &str) -> bool {
    if !package_id.is_empty() {
        return msg.get("package_id").and_then(serde_json::Value::as_str) == Some(package_id);
    }
    msg.pointer("/target/name")
        .and_then(serde_json::Value::as_str)
        .is_some_and(|n| n.replace('-', "_") == target_name.replace('-', "_"))
}

fn array_contains_str(val: Option<&serde_json::Value>, needle: &str) -> bool {
    val.and_then(serde_json::Value::as_array)
        .is_some_and(|arr| arr.iter().any(|v| v.as_str() == Some(needle)))
}

/// Extracts the matched library artifact plus all sibling `filenames` from that Cargo JSON message.
pub(crate) fn parse_lib_artifact_with_siblings_from_json(
    stdout: &[u8],
    package_id: &str,
    lib_name: &str,
    crate_type: &str,
    suffix: &str,
) -> Result<(PathBuf, Vec<PathBuf>), String> {
    let mut found: Option<(PathBuf, Vec<PathBuf>)> = None;
    for line in stdout.split(|&b| b == b'\n') {
        if line.is_empty() {
            continue;
        }
        let Ok(msg) = serde_json::from_slice::<serde_json::Value>(line) else { continue };
        if msg.get("reason").and_then(serde_json::Value::as_str) != Some("compiler-artifact") {
            continue;
        }
        if !artifact_matches_package(&msg, package_id, lib_name) {
            continue;
        }
        let matches_type = array_contains_str(msg.pointer("/target/crate_types"), crate_type)
            || array_contains_str(msg.pointer("/target/kind"), crate_type);
        if !matches_type {
            continue;
        }
        if let Some(files) = msg.get("filenames").and_then(serde_json::Value::as_array) {
            let all_files: Vec<PathBuf> =
                files.iter().filter_map(serde_json::Value::as_str).map(PathBuf::from).collect();
            for f in &all_files {
                if f.to_string_lossy().ends_with(suffix) {
                    found = Some((f.clone(), all_files.clone()));
                }
            }
        }
    }
    found.ok_or_else(|| {
        format!("cargo JSON output contained no `{crate_type}` artifact ending with '{suffix}' for '{lib_name}'")
    })
}

/// Extracts the authoritative compiled library artifact (`cdylib` or `staticlib`) from Cargo JSON.
pub(crate) fn parse_lib_artifact_from_json(
    stdout: &[u8],
    package_id: &str,
    lib_name: &str,
    crate_type: &str,
    suffix: &str,
) -> Result<PathBuf, String> {
    parse_lib_artifact_with_siblings_from_json(stdout, package_id, lib_name, crate_type, suffix)
        .map(|(p, _)| p)
}

/// Extracts the authoritative compiled `cdylib` artifact path from Cargo JSON output.
pub fn parse_cdylib_artifact_from_json(
    stdout: &[u8],
    package_id: &str,
    lib_name: &str,
    suffix: &str,
) -> Result<PathBuf, String> {
    parse_lib_artifact_from_json(stdout, package_id, lib_name, "cdylib", suffix)
}

/// Extracts the authoritative compiled binary executable path from Cargo JSON output.
pub fn parse_bin_artifact_from_json(
    stdout: &[u8],
    package_id: &str,
    bin_name: &str,
) -> Result<PathBuf, String> {
    let mut found: Option<PathBuf> = None;
    for line in stdout.split(|&b| b == b'\n') {
        if line.is_empty() {
            continue;
        }
        let Ok(msg) = serde_json::from_slice::<serde_json::Value>(line) else { continue };
        if msg.get("reason").and_then(serde_json::Value::as_str) != Some("compiler-artifact") {
            continue;
        }
        if !package_id.is_empty()
            && msg.get("package_id").and_then(serde_json::Value::as_str) != Some(package_id)
        {
            continue;
        }
        if !array_contains_str(msg.pointer("/target/kind"), "bin") {
            continue;
        }
        if msg.pointer("/target/name").and_then(serde_json::Value::as_str) != Some(bin_name) {
            continue;
        }
        if let Some(exe) = msg
            .get("executable")
            .and_then(serde_json::Value::as_str)
            .filter(|s| !s.is_empty())
        {
            found = Some(PathBuf::from(exe));
        }
    }
    found.ok_or_else(|| format!("cargo JSON output contained no `bin` executable artifact for '{bin_name}'"))
}

/// Runs a configured Cargo build command with `--message-format=json-render-diagnostics`,
/// streaming human-readable diagnostics to stderr and returning stdout JSON lines.
pub fn run_cargo_json_command(
    cmd: &mut ProcessCommand,
    description: &str,
) -> Result<Vec<u8>, String> {
    let out = cmd
        .arg("--message-format=json-render-diagnostics")
        .stdout(Stdio::piped())
        .stderr(Stdio::inherit())
        .output()
        .map_err(|e| format!("failed to invoke `{description}`: {e}"))?;
    if !out.status.success() {
        return Err(format!("`{description}` failed with {}", out.status));
    }
    Ok(out.stdout)
}

/// Executes [`BuildArtifactSpec`] with optional trailing `rustc` flags (after `--`) and returns
/// the matched artifact plus sibling `filenames` from Cargo JSON output.
pub fn build_artifact_with_siblings_and_rustc_args(
    spec: &BuildArtifactSpec,
    rustc_args: &[String],
) -> Result<(PathBuf, Vec<PathBuf>), String> {
    let mut cmd = ProcessCommand::new("cargo");
    if spec.working_dir.is_dir() {
        cmd.current_dir(&spec.working_dir);
    }
    if let Some(td) = &spec.target_dir {
        cmd.env("CARGO_TARGET_DIR", td);
    } else {
        preserve_relative_cargo_target_dir(&mut cmd);
    }
    cmd.envs(&spec.env);
    let base_args = spec.cargo_base_args(!rustc_args.is_empty());
    cmd.args(&base_args);
    cmd.arg("--message-format=json-render-diagnostics");
    if !rustc_args.is_empty() {
        cmd.arg("--");
        cmd.args(rustc_args);
    }
    let desc = format!("cargo {}", spec.cargo_args_with_rustc(rustc_args).join(" "));
    let out = cmd
        .stdout(Stdio::piped())
        .stderr(Stdio::inherit())
        .output()
        .map_err(|e| format!("failed to invoke `{desc}`: {e}"))?;
    if !out.status.success() {
        return Err(format!("`{desc}` failed with {}", out.status));
    }
    let stdout = out.stdout;
    let (path, siblings) = match spec.kind {
        ArtifactKind::Cdylib => parse_lib_artifact_with_siblings_from_json(
            &stdout,
            &spec.package_id,
            &spec.artifact_name,
            "cdylib",
            &spec.expected_suffix,
        )?,
        ArtifactKind::Staticlib => parse_lib_artifact_with_siblings_from_json(
            &stdout,
            &spec.package_id,
            &spec.artifact_name,
            "staticlib",
            &spec.expected_suffix,
        )?,
        ArtifactKind::Bin => {
            let p = parse_bin_artifact_from_json(&stdout, &spec.package_id, &spec.artifact_name)?;
            (p.clone(), vec![p])
        }
    };
    if !path.is_file() {
        return Err(format!(
            "built '{}' but Cargo-reported artifact '{}' does not exist",
            spec.package,
            path.display()
        ));
    }
    Ok((path, siblings))
}

/// Executes [`BuildArtifactSpec`] and returns the matched artifact plus sibling `filenames` from
/// Cargo JSON output.
pub fn build_artifact_with_siblings(
    spec: &BuildArtifactSpec,
) -> Result<(PathBuf, Vec<PathBuf>), String> {
    build_artifact_with_siblings_and_rustc_args(spec, &[])
}

/// Executes [`BuildArtifactSpec`] with trailing `rustc` flags and returns the authoritative artifact path.
pub fn build_artifact_with_rustc_args(
    spec: &BuildArtifactSpec,
    rustc_args: &[String],
) -> Result<PathBuf, String> {
    build_artifact_with_siblings_and_rustc_args(spec, rustc_args).map(|(p, _)| p)
}

/// Executes [`BuildArtifactSpec`] and returns the authoritative Cargo-reported artifact path.
pub fn build_artifact(spec: &BuildArtifactSpec) -> Result<PathBuf, String> {
    build_artifact_with_siblings(spec).map(|(p, _)| p)
}

/// Builds a package's `cdylib` using already-loaded `CargoMetadata`.
pub fn build_package_cdylib_in(
    meta: &CargoMetadata,
    package: Option<&str>,
    manifest_path: Option<&Path>,
    release: bool,
    locked: bool,
) -> Result<BuiltCdylib, String> {
    let abs_manifest = match manifest_path {
        Some(mp) => {
            let abs = absolutize_path(mp)?;
            if !abs.is_file() {
                return Err(format!("manifest path does not exist: {}", mp.display()));
            }
            Some(abs)
        }
        None => None,
    };
    let pkg = select_cdylib_package(meta, package, abs_manifest.as_deref())?;
    let lib_name = pkg
        .cdylib_name
        .clone()
        .ok_or_else(|| format!("package '{}' has no `cdylib` target", pkg.name))?;
    let working_dir = abs_manifest
        .as_deref()
        .and_then(Path::parent)
        .map(Path::to_path_buf)
        .unwrap_or_else(|| meta.workspace_root.clone());
    let dylib_path = build_artifact(&BuildArtifactSpec {
        manifest_path: abs_manifest,
        working_dir,
        package: pkg.name.clone(),
        package_id: pkg.id.clone(),
        artifact_name: lib_name.clone(),
        kind: ArtifactKind::Cdylib,
        crate_type_override: None,
        target_triple: None,
        no_default_features: false,
        features: Vec::new(),
        release,
        locked: locked && meta.workspace_root.join("Cargo.lock").is_file(),
        target_dir: None,
        env: BTreeMap::new(),
        expected_suffix: std::env::consts::DLL_SUFFIX.to_owned(),
    })?;
    Ok(BuiltCdylib { package_name: pkg.name.clone(), lib_name, dylib_path })
}

/// Resolves and builds a Cargo package's `cdylib` (loads metadata once).
pub fn build_package_cdylib(
    package: Option<&str>,
    manifest_path: Option<&Path>,
    release: bool,
    locked: bool,
) -> Result<BuiltCdylib, String> {
    if let Some(mp) = manifest_path && !mp.is_file() {
        return Err(format!("manifest path does not exist: {}", mp.display()));
    }
    let meta = load_cargo_metadata(manifest_path)?;
    build_package_cdylib_in(&meta, package, manifest_path, release, locked)
}

/// Builds a binary target of a workspace package using already-loaded `CargoMetadata`.
pub fn build_workspace_bin_in(
    meta: &CargoMetadata,
    package: &str,
    bin_name: &str,
) -> Result<PathBuf, String> {
    let pkg = find_package(meta, package)
        .ok_or_else(|| format!("workspace package '{package}' not found in `cargo metadata`"))?;
    if !pkg.bin_names.iter().any(|b| b == bin_name) {
        return Err(format!("package '{package}' does not declare binary target '{bin_name}'"));
    }
    build_artifact(&BuildArtifactSpec {
        manifest_path: None,
        working_dir: meta.workspace_root.clone(),
        package: package.to_owned(),
        package_id: pkg.id.clone(),
        artifact_name: bin_name.to_owned(),
        kind: ArtifactKind::Bin,
        crate_type_override: None,
        target_triple: None,
        no_default_features: false,
        features: Vec::new(),
        release: false,
        locked: meta.workspace_root.join("Cargo.lock").is_file(),
        target_dir: None,
        env: BTreeMap::new(),
        expected_suffix: std::env::consts::EXE_SUFFIX.to_owned(),
    })
}