cue-cli 0.2.0

Installed Cue command aggregator and extension dispatcher
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
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
use std::ffi::{OsStr, OsString};
use std::io;
use std::path::PathBuf;
use std::process::Command;

use anyhow::{Context, bail};

#[derive(Debug, Clone, PartialEq, Eq)]
enum ResolvedExtensionCommand {
    ConfiguredProgram(String),
    Path(PathBuf),
}

pub(crate) fn run(
    name: &str,
    args: &[OsString],
    supported_subcommands: &str,
) -> anyhow::Result<i32> {
    run_with(
        name,
        args,
        supported_subcommands,
        crate::config::Config::load_for_extension_dispatch,
        first_party_extension_binary,
        crate::path_lookup::find_executable_on_path,
        exec_resolved_extension_command,
    )
}

fn run_with<L, F, G, E>(
    name: &str,
    args: &[OsString],
    supported_subcommands: &str,
    mut load_config: L,
    mut find_first_party_binary: F,
    mut find_path_binary: G,
    mut exec_command: E,
) -> anyhow::Result<i32>
where
    L: FnMut() -> anyhow::Result<crate::config::Config>,
    F: FnMut(&str) -> anyhow::Result<Option<PathBuf>>,
    G: FnMut(&str) -> Option<PathBuf>,
    E: FnMut(ResolvedExtensionCommand, &[OsString]) -> anyhow::Result<i32>,
{
    if let Some(command) =
        resolve_first_party_extension_command(name, &mut find_first_party_binary)?
    {
        return exec_command(command, args);
    }

    if is_first_party_extension(name) {
        bail!(
            "`cue {name}` is available as a first-party external extension, but `cue-{name}` was not found next to `cue`; supported: {supported_subcommands}",
        );
    }
    crate::config::validate_extension_name(name, "extension subcommand")?;

    let config = load_config()?;
    if let Some(command) = resolve_user_extension_command(&config, name, &mut find_path_binary) {
        return exec_command(command, args);
    }

    bail!("unknown cue subcommand `{name}`; supported: {supported_subcommands}")
}

fn resolve_first_party_extension_command<F>(
    name: &str,
    mut find_first_party_binary: F,
) -> anyhow::Result<Option<ResolvedExtensionCommand>>
where
    F: FnMut(&str) -> anyhow::Result<Option<PathBuf>>,
{
    if let Some(program) = first_party_extension_program(name)
        && let Some(path) = find_first_party_binary(program)?
    {
        return Ok(Some(ResolvedExtensionCommand::Path(path)));
    }

    Ok(None)
}

fn resolve_user_extension_command<G>(
    config: &crate::config::Config,
    name: &str,
    mut find_path_binary: G,
) -> Option<ResolvedExtensionCommand>
where
    G: FnMut(&str) -> Option<PathBuf>,
{
    if let Some(extension) = config.extensions.commands.get(name) {
        return Some(ResolvedExtensionCommand::ConfiguredProgram(
            extension.program.clone(),
        ));
    }

    if config.extensions.path_lookup {
        return find_path_binary(&format!("cue-{name}")).map(ResolvedExtensionCommand::Path);
    }

    None
}

fn first_party_extension_binary(program: &str) -> anyhow::Result<Option<PathBuf>> {
    first_party_extension_binary_from_runtime_sources(
        program,
        std::env::current_exe(),
        crate::companion_binary::argv0_path(),
    )
}

fn first_party_extension_binary_from_runtime_sources(
    program: &str,
    current_exe: io::Result<PathBuf>,
    argv0_path: anyhow::Result<Option<PathBuf>>,
) -> anyhow::Result<Option<PathBuf>> {
    let current_exe =
        current_exe.context("resolve current executable path for first-party extension lookup")?;
    if let Some(path) = crate::companion_binary::companion_binary_for_path(&current_exe, program) {
        return Ok(Some(path));
    }

    Ok(argv0_path?
        .as_deref()
        .and_then(|path| crate::companion_binary::companion_binary_for_path(path, program)))
}

#[cfg(test)]
fn first_party_extension_binary_from_sources(
    program: &str,
    current_exe: Option<PathBuf>,
    argv0: Option<PathBuf>,
) -> Option<PathBuf> {
    crate::companion_binary::companion_binary_from_sources(program, current_exe, argv0)
}

fn is_first_party_extension(name: &str) -> bool {
    first_party_extension_program(name).is_some()
}

fn first_party_extension_program(name: &str) -> Option<&'static str> {
    match name {
        "tui" => Some("cue-tui"),
        _ => None,
    }
}

fn exec_resolved_extension_command(
    command: ResolvedExtensionCommand,
    args: &[OsString],
) -> anyhow::Result<i32> {
    match command {
        ResolvedExtensionCommand::ConfiguredProgram(program) => {
            exec_configured_extension_program(&program, args)
        }
        ResolvedExtensionCommand::Path(program) => exec_program(program.as_os_str(), args),
    }
}

fn exec_configured_extension_program(program: &str, args: &[OsString]) -> anyhow::Result<i32> {
    if program.trim().is_empty() {
        bail!("extension program is empty");
    }
    if program.trim() != program {
        bail!("extension program must not have leading or trailing whitespace");
    }
    exec_program(OsStr::new(program), args)
}

fn exec_program(program: &OsStr, args: &[OsString]) -> anyhow::Result<i32> {
    let status = Command::new(program)
        .args(args)
        .status()
        .with_context(|| format!("failed to run extension `{}`", program.to_string_lossy()))?;
    Ok(process_exit_code(status))
}

fn process_exit_code(status: std::process::ExitStatus) -> i32 {
    if let Some(code) = status.code() {
        return code.max(0);
    }
    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt as _;
        status.signal().map(|signal| 128 + signal).unwrap_or(1)
    }
    #[cfg(not(unix))]
    1
}

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

    use std::path::Path;

    #[test]
    fn first_party_tui_extension_does_not_resolve_without_companion_binary() {
        let command = resolve_first_party_extension_command("tui", |name| {
            assert_eq!(name, "cue-tui");
            Ok(None)
        })
        .expect("first-party resolver should not fail");

        assert_eq!(command, None);
    }

    #[test]
    fn run_first_party_extension_skips_user_registry_config() {
        let args = [OsString::from("--smoke")];

        let code = run_with(
            "tui",
            &args,
            "tui, run",
            || panic!("first-party dispatch should not load user extension config"),
            |name| {
                assert_eq!(name, "cue-tui");
                Ok(Some(PathBuf::from("/install/bin/cue-tui")))
            },
            |_| panic!("sibling first-party extension should not consult user PATH lookup"),
            |command, forwarded_args| {
                assert_eq!(
                    command,
                    ResolvedExtensionCommand::Path(PathBuf::from("/install/bin/cue-tui"))
                );
                assert_eq!(forwarded_args, &args);
                Ok(7)
            },
        )
        .expect("first-party extension should dispatch");

        assert_eq!(code, 7);
    }

    #[test]
    fn run_missing_first_party_extension_does_not_load_user_registry_config() {
        let error = run_with(
            "tui",
            &[],
            "tui, run",
            || panic!("missing first-party extension should not load user extension config"),
            |_| Ok(None),
            |_| panic!("missing first-party extension should not fall back to PATH"),
            |_, _| panic!("missing first-party extension should not execute"),
        )
        .expect_err("missing first-party extension should report installation problem");

        assert!(format!("{error:#}").contains("first-party external extension"));
    }

    #[test]
    fn run_invalid_extension_name_does_not_load_config_or_probe_path() {
        for name in ["foo_bar", "foo/bar", "-foo", "foo--bar"] {
            let error = run_with(
                name,
                &[],
                "tui, run",
                || panic!("invalid extension names should not load user extension config"),
                |_| panic!("invalid extension names should not probe first-party binaries"),
                |_| panic!("invalid extension names should not fall back to PATH"),
                |_, _| panic!("invalid extension names should not execute"),
            )
            .expect_err("invalid extension subcommand should fail at the dispatch boundary");

            assert_eq!(
                format!("{error:#}"),
                format!(
                    "extension subcommand `{name}` must be kebab-case ASCII, for example `foo` or `foo-bar`"
                )
            );
        }
    }

    #[test]
    fn run_first_party_extension_reports_lookup_error_without_user_registry_fallback() {
        let error = run_with(
            "tui",
            &[],
            "tui, run",
            || panic!("first-party lookup errors should not load user extension config"),
            |_| Err(anyhow::anyhow!("current directory was removed")),
            |_| panic!("first-party lookup errors should not fall back to PATH"),
            |_, _| panic!("failed first-party lookup should not execute"),
        )
        .expect_err("first-party lookup error should be reported");

        assert_eq!(format!("{error:#}"), "current directory was removed");
    }

    #[test]
    fn first_party_sibling_resolves_as_first_party_command() {
        let command = resolve_first_party_extension_command("tui", |name| {
            assert_eq!(name, "cue-tui");
            Ok(Some(PathBuf::from("/install/bin/cue-tui")))
        })
        .expect("first-party resolver should not fail");

        assert_eq!(
            command,
            Some(ResolvedExtensionCommand::Path(PathBuf::from(
                "/install/bin/cue-tui"
            )))
        );
    }

    #[test]
    fn non_first_party_extension_respects_global_path_lookup_flag() {
        let config = crate::config::Config::default();

        let command = resolve_user_extension_command(&config, "foo", |_| {
            panic!("PATH lookup should be disabled for ordinary extensions")
        });

        assert_eq!(command, None);
    }

    #[test]
    fn non_first_party_extension_uses_path_lookup_when_enabled() {
        let mut config = crate::config::Config::default();
        config.extensions.path_lookup = true;

        let command = resolve_user_extension_command(&config, "foo", |name| {
            assert_eq!(name, "cue-foo");
            Some(PathBuf::from("/tools/cue-foo"))
        });

        assert_eq!(
            command,
            Some(ResolvedExtensionCommand::Path(PathBuf::from(
                "/tools/cue-foo"
            )))
        );
    }

    #[test]
    fn first_party_binary_uses_current_exe_sibling() {
        let dir = make_temp_bin_dir("sibling");
        let cue = dir.join("cue");
        let tui = dir.join("cue-tui");
        touch(&cue);
        write_executable(&tui);

        assert_eq!(
            first_party_extension_binary_from_sources("cue-tui", Some(cue), None),
            Some(tui)
        );

        std::fs::remove_dir_all(dir).expect("remove temp bin dir");
    }

    #[test]
    fn first_party_binary_uses_cargo_deps_sibling() {
        let dir = make_temp_bin_dir("cargo-deps");
        let deps = dir.join("deps");
        std::fs::create_dir_all(&deps).expect("create deps dir");
        let cue = deps.join("cue-123");
        let tui = dir.join("cue-tui");
        touch(&cue);
        write_executable(&tui);

        assert_eq!(
            first_party_extension_binary_from_sources("cue-tui", Some(cue), None),
            Some(tui)
        );

        std::fs::remove_dir_all(dir).expect("remove temp bin dir");
    }

    #[test]
    fn first_party_binary_falls_back_to_argv0_when_current_exe_has_no_companion() {
        let current_dir = make_temp_bin_dir("current-no-companion");
        let argv0_dir = make_temp_bin_dir("argv0-companion");
        let current_cue = current_dir.join("cue");
        let argv0_cue = argv0_dir.join("cue");
        let argv0_tui = argv0_dir.join("cue-tui");
        touch(&current_cue);
        touch(&argv0_cue);
        write_executable(&argv0_tui);

        let resolved = first_party_extension_binary_from_runtime_sources(
            "cue-tui",
            Ok(current_cue),
            Ok(Some(argv0_cue)),
        )
        .expect("argv0 lookup should succeed");

        assert_eq!(resolved, Some(argv0_tui));
        std::fs::remove_dir_all(current_dir).expect("remove current temp bin dir");
        std::fs::remove_dir_all(argv0_dir).expect("remove argv0 temp bin dir");
    }

    #[test]
    fn first_party_binary_reports_current_exe_failure() {
        let error = first_party_extension_binary_from_runtime_sources(
            "cue-tui",
            Err(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                "current executable disappeared",
            )),
            Ok(Some(PathBuf::from("/ignored/cue"))),
        )
        .expect_err("current_exe errors should not be treated as missing companions");

        let message = format!("{error:#}");
        assert!(message.contains("resolve current executable path"));
        assert!(message.contains("current executable disappeared"));
    }

    #[test]
    fn first_party_extension_set_is_explicit() {
        assert!(is_first_party_extension("tui"));
        assert!(!is_first_party_extension("foo"));
    }

    #[test]
    fn configured_extension_program_rejects_empty_program() {
        let error = exec_configured_extension_program("   ", &[])
            .expect_err("empty configured extension program should fail before spawn");

        assert_eq!(format!("{error:#}"), "extension program is empty");
    }

    #[test]
    fn configured_extension_program_rejects_padded_program_without_trimming() {
        let error = exec_configured_extension_program(" sh", &[])
            .expect_err("padded configured extension program should fail before spawn");

        assert_eq!(
            format!("{error:#}"),
            "extension program must not have leading or trailing whitespace"
        );
    }

    #[cfg(unix)]
    #[test]
    fn exec_program_returns_child_exit_code_without_exiting() {
        let code = exec_program(
            OsStr::new("sh"),
            &[OsString::from("-c"), OsString::from("exit 7")],
        )
        .expect("run child extension");

        assert_eq!(code, 7);
    }

    #[cfg(unix)]
    #[test]
    fn exec_program_maps_signal_status_to_shell_exit_code() {
        let code = exec_program(
            OsStr::new("sh"),
            &[OsString::from("-c"), OsString::from("kill -TERM $$")],
        )
        .expect("run child extension");

        assert_eq!(code, 128 + libc::SIGTERM);
    }

    fn make_temp_bin_dir(name: &str) -> PathBuf {
        use std::sync::atomic::{AtomicU64, Ordering};

        static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);

        let dir = std::env::temp_dir().join(format!(
            "cue-extension-bin-test-{name}-{}-{}",
            std::process::id(),
            TEMP_COUNTER.fetch_add(1, Ordering::Relaxed)
        ));
        std::fs::create_dir_all(&dir).expect("create temp bin dir");
        dir
    }

    fn touch(path: &Path) {
        std::fs::write(path, []).expect("create temp file");
    }

    #[cfg(unix)]
    fn write_executable(path: &Path) {
        use std::os::unix::fs::PermissionsExt;

        std::fs::write(path, "#!/bin/sh\n").expect("write executable");
        let mut permissions = std::fs::metadata(path)
            .expect("stat executable")
            .permissions();
        permissions.set_mode(0o755);
        std::fs::set_permissions(path, permissions).expect("chmod executable");
    }

    #[cfg(not(unix))]
    fn write_executable(path: &Path) {
        std::fs::write(path, "").expect("write executable");
    }
}