node-app-build 6.5.0

Mini app developer CLI: scaffold, validate, package node-app-* Debian packages
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//! `node-app deps` — inspect and manage the node-app dep sources that
//! `node-app dev` (platform mode) resolves and pins.
//!
//! Resolution is sticky by design: `.node-app/sources.lock` pins whichever
//! source won a dep's FIRST resolution (lock → sibling → cache → clone), and
//! a cache-pinned dep never auto-updates. These commands are the supported
//! way to see and change that state:
//!
//!   node-app deps                     status: where each platform dep resolves from
//!   node-app deps update <name>|--all fetch + reset cached clones to upstream HEAD
//!   node-app deps use <name> <src>    pin a dep to an explicit source
//!   node-app deps rm <name>|--all     drop cached clone(s) + lock pins → re-resolve
//!
//! Dep names are as they appear in `infra/debian/platform-depends`, without
//! the `node-app-` prefix (e.g. `lcd`, `ldk-node`).

use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{bail, Context, Result};

use super::dev::platform::parse_platform_depends;
use super::dev::sources_resolver;

// ── status ───────────────────────────────────────────────────────────────────

/// `node-app deps` — one row per entry in `platform-depends`: resolved
/// source, git rev, and working-tree state. With `fetch`, also contacts each
/// repo's remote and reports how far behind upstream the local copy is.
pub fn status(project_path: &Path, fetch: bool) -> Result<()> {
    // Canonicalize so sibling detection (parent-of-project) works when
    // invoked with the default relative path ".".
    let project_path = &project_path
        .canonicalize()
        .unwrap_or_else(|_| project_path.to_path_buf());
    let depends_path = project_path.join("infra/debian/platform-depends");
    if !depends_path.is_file() {
        bail!(
            "{} not found — run from the platform repo root (or pass --path)",
            depends_path.display()
        );
    }
    let dependencies = parse_platform_depends(&depends_path)?;
    let lock = sources_resolver::lock_entries(project_path);

    println!("{:<20} {:<44} {:<9} STATE", "DEP", "SOURCE", "REV");
    for dependency in &dependencies {
        let name = &dependency.key;
        let (source, dir) = classify(project_path, name, &lock);
        let (rev, state) = match &dir {
            Some(d) => {
                let rev = git_short_rev(d).unwrap_or_else(|| "-".into());
                let mut state = match dirty_file_count(d) {
                    Some(0) => "clean".to_string(),
                    Some(n) => format!("DIRTY ({n} files)"),
                    None => "-".to_string(),
                };
                if fetch {
                    match commits_behind(d) {
                        Some(0) => state.push_str(", up to date"),
                        Some(n) => state.push_str(&format!(", BEHIND {n}")),
                        None => state.push_str(", behind: ?"),
                    }
                }
                (rev, state)
            }
            None => ("-".into(), "-".into()),
        };
        let runtime_name = dir
            .as_deref()
            .and_then(|path| sources_resolver::read_manifest_name(path).ok())
            .unwrap_or_else(|| name.to_string());
        let identity = display_identity(name, &runtime_name);
        println!("{identity:<20} {source:<44} {rev:<9} {state}");
    }
    Ok(())
}

fn display_identity(key: &str, runtime_name: &str) -> String {
    if key == runtime_name {
        key.to_string()
    } else {
        format!("{key}{runtime_name}")
    }
}

/// Where would/does `name` resolve from? Returns a human label and the
/// source dir when one exists on disk. Mirrors `sources_resolver::resolve_one`
/// order without side effects.
fn classify(
    project_root: &Path,
    name: &str,
    lock: &[(String, PathBuf)],
) -> (String, Option<PathBuf>) {
    if let Some((_, p)) = lock.iter().find(|(n, _)| n == name) {
        if sources_resolver::is_node_app_dir(p) {
            let label = match source_kind(project_root, name, p) {
                SourceKind::Cache => "cache".to_string(),
                SourceKind::Sibling => format!("sibling {}", p.display()),
                SourceKind::Other => format!("custom {}", p.display()),
            };
            return (label, Some(p.clone()));
        }
        // Stale pin — fall through to what the next dev run would pick.
    }
    if let Some(sib) = sources_resolver::find_sibling(project_root, name) {
        return (format!("(will use sibling {})", sib.display()), Some(sib));
    }
    if let Ok(cache) = sources_resolver::cache_dep_dir(name) {
        if sources_resolver::is_node_app_dir(&cache) {
            return ("(will use cache)".to_string(), Some(cache));
        }
    }
    ("(will clone)".to_string(), None)
}

enum SourceKind {
    Cache,
    Sibling,
    Other,
}

fn source_kind(project_root: &Path, name: &str, path: &Path) -> SourceKind {
    if let Ok(cache) = sources_resolver::cache_dep_dir(name) {
        if same_path(path, &cache) {
            return SourceKind::Cache;
        }
    }
    if let Some(parent) = project_root.parent() {
        if same_path(path, &parent.join(format!("node-app-{name}"))) {
            return SourceKind::Sibling;
        }
    }
    SourceKind::Other
}

fn same_path(a: &Path, b: &Path) -> bool {
    let ca = a.canonicalize().unwrap_or_else(|_| a.to_path_buf());
    let cb = b.canonicalize().unwrap_or_else(|_| b.to_path_buf());
    ca == cb
}

// ── update ───────────────────────────────────────────────────────────────────

/// `node-app deps update` — fetch + hard-reset cached clones to upstream
/// HEAD. Only ever touches the global cache; sibling checkouts and custom
/// pins are never reset. Dirty cache clones are skipped unless `force`.
pub fn update(project_path: &Path, names: &[String], all: bool, force: bool) -> Result<()> {
    let deps_root = sources_resolver::cache_root()?.join("deps");
    if !all && names.is_empty() {
        bail!("pass one or more dep names or --all");
    }
    let targets: Vec<String> = if all {
        cached_dep_names(&deps_root)
    } else {
        names.to_vec()
    };
    if targets.is_empty() {
        println!("dep cache is empty ({})", deps_root.display());
        return Ok(());
    }

    let lock = sources_resolver::lock_entries(project_path);
    let mut failed = 0usize;
    for name in &targets {
        let path = sources_resolver::cache_dep_dir(name)?;
        if !path.join(".git").is_dir() {
            println!("{name}: not cached ({}) — skipped", path.display());
            continue;
        }
        if let Some(n) = dirty_file_count(&path) {
            if n > 0 && !force {
                println!(
                    "{name}: cache clone has {n} uncommitted change(s) — skipped (--force to reset anyway)"
                );
                continue;
            }
        }
        let old = git_short_rev(&path).unwrap_or_else(|| "?".into());
        if let Err(e) = git_in(&path, &["fetch", "--quiet"]) {
            println!("{name}: git fetch failed: {e:#}");
            failed += 1;
            continue;
        }
        if let Err(e) = git_in(&path, &["reset", "--hard", "--quiet", "origin/HEAD"]) {
            println!("{name}: git reset failed: {e:#}");
            failed += 1;
            continue;
        }
        let new = git_short_rev(&path).unwrap_or_else(|| "?".into());
        if old == new {
            println!("{name}: already up to date ({new})");
        } else {
            let count = git_count(&path, &format!("{old}..{new}"))
                .map(|n| format!(" (+{n} commits)"))
                .unwrap_or_default();
            println!("{name}: {old}{new}{count}");
        }
        // Keep the lockfile's recorded rev in sync when this cache copy is
        // the pinned source (no-op otherwise).
        sources_resolver::refresh_lock_rev(project_path, name, &path)?;
        // A pin pointing elsewhere means this update won't affect dev runs.
        if let Some((_, pinned)) = lock.iter().find(|(n, _)| n == name) {
            if !same_path(pinned, &path) {
                println!(
                    "  note: '{name}' is pinned to {} — dev runs are unaffected",
                    pinned.display()
                );
            }
        }
    }
    if failed > 0 {
        bail!("{failed} dep(s) failed to update");
    }
    Ok(())
}

// ── use ──────────────────────────────────────────────────────────────────────

/// `node-app deps use` — pin a dep to an explicit source in `sources.lock`.
pub fn use_source(
    project_path: &Path,
    name: &str,
    source: Option<&Path>,
    sibling: bool,
    cache: bool,
) -> Result<()> {
    let target: PathBuf = match (source, sibling, cache) {
        (Some(p), false, false) => p.to_path_buf(),
        (None, true, false) => {
            let parent = project_path
                .canonicalize()
                .unwrap_or_else(|_| project_path.to_path_buf())
                .parent()
                .map(|p| p.to_path_buf())
                .ok_or_else(|| anyhow::anyhow!("project root has no parent directory"))?;
            parent.join(format!("node-app-{name}"))
        }
        (None, false, true) => sources_resolver::cache_dep_dir(name)?,
        _ => bail!("pass exactly one of: a source PATH, --sibling, or --cache"),
    };
    if cache && !target.is_dir() {
        bail!(
            "no cached clone at {} — the next `node-app dev` clones it, or `node-app deps rm {name}` first to force a fresh one",
            target.display()
        );
    }
    sources_resolver::pin_lock_entry(project_path, name, &target)?;
    let rev = git_short_rev(&target).unwrap_or_else(|| "-".into());
    println!("✓ '{name}' now resolves from {} (rev {rev})", target.display());
    println!("  takes effect on the next `node-app dev` run; for a live session: node-app reload {name}");
    Ok(())
}

// ── rm ───────────────────────────────────────────────────────────────────────

/// `node-app deps rm <names...>` / `--all` — delete cached clones and prune
/// any `sources.lock` entries that pointed at them so the next `node-app dev`
/// re-resolves (sibling checkout wins again if present).
pub fn rm(project_path: &Path, names: &[String], all: bool) -> Result<()> {
    let deps_root = sources_resolver::cache_root()?.join("deps");

    if !all && names.is_empty() {
        bail!("pass one or more dep names (as in platform-depends, without the node-app- prefix) or --all");
    }
    let targets: Vec<String> = if all {
        cached_dep_names(&deps_root)
    } else {
        names.to_vec()
    };

    if targets.is_empty() {
        println!("dep cache is already empty ({})", deps_root.display());
        return Ok(());
    }

    let mut removed_paths = Vec::new();
    for name in &targets {
        let path = sources_resolver::cache_dep_dir(name)?;
        if path.is_dir() {
            // Canonicalize BEFORE deletion (impossible after) — lock entries
            // store canonicalized paths, so pruning must compare like with
            // like or symlinked cache roots leave stale entries behind.
            let canonical = path.canonicalize().unwrap_or_else(|_| path.clone());
            fs::remove_dir_all(&path)
                .with_context(|| format!("remove {}", path.display()))?;
            println!("✓ removed {}", path.display());
            removed_paths.push(canonical);
        } else {
            println!("⚠ not cached: {name} ({})", path.display());
            // Still prune a lock entry pointing at the (already gone) path so
            // `rm` also repairs a half-deleted state.
            removed_paths.push(path);
        }
    }

    let pruned = sources_resolver::prune_lock_entries(project_path, &removed_paths)?;
    if !pruned.is_empty() {
        println!("✓ pruned sources.lock entries: {}", pruned.join(", "));
    }
    println!("next `node-app dev` will re-resolve: sibling ../node-app-<name> wins over a fresh clone.");
    Ok(())
}

// ── git helpers ──────────────────────────────────────────────────────────────

fn cached_dep_names(deps_root: &Path) -> Vec<String> {
    let mut names: Vec<String> = match fs::read_dir(deps_root) {
        Ok(rd) => rd
            .filter_map(|e| e.ok())
            .filter(|e| e.path().is_dir())
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .collect(),
        Err(_) => Vec::new(),
    };
    names.sort();
    names
}

fn git_in(dir: &Path, args: &[&str]) -> Result<()> {
    let out = Command::new("git")
        .args(args)
        .current_dir(dir)
        .output()
        .with_context(|| format!("run git {args:?} in {}", dir.display()))?;
    if !out.status.success() {
        bail!(
            "git {} failed: {}",
            args.first().copied().unwrap_or(""),
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    Ok(())
}

fn git_capture(dir: &Path, args: &[&str]) -> Option<String> {
    let out = Command::new("git").args(args).current_dir(dir).output().ok()?;
    if !out.status.success() {
        return None;
    }
    Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

fn git_short_rev(dir: &Path) -> Option<String> {
    git_capture(dir, &["rev-parse", "--short", "HEAD"])
}

/// Number of changed/untracked paths, or None when not a git checkout.
fn dirty_file_count(dir: &Path) -> Option<usize> {
    git_capture(dir, &["status", "--porcelain"])
        .map(|s| s.lines().filter(|l| !l.trim().is_empty()).count())
}

fn git_count(dir: &Path, range: &str) -> Option<usize> {
    git_capture(dir, &["rev-list", "--count", range]).and_then(|s| s.parse().ok())
}

/// Commits HEAD is behind origin/HEAD, fetching first. None when the remote
/// is unreachable or the clone has no origin/HEAD ref (e.g. shallow).
fn commits_behind(dir: &Path) -> Option<usize> {
    git_in(dir, &["fetch", "--quiet"]).ok()?;
    git_count(dir, "HEAD..origin/HEAD")
}

// ── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn status_identity_shows_package_and_runtime_names_when_distinct() {
        assert_eq!(display_identity("stage-home", "home"), "stage-home → home");
        assert_eq!(display_identity("discovery", "discovery"), "discovery");
    }

    #[test]
    fn use_source_rejects_conflicting_flags() {
        let tmp = tempfile::TempDir::new().unwrap();
        // Both --sibling and --cache.
        let err = use_source(tmp.path(), "foo", None, true, true).unwrap_err();
        assert!(err.to_string().contains("exactly one of"));
        // Neither a path nor a flag.
        let err = use_source(tmp.path(), "foo", None, false, false).unwrap_err();
        assert!(err.to_string().contains("exactly one of"));
    }

    #[test]
    fn use_source_rejects_path_with_invalid_manifest() {
        let tmp = tempfile::TempDir::new().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(
            src.join("manifest.json"),
            r#"{"version":"1","app_type":"bun"}"#,
        )
        .unwrap();
        let err = use_source(tmp.path(), "foo", Some(&src), false, false).unwrap_err();
        assert!(err.to_string().contains("not a node-app source"));
    }

    #[test]
    fn use_source_pins_package_key_with_distinct_runtime_name() {
        let tmp = tempfile::TempDir::new().unwrap();
        let src = tmp.path().join("node-app-stage-home");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(
            src.join("manifest.json"),
            r#"{"name":"home","version":"1","app_type":"bun"}"#,
        )
        .unwrap();

        use_source(tmp.path(), "stage-home", Some(&src), false, false).unwrap();

        let entries = sources_resolver::lock_entries(tmp.path());
        assert_eq!(entries, vec![("stage-home".to_string(), src.canonicalize().unwrap())]);
    }

    #[test]
    fn update_requires_names_or_all() {
        let tmp = tempfile::TempDir::new().unwrap();
        let err = update(tmp.path(), &[], false, false).unwrap_err();
        assert!(err.to_string().contains("--all"));
    }

    #[test]
    fn rm_requires_names_or_all() {
        let tmp = tempfile::TempDir::new().unwrap();
        let err = rm(tmp.path(), &[], false).unwrap_err();
        assert!(err.to_string().contains("--all"));
    }
}