spectra-cli 0.5.0

OpenSpectra command-line interface.
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
mod common;

use std::path::Path;
use std::process::{Command, Output};

use common::{spectra, TempDir};

fn isolated_spectra(root: &Path) -> Command {
    let mut command = spectra();
    command
        .current_dir(root)
        .env("HOME", root.join("home"))
        .env("XDG_DATA_HOME", root.join("xdg-data"))
        .env("XDG_CONFIG_HOME", root.join("xdg-config"))
        .env("ZDOTDIR", root.join("zdotdir"));
    command
}

fn combined_output(output: &Output) -> String {
    format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    )
}

#[test]
fn generate_supports_all_five_shells() {
    let root = TempDir::new("completion-generate");

    for shell in ["bash", "zsh", "fish", "elvish", "powershell"] {
        let output = spectra()
            .args(["completion", "generate", shell])
            .current_dir(&*root)
            .output()
            .unwrap();

        assert!(
            output.status.success(),
            "{shell} generate failed: {output:?}"
        );
        assert!(!output.stdout.is_empty(), "{shell} output was empty");
        assert!(
            String::from_utf8_lossy(&output.stdout).contains("spectra"),
            "{shell} output did not mention spectra: {output:?}"
        );
    }
}

/// A marker unique to each shell's generated script. `contains("spectra")`
/// is true of all five, so it cannot tell them apart -- installing bash's
/// script into the zsh and fish locations passed every content assertion
/// until these markers landed.
fn shell_marker(shell: &str) -> &'static str {
    match shell {
        "bash" => "complete -F _spectra",
        "zsh" => "#compdef spectra",
        "fish" => "complete -c spectra",
        other => panic!("no marker registered for {other}"),
    }
}

#[test]
fn install_bash_writes_completion_to_xdg_data_home() {
    let root = TempDir::new("completion-install-bash");
    let output = isolated_spectra(&root)
        .args(["completion", "install", "bash", "--verbose"])
        .output()
        .unwrap();

    assert!(output.status.success(), "bash install failed: {output:?}");
    let path = root.join("xdg-data/bash-completion/completions/spectra");
    assert!(
        path.is_file(),
        "completion file missing at {}",
        path.display()
    );
    let script = std::fs::read_to_string(&path).unwrap();
    assert!(
        script.contains(shell_marker("bash")),
        "installed script is not a bash script: {script:.200}"
    );

    // --verbose is advertised in README; without this it can be deleted and
    // become a silent no-op with the suite green. The byte count must match
    // the file actually on disk, not just be present.
    let bytes = std::fs::metadata(&path).unwrap().len();
    assert!(
        combined_output(&output).contains(&format!("Bytes written: {bytes}")),
        "--verbose must report the real byte count ({bytes}): {output:?}"
    );
}

#[test]
fn installing_bash_twice_overwrites_rather_than_appends() {
    let root = TempDir::new("completion-install-twice");
    let path = root.join("xdg-data/bash-completion/completions/spectra");

    let mut after_each = Vec::new();
    for attempt in 1..=2 {
        let output = isolated_spectra(&root)
            .args(["completion", "install", "bash"])
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "bash install attempt {attempt} failed: {output:?}"
        );
        after_each.push(std::fs::read(&path).unwrap());
    }

    // Exit 0 twice is also what an *appending* write looks like, and that
    // would leave a doubled `_spectra()` definition that bash re-sources.
    assert!(!after_each[0].is_empty(), "first install wrote nothing");
    assert_eq!(
        after_each[0],
        after_each[1],
        "reinstall must overwrite, not grow the file ({} -> {} bytes)",
        after_each[0].len(),
        after_each[1].len()
    );
}

#[test]
fn install_never_follows_a_symlink_into_an_rc_file() {
    // The strongest promise this command makes is that it never touches rc
    // files. `std::fs::write` follows a symlink at the target path and
    // truncates whatever it points at, so a completion path symlinked to
    // ~/.bashrc silently replaced the user's config with a completion
    // script -- and reported success.
    let root = TempDir::new("completion-symlink");
    let home = root.join("home");
    let completions = root.join("xdg-data/bash-completion/completions");
    std::fs::create_dir_all(&completions).unwrap();
    std::fs::create_dir_all(&home).unwrap();

    let rc = home.join(".bashrc");
    let rc_contents = "# precious user config\nexport FOO=bar\n";
    std::fs::write(&rc, rc_contents).unwrap();

    let link = completions.join("spectra");
    #[cfg(unix)]
    std::os::unix::fs::symlink(&rc, &link).unwrap();
    #[cfg(windows)]
    std::os::windows::fs::symlink_file(&rc, &link).unwrap();

    let output = isolated_spectra(&root)
        .args(["completion", "install", "bash"])
        .output()
        .unwrap();
    assert!(output.status.success(), "bash install failed: {output:?}");

    assert_eq!(
        std::fs::read_to_string(&rc).unwrap(),
        rc_contents,
        "install must not write through a symlink into an rc file"
    );
    assert!(
        std::fs::read_to_string(&link)
            .unwrap()
            .contains(shell_marker("bash")),
        "the completion path itself must now hold the completion script"
    );
    let entries: Vec<String> = std::fs::read_dir(&completions)
        .unwrap()
        .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
        .collect();
    assert_eq!(
        entries,
        vec!["spectra".to_string()],
        "no temp file may be left behind: {entries:?}"
    );
}

#[test]
fn empty_xdg_data_home_falls_back_to_home_not_the_current_directory() {
    // An exported-but-empty variable means "unset" per the XDG spec. Treating
    // it as a path makes it relative, so install wrote into whatever
    // directory the user was standing in and printed that as if correct.
    let root = TempDir::new("completion-empty-xdg");
    let home = root.join("home");
    let cwd = root.join("elsewhere");
    std::fs::create_dir_all(&home).unwrap();
    std::fs::create_dir_all(&cwd).unwrap();

    let output = spectra()
        .args(["completion", "install", "bash"])
        .current_dir(&cwd)
        .env("HOME", &home)
        .env("XDG_DATA_HOME", "")
        .output()
        .unwrap();
    assert!(output.status.success(), "bash install failed: {output:?}");

    assert!(
        !cwd.join("bash-completion").exists(),
        "empty XDG_DATA_HOME must not resolve relative to the cwd"
    );
    assert!(
        home.join(".local/share/bash-completion/completions/spectra")
            .is_file(),
        "empty XDG_DATA_HOME must take the $HOME fallback: {output:?}"
    );
}

#[test]
fn empty_home_is_an_error_not_a_relative_path() {
    let root = TempDir::new("completion-empty-home");
    let cwd = root.join("elsewhere");
    std::fs::create_dir_all(&cwd).unwrap();

    let output = spectra()
        .args(["completion", "install", "zsh"])
        .current_dir(&cwd)
        .env("HOME", "")
        .env("ZDOTDIR", "")
        .output()
        .unwrap();

    assert_eq!(
        output.status.code(),
        Some(1),
        "empty HOME must fail loudly, not write to the cwd: {output:?}"
    );
    assert!(
        !cwd.join(".zfunc").exists(),
        "nothing may be written when HOME is unusable"
    );
}

#[test]
fn uninstall_bash_with_yes_removes_completion() {
    let root = TempDir::new("completion-uninstall-bash");
    let install = isolated_spectra(&root)
        .args(["completion", "install", "bash"])
        .output()
        .unwrap();
    assert!(install.status.success(), "bash install failed: {install:?}");

    let path = root.join("xdg-data/bash-completion/completions/spectra");
    assert!(path.is_file());

    let uninstall = isolated_spectra(&root)
        .args(["completion", "uninstall", "bash", "-y"])
        .output()
        .unwrap();
    assert!(
        uninstall.status.success(),
        "bash uninstall failed: {uninstall:?}"
    );
    assert!(!path.exists(), "completion file was not removed");
}

#[test]
fn uninstalling_missing_completion_succeeds() {
    let root = TempDir::new("completion-uninstall-missing");
    let output = isolated_spectra(&root)
        .args(["completion", "uninstall", "bash", "-y"])
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "missing uninstall failed: {output:?}"
    );
    assert!(
        combined_output(&output)
            .to_ascii_lowercase()
            .contains("not installed"),
        "missing uninstall output was not actionable: {output:?}"
    );
}

#[test]
fn generate_rejects_unknown_shell_with_clap_exit_code() {
    let root = TempDir::new("completion-invalid-shell");
    let output = spectra()
        .args(["completion", "generate", "bogus-shell"])
        .current_dir(&*root)
        .output()
        .unwrap();

    assert_eq!(
        output.status.code(),
        Some(2),
        "unexpected output: {output:?}"
    );
    assert!(
        String::from_utf8_lossy(&output.stderr).contains("invalid value"),
        "expected clap invalid-value error: {output:?}"
    );
}

#[test]
fn zsh_and_fish_install_to_their_native_autoload_directories() {
    let root = TempDir::new("completion-install-zsh-fish");

    let zsh = isolated_spectra(&root)
        .args(["completion", "install", "zsh"])
        .output()
        .unwrap();
    assert!(zsh.status.success(), "zsh install failed: {zsh:?}");
    let zsh_script = root.join("zdotdir/.zfunc/_spectra");
    assert!(zsh_script.is_file());
    assert!(
        std::fs::read_to_string(&zsh_script)
            .unwrap()
            .contains(shell_marker("zsh")),
        "zsh location must hold the zsh script, not another shell's"
    );
    // The path honours ZDOTDIR, so the hint must name that directory -- a
    // hardcoded ~/.zfunc sends ZDOTDIR users to a directory the script is
    // not in, leaving completion silently non-functional. Assert the exact
    // `fpath+=(...)` the user is told to paste: matching the bare directory
    // anywhere in the output is satisfied by the "Installed ... to <path>"
    // line printed just above, so a hardcoded hint would slip through.
    assert!(
        combined_output(&zsh).contains(&format!(
            "fpath+=('{}')",
            root.join("zdotdir/.zfunc").display()
        )),
        "zsh hint must tell the user to add the directory actually written to, \
         single-quoted so a path with spaces does not word-split: {zsh:?}"
    );

    let fish = isolated_spectra(&root)
        .args(["completion", "install", "fish"])
        .output()
        .unwrap();
    assert!(fish.status.success(), "fish install failed: {fish:?}");
    let fish_script = root.join("xdg-config/fish/completions/spectra.fish");
    assert!(fish_script.is_file());
    assert!(
        std::fs::read_to_string(&fish_script)
            .unwrap()
            .contains(shell_marker("fish")),
        "fish location must hold the fish script, not another shell's"
    );
}

#[test]
fn install_and_uninstall_never_modify_an_existing_rc_file() {
    // Asserting an rc file does not *exist* in a fresh temp dir proves
    // nothing -- it is satisfied by the fixture, not by the code. The real
    // failure mode is appending to an rc file that is already there, so the
    // rc files must exist first and be compared byte-for-byte afterwards.
    let root = TempDir::new("completion-rc-immutable");
    let rc_files = [
        ("home/.bashrc", "# bashrc sentinel\n"),
        ("home/.bash_profile", "# bash_profile sentinel\n"),
        ("zdotdir/.zshrc", "# zshrc sentinel\n"),
        ("xdg-config/fish/config.fish", "# fish config sentinel\n"),
    ];
    for (rel, contents) in rc_files {
        let path = root.join(rel);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, contents).unwrap();
    }

    for shell in ["bash", "zsh", "fish"] {
        for op in ["install", "uninstall"] {
            let mut command = isolated_spectra(&root);
            command.args(["completion", op, shell]);
            if op == "uninstall" {
                command.arg("-y");
            }
            let output = command.output().unwrap();
            assert!(output.status.success(), "{op} {shell} failed: {output:?}");
        }
    }

    for (rel, contents) in rc_files {
        assert_eq!(
            std::fs::read_to_string(root.join(rel)).unwrap(),
            contents,
            "{rel} was modified; this command must never touch rc files"
        );
    }
}

#[test]
fn generate_detects_the_shell_from_the_environment() {
    let root = TempDir::new("completion-detect-shell");

    // More than one shell on purpose: with a single sample, a detection that
    // ignores $SHELL and always returns that one shell passes -- and a bash
    // user would silently get the zsh script.
    for (shell_env, expected) in [
        ("/bin/bash", "bash"),
        ("/bin/zsh", "zsh"),
        ("/usr/local/bin/fish", "fish"),
    ] {
        let output = isolated_spectra(&root)
            .args(["completion", "generate"])
            .env("SHELL", shell_env)
            .output()
            .unwrap();

        assert!(
            output.status.success(),
            "auto-detection failed for {shell_env}: {output:?}"
        );
        assert!(
            String::from_utf8_lossy(&output.stdout).contains(shell_marker(expected)),
            "$SHELL={shell_env} must produce a {expected} script: {output:?}"
        );
    }
}

#[test]
fn generate_without_a_detectable_shell_exits_one() {
    let root = TempDir::new("completion-detect-fail");
    let output = isolated_spectra(&root)
        .args(["completion", "generate"])
        .env_remove("SHELL")
        .output()
        .unwrap();

    // Exit 1, not a silent default: falling back to bash would write the
    // wrong shell's completions into an unsuspecting user's home.
    assert_eq!(
        output.status.code(),
        Some(1),
        "undetectable shell must exit 1: {output:?}"
    );
    assert!(
        combined_output(&output).contains("could not detect shell"),
        "error must say detection failed: {output:?}"
    );
}

#[test]
fn install_and_uninstall_reject_unsupported_shells_with_generate_guidance() {
    let root = TempDir::new("completion-unsupported");

    for shell in ["elvish", "powershell"] {
        for op in ["install", "uninstall"] {
            let output = isolated_spectra(&root)
                .args(["completion", op, shell])
                .output()
                .unwrap();

            assert_eq!(
                output.status.code(),
                Some(1),
                "{op} {shell} must exit 1: {output:?}"
            );
            let message = combined_output(&output);
            assert!(
                message.contains(&format!("spectra completion generate {shell}")),
                "{op} {shell} guidance missing: {output:?}"
            );
            // The uninstall path rewrites the verb; without this a deleted
            // rewrite tells users that *installing* is unsupported.
            //
            // Assert the exact phrase, not `contains(verb)`: "uninstalling"
            // contains "installing", so a `contains` check on the install
            // branch is satisfied by the uninstall message and has zero
            // discriminating power.
            let expected_verb = if op == "install" {
                "installing"
            } else {
                "uninstalling"
            };
            assert!(
                message.contains(&format!(
                    "{expected_verb} {shell} completion is not supported"
                )),
                "{op} {shell} message must open with '{expected_verb}': {output:?}"
            );
            if op == "install" {
                assert!(
                    !message.contains("uninstalling"),
                    "install must not claim uninstalling is unsupported: {output:?}"
                );
            }
        }
    }
}

#[test]
fn relative_xdg_data_home_falls_back_to_home_not_the_current_directory() {
    // The empty-value case is not the whole story: a non-empty *relative*
    // value joins the same way, so install wrote under the cwd and printed
    // that relative path as if correct. The XDG spec requires an absolute
    // path and says an invalid value takes the $HOME fallback.
    let root = TempDir::new("completion-relative-xdg");
    let home = root.join("home");
    let cwd = root.join("elsewhere");
    std::fs::create_dir_all(&home).unwrap();
    std::fs::create_dir_all(&cwd).unwrap();

    let output = spectra()
        .args(["completion", "install", "bash"])
        .current_dir(&cwd)
        .env("HOME", &home)
        .env("XDG_DATA_HOME", "relative-xdg")
        .env("XDG_CONFIG_HOME", root.join("xdg-config"))
        .env("ZDOTDIR", root.join("zdotdir"))
        .output()
        .unwrap();
    assert!(output.status.success(), "bash install failed: {output:?}");

    assert!(
        !cwd.join("relative-xdg").exists(),
        "a relative XDG_DATA_HOME must not resolve against the cwd: {output:?}"
    );
    assert!(
        home.join(".local/share/bash-completion/completions/spectra")
            .is_file(),
        "a relative XDG_DATA_HOME must take the $HOME fallback: {output:?}"
    );
}

#[test]
fn install_leaves_no_temp_file_when_the_rename_fails() {
    // A pre-existing *directory* at the completion path lets the temp write
    // succeed but makes the rename fail, exercising the cleanup-on-rename-
    // failure branch. Without the cleanup call, the leftover `_spectra.tmp-*`
    // would sit in the user's fpath directory still carrying `#compdef
    // spectra` on its first line. Mirrors spectra-core's
    // `write_atomically_cleans_up_the_temp_file_when_rename_fails`.
    let root = TempDir::new("completion-rename-fails");
    let completions = root.join("xdg-data/bash-completion/completions");
    std::fs::create_dir_all(completions.join("spectra")).unwrap();

    let output = isolated_spectra(&root)
        .args(["completion", "install", "bash"])
        .output()
        .unwrap();

    assert_eq!(
        output.status.code(),
        Some(1),
        "install onto a directory must fail loudly: {output:?}"
    );
    let entries: Vec<String> = std::fs::read_dir(&completions)
        .unwrap()
        .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
        .collect();
    assert_eq!(
        entries,
        vec!["spectra".to_string()],
        "a failed rename must leave no temp file behind: {entries:?}"
    );
}