opi 0.13.3

Operations Interface — a project control center for your terminal
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
//! The process boundary, tested against the real binary.
//!
//! The unit tests cover what `opi` decides; these cover what actually crosses
//! into another process — the argv, the working directory, the exit code, and
//! what `opi` makes of stdout, stderr and a missing executable.
//!
//! Package managers are stand-ins: small `sh` scripts on a `PATH` that holds
//! nothing else, each recording how it was called and answering with output
//! trimmed from real runs. The boundary is real, the network is not — a test
//! that needs the registry is a test that fails on a train.

use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};

struct Fixture {
    root: tempfile::TempDir,
}

impl Fixture {
    fn new() -> Self {
        let root = tempfile::tempdir().expect("temp dir");
        fs::create_dir_all(root.path().join("bin")).expect("mkdir bin");
        fs::create_dir_all(root.path().join("log")).expect("mkdir log");
        fs::create_dir_all(root.path().join("project")).expect("mkdir project");
        Self { root }
    }

    fn project(&self) -> PathBuf {
        self.root.path().join("project")
    }

    /// Writes a file under the project.
    fn file(&self, path: &str, contents: &str) -> &Self {
        let full = self.project().join(path);
        fs::create_dir_all(full.parent().expect("parent")).expect("mkdir");
        fs::write(full, contents).expect("write");
        self
    }

    /// An executable at `path` under the project, recording its calls.
    fn tool(&self, path: &str, body: &str) -> &Self {
        let name = Path::new(path).file_name().expect("name").to_string_lossy();
        let full = self.project().join(path);
        fs::create_dir_all(full.parent().expect("parent")).expect("mkdir");
        write_script(&full, &name, body);
        self
    }

    /// A stand-in for `name` on `PATH`, recording its calls.
    fn shim(&self, name: &str, body: &str) -> &Self {
        write_script(&self.root.path().join("bin").join(name), name, body);
        self
    }

    /// How `name` was called: its working directory, then one line per
    /// argument. `None` if it never ran.
    fn calls(&self, name: &str) -> Option<Vec<String>> {
        let text = fs::read_to_string(self.root.path().join("log").join(name)).ok()?;
        Some(text.lines().map(str::to_owned).collect())
    }

    /// Runs `opi` in `dir` (relative to the project) with nothing on `PATH`
    /// but the stand-ins.
    fn opi(&self, dir: &str, args: &[&str]) -> Output {
        let dir = self.project().join(dir);
        fs::create_dir_all(&dir).expect("mkdir cwd");
        Command::new(env!("CARGO_BIN_EXE_opi"))
            .args(args)
            .current_dir(dir)
            .env_clear()
            .env("PATH", self.root.path().join("bin"))
            .env("HOME", self.root.path())
            .env("OPI_TEST_LOG", self.root.path().join("log"))
            .output()
            .expect("opi runs")
    }
}

fn write_script(path: &Path, name: &str, body: &str) {
    // Builtins only: `PATH` holds nothing but the stand-ins, so `cat` or `env`
    // would not be found.
    let script = format!(
        "#!/bin/sh\nprintf '%s\\n' \"$(pwd -P)\" \"$@\" > \"$OPI_TEST_LOG/{name}\"\n{body}\n"
    );
    fs::write(path, script).expect("write script");
    fs::set_permissions(path, fs::Permissions::from_mode(0o755)).expect("chmod");
}

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()
}

fn canonical(path: PathBuf) -> String {
    path.canonicalize()
        .expect("canonicalize")
        .to_string_lossy()
        .into_owned()
}

// --- Running a script ---

#[test]
fn a_script_runs_through_the_detected_manager_with_its_arguments() {
    let fixture = Fixture::new();
    fixture
        .file("package.json", r#"{"scripts":{"build":"x"}}"#)
        .file("package-lock.json", "{}")
        .shim("npm", "exit 0");

    let output = fixture.opi(".", &["build", "--verbose"]);
    assert!(output.status.success(), "{}", stderr(&output));

    let calls = fixture.calls("npm").expect("npm ran");
    assert_eq!(
        calls[1..],
        ["run", "build", "--", "--verbose"],
        "npm needs `--` before the script's own flags"
    );
}

#[test]
fn a_member_script_is_addressed_the_way_the_manager_expects() {
    let fixture = Fixture::new();
    fixture
        .file("package.json", r#"{"name":"root","workspaces":["apps/*"]}"#)
        .file("pnpm-lock.yaml", "")
        .file(
            "apps/blog/package.json",
            r#"{"name":"blog","scripts":{"dev":"x"}}"#,
        )
        .shim("pnpm", "exit 0");

    let output = fixture.opi(".", &["blog/dev"]);
    assert!(output.status.success(), "{}", stderr(&output));
    assert_eq!(
        fixture.calls("pnpm").expect("pnpm ran")[1..],
        ["--filter", "blog", "run", "dev"]
    );
}

#[test]
fn the_scripts_exit_code_and_output_are_its_own() {
    // `exec`, not supervision: what the shell sees is the script's status and
    // the script's stdout, untouched.
    let fixture = Fixture::new();
    fixture
        .file("package.json", r#"{"scripts":{"test":"x"}}"#)
        .file("pnpm-lock.yaml", "")
        .shim("pnpm", "echo 'from the script'\nexit 7");

    let output = fixture.opi(".", &["test"]);
    assert_eq!(output.status.code(), Some(7));
    assert_eq!(stdout(&output), "from the script\n");
}

#[test]
fn a_script_starts_where_opi_was_started() {
    // No directory is set: the package manager finds its own root by walking
    // up, as it would if typed by hand, and `cargo run` depends on this.
    let fixture = Fixture::new();
    fixture
        .file("package.json", r#"{"scripts":{"dev":"x"}}"#)
        .file("package-lock.json", "{}")
        .shim("npm", "exit 0");

    let output = fixture.opi("src/pages", &["dev"]);
    assert!(output.status.success(), "{}", stderr(&output));
    assert_eq!(
        fixture.calls("npm").expect("npm ran")[0],
        canonical(fixture.project().join("src/pages"))
    );
}

#[test]
fn a_missing_package_manager_is_named_rather_than_crashed_on() {
    let fixture = Fixture::new();
    fixture
        .file("package.json", r#"{"scripts":{"build":"x"}}"#)
        .file("pnpm-lock.yaml", "");

    let output = fixture.opi(".", &["build"]);
    assert_eq!(output.status.code(), Some(1));
    let said = stderr(&output);
    assert!(said.contains("Cannot run pnpm"), "{said}");
    assert!(said.contains("installed and on your PATH"), "{said}");
}

#[test]
fn a_cargo_task_covers_the_whole_workspace_from_inside_a_member() {
    // A root that is also a package: without --workspace, cargo would test
    // the root package alone.
    let fixture = Fixture::new();
    fixture
        .file(
            "Cargo.toml",
            "[workspace]\nmembers = [\"crates/*\"]\n\n[package]\nname = \"repo\"\n",
        )
        .file("crates/app/Cargo.toml", "[package]\nname = \"app\"\n")
        .shim("cargo", "exit 0");

    let output = fixture.opi("crates/app", &["cargo test"]);
    assert!(output.status.success(), "{}", stderr(&output));
    let calls = fixture.calls("cargo").expect("cargo ran");
    assert_eq!(calls[1..], ["test", "--all-features", "--workspace"]);
}

// --- Piped rather than read ---

#[test]
fn a_piped_list_is_plain_text() {
    let fixture = Fixture::new();
    fixture
        .file("package.json", r#"{"scripts":{"dev":"x","build":"y"}}"#)
        .file("package-lock.json", "{}");

    let output = fixture.opi(".", &[]);
    assert!(output.status.success(), "{}", stderr(&output));
    let printed = stdout(&output);
    assert!(
        printed.contains("dev") && printed.contains("build"),
        "{printed}"
    );
    assert!(!printed.contains('\u{1b}'), "no escape codes into a pipe");
}

// --- Health ---

#[test]
fn a_members_tool_runs_in_the_member_even_without_scripts() {
    // A library with no scripts still has something to lint, and its config
    // lives beside its sources, not at the root.
    let fixture = Fixture::new();
    fixture
        .file(
            "package.json",
            r#"{"name":"root","workspaces":["packages/*"]}"#,
        )
        .file("package-lock.json", "{}")
        .file(
            "packages/lib/package.json",
            r#"{"name":"lib","devDependencies":{"eslint":"9.0.0"}}"#,
        )
        .tool("node_modules/.bin/eslint", "echo '1 problem'\nexit 1");

    let output = fixture.opi(".", &["--health"]);
    assert_eq!(output.status.code(), Some(1));
    let printed = stdout(&output);
    assert!(printed.contains("Lint (lib)"), "{printed}");
    assert!(printed.contains("1 problem"), "{printed}");
    assert_eq!(
        fixture.calls("eslint").expect("eslint ran")[0],
        canonical(fixture.project().join("packages/lib"))
    );
}

#[test]
fn a_yarn_pnp_project_is_checked_through_yarn() {
    let fixture = Fixture::new();
    fixture
        .file(
            "package.json",
            r#"{"name":"pnp","devDependencies":{"eslint":"9.0.0"}}"#,
        )
        .file("yarn.lock", "")
        .shim("yarn", "exit 0");

    let output = fixture.opi(".", &["--health"]);
    assert!(output.status.success(), "{}", stdout(&output));
    assert_eq!(
        fixture.calls("yarn").expect("yarn ran")[1..],
        ["run", "eslint", "."]
    );
}

#[test]
fn a_lockfile_out_of_step_with_its_manifest_fails_health() {
    let fixture = Fixture::new();
    fixture
        .file("package.json", r#"{"name":"app","dependencies":{"ms":"2.1.3"}}"#)
        .file("pnpm-lock.yaml", "")
        .shim(
            "pnpm",
            "echo ' ERR_PNPM_OUTDATED_LOCKFILE  Cannot install with \"frozen-lockfile\" because pnpm-lock.yaml is not up to date with package.json' >&2\nexit 1",
        );

    let output = fixture.opi(".", &["--health"]);
    let printed = stdout(&output);
    assert_eq!(output.status.code(), Some(1), "{printed}");
    assert!(printed.contains("Lockfile"), "{printed}");
    assert!(printed.contains("ERR_PNPM_OUTDATED_LOCKFILE"), "{printed}");
    assert_eq!(
        fixture.calls("pnpm").expect("pnpm ran")[1..],
        [
            "install",
            "--frozen-lockfile",
            "--lockfile-only",
            "--ignore-scripts",
            "--offline"
        ]
    );
}

#[test]
fn the_commit_workflow_asks_about_the_lockfile() {
    // A dependency added to package.json and never locked is exactly what a
    // commit should not carry, and the check is offline and fast enough to
    // sit there.
    let fixture = Fixture::new();
    fixture
        .file("package.json", r#"{"name":"app"}"#)
        .file("package-lock.json", "{}")
        .shim("npm", "exit 0");

    let output = fixture.opi(".", &["--check", "commit"]);
    let printed = stdout(&output);
    assert!(output.status.success(), "{printed}");
    assert!(printed.contains("Lockfile"), "{printed}");
    assert_eq!(
        fixture.calls("npm").expect("npm ran")[1..],
        ["ci", "--dry-run", "--ignore-scripts"]
    );
}

// --- Security ---

#[test]
fn a_saved_push_selection_skips_unselected_checks_and_builds() {
    let fixture = Fixture::new();
    fixture
        .file(
            "package.json",
            r#"{"name":"app","scripts":{"build":"build"},"devDependencies":{"eslint":"9"}}"#,
        )
        .file(
            ".opi/checks.json",
            r#"{"workflows":{"push":{"checks":["Secrets"],"build":false}}}"#,
        )
        .tool("node_modules/.bin/eslint", "exit 1")
        .shim("npm", "exit 1");
    let output = fixture.opi(".", &["--check", "push"]);
    assert!(output.status.success(), "{}", stdout(&output));
    assert!(stdout(&output).contains("Secrets"));
    assert!(fixture.calls("eslint").is_none());
    assert!(fixture.calls("npm").is_none());
}

#[test]
fn an_invalid_or_unavailable_selection_fails_before_running_checks() {
    let fixture = Fixture::new();
    fixture
        .file(
            "package.json",
            r#"{"name":"app","devDependencies":{"eslint":"9"}}"#,
        )
        .tool("node_modules/.bin/eslint", "exit 0");
    for contents in [
        r#"{"workflows":{"push":{"checks":["Typo"],"build":false}}}"#,
        r#"{"workflows":{"push":{"checks":["TypeScript"],"build":false}}}"#,
    ] {
        fixture.file(".opi/checks.json", contents);
        let output = fixture.opi(".", &["--check", "push"]);
        assert_eq!(output.status.code(), Some(1), "{}", stdout(&output));
        assert!(fixture.calls("eslint").is_none());
    }
}

#[test]
fn a_selected_build_without_a_build_script_is_reported_as_unavailable() {
    let fixture = Fixture::new();
    fixture
        .file(
            "package.json",
            r#"{"name":"app","devDependencies":{"eslint":"9"}}"#,
        )
        .file(
            ".opi/checks.json",
            r#"{"workflows":{"deploy":{"checks":["Lint", "TypeScript"],"build":true}}}"#,
        )
        .tool("node_modules/.bin/eslint", "exit 0");
    let output = fixture.opi(".", &["--check", "deploy"]);
    assert_eq!(output.status.code(), Some(1), "{}", stdout(&output));
    assert!(
        stderr(&output).contains("TypeScript, Build"),
        "{}",
        stderr(&output)
    );
    assert!(fixture.calls("eslint").is_none());
}

#[test]
fn deploy_checks_build_but_never_run_the_deploy_script() {
    let fixture = Fixture::new();
    fixture
        .file(
            "package.json",
            r#"{"name":"app","scripts":{"build":"build","deploy":"publish"}}"#,
        )
        .shim("npm", "exit 0");
    let output = fixture.opi(".", &["--check", "deploy"]);
    assert!(output.status.success(), "{}", stdout(&output));
    assert_eq!(fixture.calls("npm").unwrap()[1..], ["run", "build"]);
    assert!(stdout(&output).contains("Ready to deploy"));
}

#[test]
fn choosing_checks_without_a_terminal_never_writes_configuration() {
    let fixture = Fixture::new();
    fixture.file("package.json", r#"{"name":"app"}"#);
    let output = fixture.opi(".", &["--checks", "push"]);
    assert_eq!(output.status.code(), Some(1));
    assert!(stderr(&output).contains("needs a terminal"));
    assert!(!fixture.project().join(".opi").exists());
}

#[test]
fn bundled_secrets_need_no_installed_scanner_or_git() {
    let fixture = Fixture::new();
    fixture.file("package.json", r#"{"name":"app"}"#).file(
        "key.pem",
        &["-----BEGIN RSA ", "PRIVATE KEY-----\nexample\n"].concat(),
    );
    let output = fixture.opi(".", &["--health"]);
    let printed = stdout(&output);
    assert_eq!(output.status.code(), Some(1), "{printed}");
    assert!(printed.contains("nosecrets"), "{printed}");
    assert!(printed.contains("key.pem:1:"), "{printed}");
    assert!(!printed.contains("-----BEGIN"), "{printed}");
}

#[test]
fn commit_wiring_checks_the_index_instead_of_an_unstaged_fix() {
    let fixture = Fixture::new();
    fixture.file("package.json", r#"{"name":"app"}"#).file(
        "key.pem",
        &["-----BEGIN RSA ", "PRIVATE KEY-----\nexample\n"].concat(),
    );
    let git = std::env::split_paths(&std::env::var_os("PATH").unwrap())
        .map(|dir| dir.join("git"))
        .find(|path| path.is_file())
        .unwrap();
    std::os::unix::fs::symlink(git, fixture.root.path().join("bin/git")).unwrap();
    for args in [vec!["init", "-q"], vec!["add", "."]] {
        assert!(
            Command::new("git")
                .current_dir(fixture.project())
                .args(args)
                .output()
                .unwrap()
                .status
                .success()
        );
    }
    fixture.file("key.pem", "clean\n");
    let output = fixture.opi(".", &["--check", "commit"]);
    let printed = stdout(&output);
    assert_eq!(output.status.code(), Some(1), "{printed}");
    assert!(printed.contains("key.pem:1:"), "{printed}");
    assert!(printed.contains("Staged files"), "{printed}");

    // A saved selection applies to the commit-only checks as well.
    fixture.file(
        ".opi/checks.json",
        r#"{"workflows":{"commit":{"checks":["Secrets"],"build":false}}}"#,
    );
    let output = fixture.opi(".", &["--check", "commit"]);
    let printed = stdout(&output);
    assert!(printed.contains("key.pem:1:"), "{printed}");
    assert!(!printed.contains("Staged files"), "{printed}");
}

#[test]
fn a_failed_audit_is_not_reported_as_clean() {
    // The false acquittal: no report on stdout, the reason on stderr. Read as
    // "no findings", this said "Nothing to act on." and exited 0.
    let fixture = Fixture::new();
    fixture
        .file("package.json", r#"{"name":"app"}"#)
        .file("package-lock.json", "{}")
        .shim(
            "npm",
            "echo 'npm error code ENOTFOUND registry.npmjs.org' >&2\nexit 1",
        );

    let output = fixture.opi(".", &["--security"]);
    let printed = stdout(&output);
    assert_ne!(output.status.code(), Some(0), "{printed}");
    assert!(printed.contains("ENOTFOUND"), "{printed}");
    assert!(!printed.contains("no known vulnerabilities"), "{printed}");
    assert!(!printed.contains("Nothing to act on"), "{printed}");
}

#[test]
fn a_clean_yarn_audit_prints_nothing_and_is_clean() {
    let fixture = Fixture::new();
    fixture
        .file("package.json", r#"{"name":"app"}"#)
        .file("yarn.lock", "")
        .shim("yarn", "exit 0");

    let output = fixture.opi(".", &["--security"]);
    let printed = stdout(&output);
    assert!(output.status.success(), "{printed}");
    assert!(printed.contains("no known vulnerabilities"), "{printed}");
    assert_eq!(
        fixture.calls("yarn").expect("yarn ran")[1..],
        ["npm", "audit", "--all", "--recursive", "--json"]
    );
}

#[test]
fn a_yarn_advisory_is_reported_and_fails_the_run() {
    let fixture = Fixture::new();
    fixture
        .file("package.json", r#"{"name":"app"}"#)
        .file("yarn.lock", "")
        .shim(
            "yarn",
            r#"printf '%s\n' '{"value":"lodash","children":{"ID":1106913,"Severity":"high","Vulnerable Versions":"<4.17.21","Dependents":["app@workspace:."]}}'
exit 1"#,
        );

    let output = fixture.opi(".", &["--security"]);
    let printed = stdout(&output);
    assert_eq!(output.status.code(), Some(1), "{printed}");
    assert!(printed.contains("lodash"), "{printed}");
}

// --- Updates ---

#[test]
fn a_failed_outdated_is_not_everything_is_current() {
    let fixture = Fixture::new();
    fixture
        .file("package.json", r#"{"name":"app"}"#)
        .file("package-lock.json", "{}")
        .shim("npm", "echo 'npm error network request failed' >&2\nexit 1");

    let output = fixture.opi(".", &["--updates"]);
    let printed = stdout(&output);
    assert_eq!(output.status.code(), Some(1), "{printed}");
    assert!(printed.contains("network request failed"), "{printed}");
    assert!(!printed.contains("everything is current"), "{printed}");
}

#[test]
fn a_silent_outdated_is_everything_is_current() {
    // npm prints nothing at all when nothing is outdated — measured — so
    // silence on both streams is the clean case, not a failure.
    let fixture = Fixture::new();
    fixture
        .file("package.json", r#"{"name":"app"}"#)
        .file("package-lock.json", "{}")
        .shim("npm", "exit 0");

    let output = fixture.opi(".", &["--updates"]);
    let printed = stdout(&output);
    assert!(output.status.success(), "{printed}");
    assert!(printed.contains("everything is current"), "{printed}");
}

#[test]
fn bun_is_never_asked_to_update_without_a_terminal() {
    // The handover to `bun update --interactive` is an offer; a pipe gets the
    // offer's absence explained, and bun is not started at all.
    let fixture = Fixture::new();
    fixture
        .file("package.json", r#"{"name":"app"}"#)
        .file("bun.lock", "")
        .shim("bun", "exit 0");

    let output = fixture.opi(".", &["--updates"]);
    let printed = stdout(&output);
    assert!(output.status.success(), "{printed}");
    assert!(printed.contains("in a terminal"), "{printed}");
    assert!(
        fixture.calls("bun").is_none(),
        "bun update ran without asking"
    );
}