nova-cli 0.3.1

The Nova programming language: compiler, formatter, language server, package manager and documentation generator
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
//! The install scripts, `tools/install/install.sh` and `install.ps1` (spec
//! `docs/superpowers/specs/2026-10-12-phase-3-6a-release-preparation-design.md`
//! §6, §11.3), against a fake release that the loopback server serves: the
//! host's archive, packed as release.yml packs it around this test's own
//! `nova`, and its `SHA256SUMS`.
//!
//! `install.sh` runs (with `sh`, which is dash on Ubuntu) on Linux and
//! macOS; `install.ps1` runs in Windows PowerShell 5.1 on Windows, with
//! `NOVA_INSTALL_NO_PATH=1` so the user's PATH is never touched. Each run
//! has `NOVA_HOME` (and on Unix `HOME`) in the test's own directory, no
//! proxy, and `NOVA_INSTALL_BASE` at the loopback server, so every request
//! goes there. On a system the scripts have no archive for, only the tests
//! that need none run.

#[path = "../../nova-index/tests/support/mod.rs"]
mod support;

use std::collections::HashMap;
use std::env::consts::EXE_SUFFIX;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::{Arc, Mutex};

use support::{Response, Server};

/// The release the `latest` redirect names, and an older one.
const LATEST: &str = "1.2.3";
const OLDER: &str = "1.2.2";

/// The target whose archive the scripts pick on this system (spec §6.1
/// step 1), or `None` where there is none.
fn host_target() -> Option<&'static str> {
    if cfg!(all(target_os = "linux", target_arch = "x86_64")) {
        Some("x86_64-unknown-linux-gnu")
    } else if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
        Some("aarch64-apple-darwin")
    } else if cfg!(all(target_os = "macos", target_arch = "x86_64")) {
        Some("x86_64-apple-darwin")
    } else if cfg!(all(target_os = "windows", target_arch = "x86_64")) {
        Some("x86_64-pc-windows-msvc")
    } else {
        None
    }
}

/// The host's target, or `None` after saying the test is skipped.
fn target_or_skip() -> Option<&'static str> {
    let target = host_target();
    if target.is_none() {
        eprintln!("skipped: the install scripts have no archive for this system");
    }
    target
}

/// `nova-<version>-<target>.tar.gz`, or `.zip` on Windows (release.yml).
fn archive_name(version: &str, target: &str) -> String {
    let extension = if cfg!(windows) { "zip" } else { "tar.gz" };
    format!("nova-{version}-{target}.{extension}")
}

fn repo() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .ancestors()
        .nth(2)
        .expect("the repository holds crates/nova-cli")
        .to_path_buf()
}

/// A fresh, empty directory with a fixed name, so each run replaces the last.
fn fresh(name: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("nova-install-scripts-{name}"));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).expect("create the test directory");
    dir
}

/// This test's own `nova`, which the fake archives carry.
fn nova() -> PathBuf {
    PathBuf::from(env!("CARGO_BIN_EXE_nova"))
}

fn stdout(output: &Output) -> String {
    String::from_utf8_lossy(&output.stdout).into_owned()
}

fn stderr(output: &Output) -> String {
    String::from_utf8_lossy(&output.stderr).into_owned()
}

/// Run `command`, which must succeed, and return its stdout.
fn run_ok(command: &mut Command) -> String {
    let output = command
        .output()
        .unwrap_or_else(|e| panic!("running {command:?}: {e}"));
    assert!(
        output.status.success(),
        "{command:?} failed\n{}\n{}",
        stdout(&output),
        stderr(&output)
    );
    stdout(&output)
}

/// Windows PowerShell 5.1, started without the `PSModulePath` this test
/// inherited. Under PowerShell 7, which runs CI's `cargo test` on Windows,
/// that variable leads with PowerShell 7's module paths, and Windows
/// PowerShell started through another process, as here, then cannot load
/// its own `Microsoft.PowerShell.*` modules; without the variable it builds
/// its default (Microsoft's `about_PSModulePath`).
fn windows_powershell() -> Command {
    let mut command = Command::new("powershell");
    command.env_remove("PSModulePath");
    command
}

/// The SHA-256 of `path`, in lower-case hex, from the system's own tool.
fn sha256(path: &Path) -> String {
    let printed = if cfg!(windows) {
        run_ok(
            windows_powershell()
                .args(["-NoProfile", "-NonInteractive", "-Command"])
                .arg("(Get-FileHash -LiteralPath $env:HASH_FILE -Algorithm SHA256).Hash")
                .env("HASH_FILE", path),
        )
    } else if Command::new("sha256sum").arg("--version").output().is_ok() {
        run_ok(Command::new("sha256sum").arg(path))
    } else {
        run_ok(Command::new("shasum").args(["-a", "256"]).arg(path))
    };
    let hash = printed
        .split_whitespace()
        .next()
        .unwrap_or("")
        .to_ascii_lowercase();
    assert!(
        hash.len() == 64 && hash.bytes().all(|b| b.is_ascii_hexdigit()),
        "not a SHA-256: {printed}"
    );
    hash
}

/// What a `nova` that cannot start on this system looks like to the
/// scripts: neither Windows nor a Unix kernel can run these bytes, and a
/// Unix shell refuses them as a binary ("Exec format error").
const NOT_A_PROGRAM: &[u8] = b"\x7fELF\x02\x01\x01\0\0\0\0\0\0\0\0\0 not a nova\n";

/// Pack release `version`'s archive for `target` in `dir` as release.yml
/// does: one directory, `nova-<version>-<target>`, holding `binary` as
/// `nova` (or `nova.exe`), `README.md` and both licences; `tar -czf` on
/// Unix and `Compress-Archive` on Windows. Returns the archive's path. The
/// packed directory is removed, as each copy of a debug `nova` is large.
fn pack(dir: &Path, version: &str, target: &str, binary: &Path) -> PathBuf {
    let name = format!("nova-{version}-{target}");
    let stage = dir.join(format!("stage-{version}"));
    let inner = stage.join(&name);
    std::fs::create_dir_all(&inner).expect("create the archive's directory");
    for file in ["README.md", "LICENSE-MIT", "LICENSE-APACHE"] {
        std::fs::copy(repo().join(file), inner.join(file)).expect("copy a release file");
    }
    std::fs::copy(binary, inner.join(format!("nova{EXE_SUFFIX}"))).expect("copy nova");
    let archive = archive_name(version, target);
    if cfg!(windows) {
        run_ok(
            windows_powershell()
                .args(["-NoProfile", "-NonInteractive", "-Command"])
                .arg("Compress-Archive -LiteralPath $env:PACK_SOURCE -DestinationPath $env:PACK_ARCHIVE")
                .env("PACK_SOURCE", &inner)
                .env("PACK_ARCHIVE", stage.join(&archive)),
        );
    } else {
        run_ok(
            Command::new("tar")
                .arg("-czf")
                .arg(&archive)
                .arg(&name)
                .current_dir(&stage),
        );
    }
    std::fs::remove_dir_all(&inner).expect("remove the packed directory");
    stage.join(archive)
}

/// What a fake release's `SHA256SUMS` says of its archive.
enum Sums {
    /// The archive's own SHA-256.
    Right,
    /// Another SHA-256.
    Wrong,
    /// Nothing: the archive has no line.
    Missing,
}

/// Release `version`'s files for `target`, each by its path under
/// `/releases/download/`: the archive, around this test's own `nova`, and
/// a `SHA256SUMS` that also lists another asset, as a real release's does.
fn release(dir: &Path, version: &str, target: &str, sums: Sums) -> HashMap<String, Vec<u8>> {
    release_of(dir, version, target, sums, &nova())
}

/// `release`, with `binary` as the archive's `nova`.
fn release_of(
    dir: &Path,
    version: &str,
    target: &str,
    sums: Sums,
    binary: &Path,
) -> HashMap<String, Vec<u8>> {
    let archive = pack(dir, version, target, binary);
    let name = archive.file_name().unwrap().to_str().unwrap().to_string();
    let hash = sha256(&archive);
    let other = format!(
        "{}  nova-vscode-{version}.vsix\n",
        "0123456789abcdef".repeat(4)
    );
    let text = match sums {
        Sums::Right => format!("{hash}  {name}\n{other}"),
        Sums::Wrong => {
            let wrong = if hash.starts_with("ab") { "cd" } else { "ab" }.repeat(32);
            format!("{wrong}  {name}\n{other}")
        }
        Sums::Missing => other,
    };
    let bytes = std::fs::read(&archive).expect("read the archive");
    HashMap::from([
        (format!("v{version}/{name}"), bytes),
        (format!("v{version}/SHA256SUMS"), text.into_bytes()),
    ])
}

/// A loopback stand-in for `github.com/Sakeerin/nova/releases`: `latest`
/// redirects to `tag/v<LATEST>`, which answers with a page, and
/// `download/<path>` answers with `files`' entry; anything else is a 404.
fn serve(files: HashMap<String, Vec<u8>>) -> Server {
    let url = Arc::new(Mutex::new(String::new()));
    let base = Arc::clone(&url);
    let server = Server::start(move |request| {
        let path = request.path.as_str();
        if path == "/releases/latest" {
            let base = base.lock().unwrap().clone();
            return Response::redirect(&format!("{base}/releases/tag/v{LATEST}"));
        }
        if path == format!("/releases/tag/v{LATEST}") {
            return Response::ok(format!("<html><title>Nova {LATEST}</title></html>"));
        }
        match path
            .strip_prefix("/releases/download/")
            .and_then(|file| files.get(file))
        {
            Some(bytes) => Response::ok(bytes.clone()),
            None => Response::status(404),
        }
    });
    *url.lock().unwrap() = server.url.clone();
    server
}

/// The paths the server was asked for, in order.
fn paths(server: &Server) -> Vec<String> {
    server.requests().into_iter().map(|r| r.path).collect()
}

/// The host's install script, run in `dir` against `server`, with
/// `NOVA_HOME` in `dir/nova-home`, on Unix `HOME` in `dir/home`, no
/// `NOVA_VERSION` and no proxy. On Windows, `NOVA_INSTALL_NO_PATH=1`.
fn script(dir: &Path, server: &Server) -> Command {
    let mut command = if cfg!(windows) {
        let mut command = windows_powershell();
        command
            .args([
                "-NoProfile",
                "-NonInteractive",
                "-ExecutionPolicy",
                "Bypass",
                "-File",
            ])
            .arg(repo().join("tools").join("install").join("install.ps1"))
            .env("NOVA_INSTALL_NO_PATH", "1");
        command
    } else {
        let home = dir.join("home");
        std::fs::create_dir_all(&home).expect("create HOME");
        let mut command = Command::new("sh");
        command
            .arg(repo().join("tools").join("install").join("install.sh"))
            .env("HOME", home);
        command
    };
    command
        .current_dir(dir)
        .env("NOVA_INSTALL_BASE", format!("{}/releases", server.url))
        .env("NOVA_HOME", dir.join("nova-home"))
        .env_remove("NOVA_VERSION");
    for proxy in [
        "http_proxy",
        "HTTP_PROXY",
        "https_proxy",
        "HTTPS_PROXY",
        "all_proxy",
        "ALL_PROXY",
    ] {
        command.env_remove(proxy);
    }
    command
}

fn run(command: &mut Command) -> Output {
    command.output().expect("run the install script")
}

/// `dir/nova-home/bin`, where the scripts install.
fn bin(dir: &Path) -> PathBuf {
    dir.join("nova-home").join("bin")
}

fn entries(dir: &Path) -> Vec<String> {
    let mut names: Vec<String> = std::fs::read_dir(dir)
        .unwrap_or_else(|e| panic!("{}: {e}", dir.display()))
        .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
        .collect();
    names.sort();
    names
}

/// `bin` holds this test's `nova` and nothing else.
fn assert_installed(bin: &Path) {
    let exe = format!("nova{EXE_SUFFIX}");
    assert_eq!(entries(bin), [exe.as_str()], "{}", bin.display());
    assert!(
        std::fs::read(bin.join(&exe)).unwrap() == std::fs::read(nova()).unwrap(),
        "{} is not the release's nova",
        bin.join(&exe).display()
    );
}

/// `out` holds every line this test's `nova version` prints, in order.
fn assert_prints_version(out: &str) {
    let ours = run_ok(Command::new(nova()).arg("version"));
    let ours: Vec<&str> = ours.lines().collect();
    assert!(ours[0].starts_with("nova "), "{ours:?}");
    let printed: Vec<&str> = out.lines().collect();
    assert!(
        printed
            .windows(ours.len())
            .any(|lines| lines == ours.as_slice()),
        "the installed nova version is not in:\n{out}"
    );
}

/// The paths of release `version`'s two downloads.
fn downloads(version: &str, target: &str) -> [String; 2] {
    [
        format!(
            "/releases/download/v{version}/{}",
            archive_name(version, target)
        ),
        format!("/releases/download/v{version}/SHA256SUMS"),
    ]
}

#[test]
fn installs_the_latest_release_found_through_the_redirect() {
    let Some(target) = target_or_skip() else {
        return;
    };
    let dir = fresh("latest");
    let server = serve(release(&dir, LATEST, target, Sums::Right));

    let output = run(&mut script(&dir, &server));
    let (out, err) = (stdout(&output), stderr(&output));
    assert!(output.status.success(), "{out}\n{err}");
    assert_installed(&bin(&dir));
    assert_prints_version(&out);

    // install.sh's curl follows the redirect to the release's page;
    // install.ps1 only reads where it points.
    let mut expected = vec!["/releases/latest".to_string()];
    if !cfg!(windows) {
        expected.push(format!("/releases/tag/v{LATEST}"));
    }
    expected.extend(downloads(LATEST, target));
    assert_eq!(paths(&server), expected);

    // NOVA_HOME is not under HOME, so install.sh names the directory itself.
    if !cfg!(windows) {
        let line = format!(
            "nova: add nova to your PATH: export PATH=\"{}:$PATH\"",
            bin(&dir).display()
        );
        assert!(out.lines().any(|l| l == line), "no `{line}` in:\n{out}");
    }
}

#[test]
fn nova_version_fetches_that_version_and_never_asks_for_latest() {
    let Some(target) = target_or_skip() else {
        return;
    };
    let dir = fresh("chosen-version");
    let server = serve(release(&dir, OLDER, target, Sums::Right));

    let output = run(script(&dir, &server).env("NOVA_VERSION", OLDER));
    let (out, err) = (stdout(&output), stderr(&output));
    assert!(output.status.success(), "{out}\n{err}");
    assert_installed(&bin(&dir));
    assert_prints_version(&out);
    assert_eq!(paths(&server), downloads(OLDER, target));
}

#[test]
fn a_checksum_mismatch_installs_nothing() {
    let Some(target) = target_or_skip() else {
        return;
    };
    let dir = fresh("mismatch");
    let server = serve(release(&dir, LATEST, target, Sums::Wrong));
    // An older nova is installed already; a failed install leaves it.
    let exe = bin(&dir).join(format!("nova{EXE_SUFFIX}"));
    std::fs::create_dir_all(bin(&dir)).unwrap();
    std::fs::write(&exe, "an older nova").unwrap();

    let output = run(&mut script(&dir, &server));
    let (out, err) = (stdout(&output), stderr(&output));
    assert!(!output.status.success(), "{out}\n{err}");
    let archive = archive_name(LATEST, target);
    assert!(
        err.contains(&archive),
        "the error does not name {archive}:\n{err}"
    );
    assert_eq!(std::fs::read_to_string(&exe).unwrap(), "an older nova");
    assert_eq!(entries(&bin(&dir)), [format!("nova{EXE_SUFFIX}")]);
}

#[test]
fn an_archive_missing_from_sha256sums_installs_nothing() {
    let Some(target) = target_or_skip() else {
        return;
    };
    let dir = fresh("missing");
    let server = serve(release(&dir, LATEST, target, Sums::Missing));

    let output = run(&mut script(&dir, &server));
    let (out, err) = (stdout(&output), stderr(&output));
    assert!(!output.status.success(), "{out}\n{err}");
    let archive = archive_name(LATEST, target);
    assert!(
        err.contains(&archive),
        "the error does not name {archive}:\n{err}"
    );
    assert!(err.contains("SHA256SUMS"), "{err}");
    assert!(!dir.join("nova-home").exists(), "something was installed");
}

#[test]
fn running_it_again_replaces_the_binary() {
    let Some(target) = target_or_skip() else {
        return;
    };
    let dir = fresh("again");
    let server = serve(release(&dir, LATEST, target, Sums::Right));

    let first = run(&mut script(&dir, &server));
    assert!(
        first.status.success(),
        "{}\n{}",
        stdout(&first),
        stderr(&first)
    );
    assert_installed(&bin(&dir));
    // Stand in for an older nova; the second run must replace it.
    std::fs::write(bin(&dir).join(format!("nova{EXE_SUFFIX}")), "an older nova").unwrap();
    // On Windows, also for the nova.exe.old an earlier update leaves when
    // the nova it replaced was still running; the next run removes it.
    if cfg!(windows) {
        std::fs::write(bin(&dir).join("nova.exe.old"), "an even older nova").unwrap();
    }

    let second = run(&mut script(&dir, &server));
    let (out, err) = (stdout(&second), stderr(&second));
    assert!(second.status.success(), "{out}\n{err}");
    assert_installed(&bin(&dir));
    assert_prints_version(&out);
}

#[test]
fn a_nova_that_cannot_run_here_replaces_nothing() {
    let Some(target) = target_or_skip() else {
        return;
    };
    let dir = fresh("cannot-run");
    let broken = dir.join("not-a-program");
    std::fs::write(&broken, NOT_A_PROGRAM).unwrap();
    let server = serve(release_of(&dir, LATEST, target, Sums::Right, &broken));
    // A working nova is installed already, this test's own; the new one has
    // to run before it replaces anything.
    std::fs::create_dir_all(bin(&dir)).unwrap();
    std::fs::copy(nova(), bin(&dir).join(format!("nova{EXE_SUFFIX}"))).unwrap();

    let output = run(&mut script(&dir, &server));
    let (out, err) = (stdout(&output), stderr(&output));
    assert!(!output.status.success(), "{out}\n{err}");
    for said in ["nothing was replaced", "cargo install nova-cli --locked"] {
        assert!(err.contains(said), "no `{said}` in:\n{err}");
    }
    // The archive was downloaded and checked: what stopped the install is
    // that its nova does not run.
    let checked = format!(
        "nova: checked {} against SHA256SUMS",
        archive_name(LATEST, target)
    );
    assert!(
        out.lines().any(|l| l == checked),
        "no `{checked}` in:\n{out}"
    );
    assert!(paths(&server).ends_with(&downloads(LATEST, target)));
    // The old nova is there byte for byte, with nothing beside it.
    assert_installed(&bin(&dir));
}

#[cfg(unix)]
#[test]
fn install_sh_prints_the_path_line_only_when_the_directory_is_not_on_path() {
    let Some(target) = target_or_skip() else {
        return;
    };
    let dir = fresh("path");
    let server = serve(release(&dir, LATEST, target, Sums::Right));
    // NOVA_HOME is HOME's .nova, as by default, so the line shows $HOME.
    let nova_home = dir.join("home").join(".nova");
    let path = std::env::var("PATH").unwrap_or_default();
    let line = "nova: add nova to your PATH: export PATH=\"$HOME/.nova/bin:$PATH\"";

    let output = run(script(&dir, &server)
        .env("NOVA_HOME", &nova_home)
        .env("PATH", &path));
    let (out, err) = (stdout(&output), stderr(&output));
    assert!(output.status.success(), "{out}\n{err}");
    assert!(out.lines().any(|l| l == line), "no `{line}` in:\n{out}");

    let on_path = format!("{}:{path}", nova_home.join("bin").display());
    let output = run(script(&dir, &server)
        .env("NOVA_HOME", &nova_home)
        .env("PATH", on_path));
    let (out, err) = (stdout(&output), stderr(&output));
    assert!(output.status.success(), "{out}\n{err}");
    assert!(
        !out.contains("add nova to your PATH"),
        "a PATH line, though nova is on PATH:\n{out}"
    );
    assert_installed(&nova_home.join("bin"));
}

#[cfg(unix)]
#[test]
fn install_sh_on_an_unknown_system_names_cargo_install() {
    use std::os::unix::fs::PermissionsExt;

    let dir = fresh("unknown-system");
    let server = serve(HashMap::new());
    let fake = dir.join("fake-bin");
    std::fs::create_dir_all(&fake).unwrap();
    let uname = fake.join("uname");
    let path = format!(
        "{}:{}",
        fake.display(),
        std::env::var("PATH").unwrap_or_default()
    );

    for (os, arch) in [("FreeBSD", "amd64"), ("Linux", "aarch64")] {
        std::fs::write(
            &uname,
            format!("#!/bin/sh\ncase \"$1\" in\n  -m) echo {arch} ;;\n  *) echo {os} ;;\nesac\n"),
        )
        .unwrap();
        std::fs::set_permissions(&uname, std::fs::Permissions::from_mode(0o755)).unwrap();

        let output = run(script(&dir, &server).env("PATH", &path));
        let (out, err) = (stdout(&output), stderr(&output));
        assert!(!output.status.success(), "{out}\n{err}");
        let message = format!(
            "no ready-built nova for {os} {arch}; install it with: cargo install nova-cli --locked"
        );
        assert!(err.contains(&message), "no `{message}` in:\n{err}");
    }
    assert_eq!(paths(&server), Vec::<String>::new());
    assert!(!dir.join("nova-home").exists());
}

#[cfg(windows)]
#[test]
fn install_ps1_on_an_unknown_system_names_cargo_install() {
    let dir = fresh("unknown-system");
    let server = serve(HashMap::new());

    let output = run(script(&dir, &server)
        .env("PROCESSOR_ARCHITECTURE", "ARM64")
        .env_remove("PROCESSOR_ARCHITEW6432"));
    let (out, err) = (stdout(&output), stderr(&output));
    assert!(!output.status.success(), "{out}\n{err}");
    let message =
        "no ready-built nova for Windows_NT ARM64; install it with: cargo install nova-cli --locked";
    assert!(err.contains(message), "no `{message}` in:\n{err}");
    assert_eq!(paths(&server), Vec::<String>::new());
    assert!(!dir.join("nova-home").exists());
}

/// Windows PowerShell 5.1 reads a script that has no byte-order mark in
/// the system's code page, and `irm | iex` would choke on a mark, so both
/// scripts are plain ASCII; `install.sh` also has Unix line ends, for `sh`.
#[test]
fn the_scripts_are_plain_ascii() {
    for name in ["install.sh", "install.ps1"] {
        let path = repo().join("tools").join("install").join(name);
        let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
        if let Some(at) = bytes.iter().position(|b| !b.is_ascii()) {
            panic!("{name} has a byte that is not ASCII at offset {at}");
        }
    }
    let sh =
        std::fs::read_to_string(repo().join("tools").join("install").join("install.sh")).unwrap();
    assert!(
        sh.starts_with("#!/bin/sh\n"),
        "install.sh does not start with #!/bin/sh"
    );
    assert!(!sh.contains('\r'), "install.sh has a carriage return");
}