From ba09bde5a7800ffdbdab6ec8e5f814f66e36c4a0 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Thu, 26 Nov 2026 13:16:33 +0100 Subject: [PATCH] Fix CLI --help/-h and --version flags, Windows setup/import/build-with, and Docker config healing (#982, #984) --- crates/kiri-win/src/client.rs | 15 ++ crates/kiri-win/src/engine.rs | 65 +++++- crates/kiri-win/src/main.rs | 7 +- crates/kiri-win/src/setup.rs | 1 + crates/kiri/src/bench.rs | 6 + crates/kiri/src/boot.rs | 8 + crates/kiri/src/bridge.rs | 27 ++- crates/kiri/src/builds.rs | 40 +++- crates/kiri/src/buildwith.rs | 22 +- crates/kiri/src/client.rs | 259 ++++++++++++++++++-- crates/kiri/src/diag/report.rs | 12 + crates/kiri/src/docker.rs | 1 + crates/kiri/src/dockerctx.rs | 303 ++++++++++++++++++++++++ crates/kiri/src/domains_cli.rs | 13 ++ crates/kiri/src/hostaccess.rs | 13 +- crates/kiri/src/images.rs | 29 ++- crates/kiri/src/import.rs | 145 +++++++++--- crates/kiri/src/k8s.rs | 4 + crates/kiri/src/machine.rs | 43 +++- crates/kiri/src/main.rs | 403 +++++++++++++++++++++++++++----- crates/kiri/src/registry_cli.rs | 10 +- crates/kiri/src/run.rs | 54 ++++- crates/kiri/src/setup.rs | 16 ++ crates/kiri/src/setup_win.rs | 310 ++++++++++++++++++++++++ crates/kiri/src/share.rs | 8 +- crates/kiri/src/usb.rs | 6 + crates/kiri/src/wsl.rs | 101 ++++++++ docs/fix-registry.md | 6 + tests/regressions.tsv | 2 + 29 files changed, 1787 insertions(+), 142 deletions(-) create mode 100644 crates/kiri/src/setup_win.rs diff --git a/crates/kiri-win/src/client.rs b/crates/kiri-win/src/client.rs index 2ecc259..7c7599a 100644 --- a/crates/kiri-win/src/client.rs +++ b/crates/kiri-win/src/client.rs @@ -426,6 +426,21 @@ pub fn alive() -> bool { alive_within(PING_WAIT) } +/// Probes the engine pipe for CLI-shared callers (`import.rs`), surfacing the +/// pipe's refusal message when Kiri is stopped or setup is unfinished. +#[allow(dead_code)] +pub fn check_alive() -> io::Result<()> { + match request_within("GET", "/_ping", None, true, Some(PING_WAIT)) { + Ok(r) if r.ok() => Ok(()), + Ok(r) => { + let err = r.error(); + let msg = if err.trim().is_empty() { "Kiri isn't running. Open Kiri, or start it with `kiri start`" } else { err.trim() }; + Err(io::Error::new(io::ErrorKind::NotConnected, msg.to_owned())) + } + Err(_) => Err(io::Error::new(io::ErrorKind::NotConnected, "Kiri isn't running. Open Kiri, or start it with `kiri start`")), + } +} + /// `alive`, for the event watcher: false after QUICK without an answer. pub fn alive_quick() -> bool { alive_within(QUICK) diff --git a/crates/kiri-win/src/engine.rs b/crates/kiri-win/src/engine.rs index 11b1715..deed953 100644 --- a/crates/kiri-win/src/engine.rs +++ b/crates/kiri-win/src/engine.rs @@ -962,6 +962,40 @@ fn emit_docker_state_if_changed() { } } +/// Ensures Kiri's `cliPluginsExtraDirs` and `kiri` context in +/// `%USERPROFILE%\.docker`, repairing `config.json` if another engine's +/// uninstaller (such as Docker Desktop's) removed it (#984). +pub fn heal_docker_config(pipe: &str) { + let Some(dir) = crate::dockerctx::docker_dir() else { return }; + let exe = std::env::current_exe().ok(); + let local = std::env::var_os("LOCALAPPDATA").map(std::path::PathBuf::from); + let plugins = crate::dockerctx::find_windows_cli_plugins(exe.as_deref(), local.as_deref()); + let desktop = std::env::var_os("ProgramFiles").is_some_and(|p| std::path::Path::new(&p).join(r"Docker\Docker\Docker Desktop.exe").is_file()); + let host = npipe_host(pipe); + match crate::dockerctx::repair_windows_config( + &dir, + crate::dockerctx::WindowsRepairOpts { + ours: crate::flavor::CONTEXT.get(), + description: "Kiri (WSL2)", + host: &host, + plugins_dir: plugins.as_deref(), + force_context_write: false, + set_current_if_empty: false, + force_use: false, + desktop_installed: desktop, + }, + ) { + Ok(r) if r.context_written || r.plugins_added || r.current_context_set => { + crate::serve::log(&format!( + "docker config self-healed (context={}, plugins={}, current={})", + r.context_written, r.plugins_added, r.current_context_set + )); + } + Ok(_) => {} + Err(e) => crate::serve::log(&format!("docker config: could not self-heal ({e})")), + } +} + /// Ensures the `kiri` context exists and is plain `docker`'s current context, /// keeping logins, credential helpers and plugin folders untouched (#369). pub fn use_kiri_context() -> io::Result<()> { @@ -1169,7 +1203,27 @@ fn set_pref(name: &str, value: Value) { /// A page link: only Kiri's own addresses, as on the Mac. fn allowed_url(url: &str) -> bool { - if url == "https://kiri.canestack.com" || url == "https://learn.microsoft.com/windows/wsl/about" || url == "https://github.com/libracoder/kiri/issues/new" || url == "https://github.com/libracoder/kiri" || url == "https://login.docker.com/activate" || url == "https://github.com/login/device" { + if matches!( + url, + "https://kiri.canestack.com" + | "https://runkiri.com" + | "https://runkiri.com/releases/" + | "https://runkiri.com/share/notice" + | "https://canestack.com" + | "https://learn.microsoft.com/windows/wsl/about" + | "https://github.com/libracoder/kiri/issues/new" + | "https://github.com/libracoder/kiri" + | "https://github.com/anchore/grype" + | "https://login.docker.com/activate" + | "https://github.com/login/device" + ) { + return true; + } + // A build warning's rule page (docs.docker.com/go/dockerfile/rule/…). + if url + .strip_prefix("https://docs.docker.com/go/") + .is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_alphanumeric() || b"-/".contains(&b))) + { return true; } let Some(rest) = url.strip_prefix("http://").or_else(|| url.strip_prefix("https://")) else { return false }; @@ -1239,8 +1293,17 @@ mod tests { assert!(allowed_url("http://localhost:8080/app")); assert!(allowed_url("https://web.kiri.localhost/")); assert!(allowed_url("http://api.kiri.local")); + assert!(allowed_url("https://runkiri.com")); + assert!(allowed_url("https://runkiri.com/releases/")); + assert!(allowed_url("https://runkiri.com/share/notice")); + assert!(allowed_url("https://canestack.com")); + assert!(allowed_url("https://kiri.canestack.com")); assert!(allowed_url("https://github.com/libracoder/kiri")); + assert!(allowed_url("https://github.com/libracoder/kiri/issues/new")); + assert!(allowed_url("https://github.com/anchore/grype")); + assert!(allowed_url("https://docs.docker.com/go/dockerfile/rule/from-as-casing/")); assert!(!allowed_url("http://evil.example/")); + assert!(!allowed_url("https://runkiri.com.evil.com")); // Bypass attempts the audit found. assert!(!allowed_url("http://localhost:1@evil.example/")); assert!(!allowed_url("http://evil.example\\x.kiri.localhost")); diff --git a/crates/kiri-win/src/main.rs b/crates/kiri-win/src/main.rs index 8beace5..9f5737b 100644 --- a/crates/kiri-win/src/main.rs +++ b/crates/kiri-win/src/main.rs @@ -44,7 +44,8 @@ mod relay; #[cfg(windows)] #[path = "../../kiri/src/hostrelay.rs"] mod hostrelay; -#[cfg(windows)] +#[cfg(any(windows, test))] +#[cfg_attr(not(windows), allow(dead_code))] #[path = "../../kiri/src/dockerctx.rs"] mod dockerctx; #[cfg(windows)] @@ -73,6 +74,7 @@ mod builds; // and Linux's own crates/kiri/src/buildwith.rs. #[cfg(windows)] #[path = "../../kiri/src/buildwith.rs"] +#[allow(dead_code)] mod buildwith; // Kiri's program moved or deleted from where it started: the Mac's and // Linux's own crates/kiri/src/appwatch.rs. @@ -217,6 +219,9 @@ fn main() -> std::process::ExitCode { return std::process::ExitCode::FAILURE; } client::set_pipe(&cfg.pipe); + if !setup { + engine::heal_docker_config(&cfg.pipe); + } ports::start(); if let Err(e) = dns::start() { serve::log(&format!("dns on 127.0.0.1:53: {e}")); diff --git a/crates/kiri-win/src/setup.rs b/crates/kiri-win/src/setup.rs index 717710e..84bed56 100644 --- a/crates/kiri-win/src/setup.rs +++ b/crates/kiri-win/src/setup.rs @@ -996,6 +996,7 @@ fn tools() -> io::Result<()> { /// Ready → Open Kiri: remember setup is done, start at sign-in if asked. fn finish() { let autostart = STATE.lock().unwrap_or_else(PoisonError::into_inner).as_ref().is_none_or(|s| s.autostart); + crate::engine::heal_docker_config(&crate::client::pipe()); // Apply "Make Kiri the default for docker" on finish too (e.g. if checked after tools finished). if STATE.lock().unwrap_or_else(PoisonError::into_inner).as_ref().is_some_and(|s| s.make_default) && let Err(e) = crate::engine::use_kiri_context() diff --git a/crates/kiri/src/bench.rs b/crates/kiri/src/bench.rs index da98e20..9985ff5 100644 --- a/crates/kiri/src/bench.rs +++ b/crates/kiri/src/bench.rs @@ -39,6 +39,12 @@ const ENGINES: [(&str, &str, &str); 3] = [ ]; pub fn run(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } let mut o = Opts { runs: 50, image: "alpine:latest".into(), bridge: false, only: None }; let mut it = args.iter(); while let Some(a) = it.next() { diff --git a/crates/kiri/src/boot.rs b/crates/kiri/src/boot.rs index 81b811d..eca6a2f 100644 --- a/crates/kiri/src/boot.rs +++ b/crates/kiri/src/boot.rs @@ -5,7 +5,15 @@ use std::time::Duration; use crate::guest::{BootOptions, Guest}; +const USAGE: &str = "usage: kiri boot [--console] [--pings N]"; + pub fn run(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } let mut opts = BootOptions::default(); let mut pings = 1000usize; let mut it = args.iter(); diff --git a/crates/kiri/src/bridge.rs b/crates/kiri/src/bridge.rs index a9dbd86..3833a9e 100644 --- a/crates/kiri/src/bridge.rs +++ b/crates/kiri/src/bridge.rs @@ -103,9 +103,32 @@ const LOG: &str = "/var/log/kiri.log"; type Out = Arc>; +const USAGE: &str = "usage: kiri bridge [--socket PATH]"; + pub fn run(args: &[String]) -> io::Result<()> { - let socket = match args.iter().position(|a| a == "--socket").and_then(|i| args.get(i + 1)) { - Some(s) => PathBuf::from(s), + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } + let mut socket_opt = None; + let mut it = args.iter(); + while let Some(a) = it.next() { + match a.as_str() { + "--socket" => { + socket_opt = Some( + it.next() + .filter(|s| !s.is_empty()) + .map(PathBuf::from) + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, USAGE))?, + ); + } + _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, USAGE)), + } + } + let socket = match socket_opt { + Some(s) => s, None => crate::daemon::socket_path()?, }; let out: Out = Arc::new(Mutex::new(BufWriter::with_capacity(64 * 1024, io::stdout()))); diff --git a/crates/kiri/src/builds.rs b/crates/kiri/src/builds.rs index e8a7c07..7f94573 100644 --- a/crates/kiri/src/builds.rs +++ b/crates/kiri/src/builds.rs @@ -462,25 +462,32 @@ pub fn builder() -> io::Result { std::thread::sleep(std::time::Duration::from_millis(200)); } let quiet = || std::process::Stdio::null(); - if !Command::new(&docker).args(["buildx", "version"]).stdout(quiet()).stderr(quiet()).status()?.success() { + let new_docker = || { + #[allow(unused_mut)] + let mut cmd = Command::new(&docker); + #[cfg(windows)] + std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); + cmd + }; + if !new_docker().args(["buildx", "version"]).stdout(quiet()).stderr(quiet()).status()?.success() { println!("docker build: no buildx plugin here, so docker builds with Kiri's classic builder API (the same BuildKit, run by the daemon)"); return Ok(false); } - let inspect = Command::new(&docker).args(["buildx", "inspect", BUILDER.get()]).stderr(quiet()).output()?; + let inspect = new_docker().args(["buildx", "inspect", BUILDER.get()]).stderr(quiet()).output()?; let mut exists = inspect.status.success(); // Without default-load a docker-container builder keeps what it builds // to itself: `docker build -t x .` builds and `docker run x` finds // nothing. One made without it is made again; --keep-state keeps its // cache volume, which the daemon's builder container reuses. if exists && !String::from_utf8_lossy(&inspect.stdout).contains("default-load") { - exists = !Command::new(&docker).args(["buildx", "rm", "--keep-state", BUILDER.get()]).stdout(quiet()).stderr(quiet()).status()?.success(); + exists = !new_docker().args(["buildx", "rm", "--keep-state", BUILDER.get()]).stdout(quiet()).stderr(quiet()).status()?.success(); } if !exists { // buildx create takes the Kiri context's name; without that context // (Linux makes it only in the optional "docker uses Kiri" step) buildx // reads the name as a host and fails on tcp://kiri:2375. ensure_context(&docker)?; - let made = Command::new(&docker) + let made = new_docker() .args(["buildx", "create", "--name", BUILDER.get(), "--driver", "docker-container", "--driver-opt", "default-load=true", CONTEXT.get()]) .stdout(quiet()) .output()?; @@ -496,13 +503,24 @@ pub fn builder() -> io::Result { Ok(true) } -/// The docker context named CONTEXT, pointing at Kiri's socket, made when -/// missing. It is only made, never made current: which engine plain docker -/// uses stays the user's choice. -/// On Windows, setup (kiri.ps1) makes the context, on the pipe. -#[cfg(not(unix))] -fn ensure_context(_docker: impl AsRef) -> io::Result<()> { - Ok(()) +/// The docker context named CONTEXT, pointing at Kiri's socket or Windows +/// named pipe, made when missing. It is only made, never made current: which +/// engine plain docker uses stays the user's choice. +#[cfg(windows)] +fn ensure_context(docker: impl AsRef) -> io::Result<()> { + let docker = docker.as_ref(); + let quiet = || std::process::Stdio::null(); + let new_cmd = || { + let mut cmd = Command::new(docker); + std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); + cmd + }; + if new_cmd().args(["context", "inspect", CONTEXT.get()]).stdout(quiet()).stderr(quiet()).status()?.success() { + return Ok(()); + } + let host = format!("host=npipe://{}", crate::client::pipe().replace('\\', "/")); + let out = new_cmd().args(["context", "create", CONTEXT.get(), "--description", "Kiri (WSL2)", "--docker", &host]).stdout(quiet()).output()?; + if out.status.success() { Ok(()) } else { Err(io::Error::other(failure("docker context create failed", &out.stderr))) } } #[cfg(unix)] diff --git a/crates/kiri/src/buildwith.rs b/crates/kiri/src/buildwith.rs index 4bf796a..68a927e 100644 --- a/crates/kiri/src/buildwith.rs +++ b/crates/kiri/src/buildwith.rs @@ -437,13 +437,27 @@ pub fn ask() -> Option<&'static str> { places().ok().filter(|p| p.ask(other)).and(other) } -/// `kiri build-with [docker|kiri]`: says which, or switches. -#[cfg(unix)] +const USAGE: &str = "usage: kiri build-with [docker|kiri|status]"; + +/// `kiri build-with [docker|kiri|status]`: says which, or switches. +#[cfg(any(unix, windows))] pub fn cli(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } + if args.len() > 1 { + return Err(io::Error::new(io::ErrorKind::InvalidInput, USAGE)); + } + let choice = match args.first().map(String::as_str) { + None | Some("status") => None, + Some(a) => Some(With::parse(a).ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, USAGE))?), + }; let p = places()?; let other = other_engine(); - if let Some(a) = args.first() { - let with = With::parse(a).ok_or_else(|| io::Error::other("usage: kiri build-with [docker|kiri]"))?; + if let Some(with) = choice { p.choose(with)?; if with == With::Kiri && !p.ready() { crate::builds::ensure_builder(); diff --git a/crates/kiri/src/client.rs b/crates/kiri/src/client.rs index 7adcc12..494794e 100644 --- a/crates/kiri/src/client.rs +++ b/crates/kiri/src/client.rs @@ -1,18 +1,37 @@ //! The window and `kiri` subcommands talk to `kiri daemon` the way the docker CLI does: HTTP over -//! the daemon's unix socket. One short connection per request, and one -//! long-lived one for `/events`. +//! the daemon's unix socket (or `\\.\pipe\kiri` on Windows). One short connection per request, +//! and one long-lived one for `/events`. // Parts of this serve only the Mac (the window, boot timings). #![cfg_attr(not(target_os = "macos"), allow(dead_code))] +#[cfg(any(unix, test))] use std::ffi::OsStr; use std::io::{self, BufRead, BufReader, Read, Write}; +#[cfg(unix)] use std::os::unix::net::UnixStream; -use std::path::{Component, Path, PathBuf}; +#[cfg(any(unix, test))] +use std::path::Component; +use std::path::PathBuf; +#[cfg(any(unix, test))] +use std::path::Path; use std::time::Duration; use serde_json::Value; +#[cfg(windows)] +pub const DEFAULT_PIPE: &str = r"\\.\pipe\kiri"; + +/// The Windows named pipe `kiri-win` serves the Docker API on. +#[cfg(windows)] +pub fn pipe() -> String { + std::env::var("KIRI_PIPE") + .ok() + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| DEFAULT_PIPE.to_owned()) +} + +#[cfg(unix)] pub fn socket() -> io::Result { let kiri_socket = std::env::var_os("KIRI_SOCKET"); let home = std::env::var_os("HOME"); @@ -35,10 +54,21 @@ pub fn socket() -> io::Result { } } +#[cfg(any(unix, test))] fn safe_wsl_distro(name: &str) -> bool { - crate::daemon::binds::valid_distro_name(name) && !name.contains("..") + #[cfg(unix)] + { + crate::daemon::binds::valid_distro_name(name) && !name.contains("..") + } + #[cfg(not(unix))] + { + !name.is_empty() + && !name.contains("..") + && name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')) + } } +#[cfg(any(unix, test))] fn is_wsl_socket_path(target: &Path, wsl_sockets_dir: &Path) -> bool { let Ok(rel) = target.strip_prefix(wsl_sockets_dir) else { return false; @@ -56,6 +86,7 @@ fn is_wsl_socket_path(target: &Path, wsl_sockets_dir: &Path) -> bool { /// directory (such as a `0750` WSL integration socket directory) as present so /// `check_alive` surfaces a clear permission-denied error instead of falling /// back to a missing home socket. +#[cfg(any(unix, test))] fn socket_present(path: &Path) -> bool { match std::fs::metadata(path) { Ok(_) => true, @@ -63,6 +94,7 @@ fn socket_present(path: &Path) -> bool { } } +#[cfg(any(unix, test))] fn socket_for( kiri_socket: Option<&OsStr>, service_socket: Option<&Path>, @@ -129,16 +161,106 @@ impl Response { } } +#[cfg(unix)] +fn op_header() -> String { + crate::diag::op_header() +} + +#[cfg(windows)] +fn op_header() -> String { + String::new() +} + +#[cfg(unix)] fn connect_to(sock: &Path, timeout: Option) -> io::Result { let s = UnixStream::connect(sock)?; s.set_read_timeout(timeout)?; Ok(s) } +#[cfg(unix)] fn connect(timeout: Option) -> io::Result { connect_to(&socket()?, timeout) } +#[cfg(windows)] +struct WinPipe(std::fs::File); + +#[cfg(windows)] +impl WinPipe { + fn open(name: &str) -> io::Result { + use std::os::windows::fs::OpenOptionsExt; + use std::os::windows::io::AsRawHandle; + const ERROR_PIPE_BUSY: i32 = 231; + const SECURITY_IDENTIFICATION: u32 = 0x0001_0000; + const PIPE_READMODE_MESSAGE: u32 = 0x0000_0002; + unsafe extern "system" { + fn SetNamedPipeHandleState( + hNamedPipe: *mut core::ffi::c_void, + lpMode: *const u32, + lpMaxCollectionCount: *const u32, + lpCollectDataTimeout: *const u32, + ) -> i32; + } + for _ in 0..20 { + match std::fs::OpenOptions::new() + .read(true) + .write(true) + .share_mode(0) + .security_qos_flags(SECURITY_IDENTIFICATION) + .open(name) + { + Ok(file) => { + // `kiri-win` serves `\\.\pipe\kiri` in message mode and ends + // unframed HTTP responses with a 0-byte message. + let mode = PIPE_READMODE_MESSAGE; + // SAFETY: `file` owns a valid handle for the duration of the call. + unsafe { + SetNamedPipeHandleState( + file.as_raw_handle(), + &mode, + std::ptr::null(), + std::ptr::null(), + ); + } + return Ok(Self(file)); + } + Err(e) if e.raw_os_error() == Some(ERROR_PIPE_BUSY) => { + std::thread::sleep(Duration::from_millis(50)); + } + Err(e) => return Err(e), + } + } + Err(io::Error::new(io::ErrorKind::TimedOut, format!("pipe {name} stayed busy"))) + } +} + +#[cfg(windows)] +impl Read for WinPipe { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + const ERROR_BROKEN_PIPE: i32 = 109; + const ERROR_PIPE_NOT_CONNECTED: i32 = 233; + const ERROR_MORE_DATA: i32 = 234; + match self.0.read(buf) { + Ok(n) => Ok(n), + Err(e) if e.raw_os_error() == Some(ERROR_MORE_DATA) => Ok(buf.len()), + Err(e) if matches!(e.raw_os_error(), Some(ERROR_BROKEN_PIPE | ERROR_PIPE_NOT_CONNECTED)) => Ok(0), + Err(e) => Err(e), + } + } +} + +#[cfg(windows)] +impl Write for WinPipe { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.0.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.0.flush() + } +} + fn head(r: &mut impl BufRead) -> io::Result<(u16, Option, bool)> { let mut line = String::new(); r.read_line(&mut line)?; @@ -195,15 +317,17 @@ pub fn get_background(path: &str) -> io::Result { Ok(r.json()) } +#[cfg(unix)] fn send(method: &str, path: &str, body: Option<&Value>, extra: &str) -> io::Result { send_to(&socket()?, method, path, body, extra) } +#[cfg(unix)] fn send_to(sock: &Path, method: &str, path: &str, body: Option<&Value>, extra: &str) -> io::Result { let mut s = connect_to(sock, Some(Duration::from_secs(120)))?; let payload = body.map(Value::to_string).unwrap_or_default(); // The window's action this is part of, for the engine's log lines. - let op = crate::diag::op_header(); + let op = op_header(); write!( s, "{method} {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{extra}{op}Content-Type: application/json\r\nContent-Length: {}\r\n\r\n{payload}", @@ -212,6 +336,25 @@ fn send_to(sock: &Path, method: &str, path: &str, body: Option<&Value>, extra: & answer(s) } +#[cfg(windows)] +fn send(method: &str, path: &str, body: Option<&Value>, extra: &str) -> io::Result { + send_to_pipe(&pipe(), method, path, body, extra) +} + +#[cfg(windows)] +fn send_to_pipe(name: &str, method: &str, path: &str, body: Option<&Value>, extra: &str) -> io::Result { + let mut s = WinPipe::open(name)?; + let payload = body.map(Value::to_string).unwrap_or_default(); + let op = op_header(); + write!( + s, + "{method} {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{extra}{op}Content-Type: application/json\r\nContent-Length: {}\r\n\r\n{payload}", + payload.len() + )?; + s.flush()?; + answer(s) +} + /// The answer to a request just sent; the whole body is read, chunked or not. fn answer(s: impl Read) -> io::Result { let mut r = BufReader::new(s); @@ -239,9 +382,10 @@ fn answer(s: impl Read) -> io::Result { /// body `write` gives up on is never ended, so the daemon sees it cut /// short, not as a whole one; if the daemon stopped reading first (it /// refused the request), its answer is returned, which says why. +#[cfg(unix)] pub fn post_stream(path: &str, content_type: &str, write: impl FnOnce(&mut dyn Write) -> io::Result<()>) -> io::Result { let s = connect(Some(Duration::from_secs(300)))?; - let op = crate::diag::op_header(); + let op = op_header(); (&s).write_all(format!("POST {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{op}Content-Type: {content_type}\r\nTransfer-Encoding: chunked\r\n\r\n").as_bytes())?; match stream_body(&s, write) { Ok(()) => answer(&s), @@ -253,6 +397,24 @@ pub fn post_stream(path: &str, content_type: &str, write: impl FnOnce(&mut dyn W } } +#[cfg(windows)] +pub fn post_stream(path: &str, content_type: &str, write: impl FnOnce(&mut dyn Write) -> io::Result<()>) -> io::Result { + let mut s = WinPipe::open(&pipe())?; + let op = op_header(); + write!( + s, + "POST {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{op}Content-Type: {content_type}\r\nTransfer-Encoding: chunked\r\n\r\n" + )?; + match stream_body(&mut s, write) { + Ok(()) => answer(s), + Err(e) if refused(&e) => match answer(s) { + Ok(r) if !r.ok() => Ok(r), + _ => Err(e), + }, + Err(e) => Err(e), + } +} + /// Writes a body chunked, in chunks of up to 256 KiB, and ends it only when /// `write` succeeds. pub(crate) fn stream_body(to: impl Write, write: impl FnOnce(&mut dyn Write) -> io::Result<()>) -> io::Result<()> { @@ -325,16 +487,24 @@ fn not_running_message_for(is_linux: bool, is_wsl: bool) -> &'static str { /// Actionable OS-specific error text when the engine is not running. pub fn not_running_message() -> &'static str { - #[cfg(target_os = "linux")] - let wsl = is_wsl_env( - std::env::var_os("WSL_DISTRO_NAME").as_deref(), - &[Path::new("/proc/sys/fs/binfmt_misc/WSLInterop"), Path::new("/proc/sys/fs/binfmt_misc/WSLInterop-late")], - ); - #[cfg(not(target_os = "linux"))] - let wsl = false; - not_running_message_for(cfg!(target_os = "linux"), wsl) + #[cfg(windows)] + { + "Kiri isn't running. Open Kiri, or start it with `kiri start`" + } + #[cfg(not(windows))] + { + #[cfg(target_os = "linux")] + let wsl = is_wsl_env( + std::env::var_os("WSL_DISTRO_NAME").as_deref(), + &[Path::new("/proc/sys/fs/binfmt_misc/WSLInterop"), Path::new("/proc/sys/fs/binfmt_misc/WSLInterop-late")], + ); + #[cfg(not(target_os = "linux"))] + let wsl = false; + not_running_message_for(cfg!(target_os = "linux"), wsl) + } } +#[cfg(any(unix, test))] fn permission_denied_error(sock: &Path, is_linux: bool) -> io::Error { let msg = if is_linux { format!( @@ -347,6 +517,7 @@ fn permission_denied_error(sock: &Path, is_linux: bool) -> io::Error { io::Error::new(io::ErrorKind::PermissionDenied, msg) } +#[cfg(unix)] fn check_alive_at(sock: &Path, not_running: &str) -> io::Result<()> { match send_to(sock, "GET", "/_ping", None, "X-Kiri-Background: 1\r\n") { Ok(r) if r.ok() => Ok(()), @@ -362,16 +533,31 @@ pub fn check_alive() -> io::Result<()> { } /// Like [`check_alive`], using `not_running` when the daemon is not running. +#[cfg(unix)] pub fn check_alive_with(not_running: &str) -> io::Result<()> { let sock = socket()?; check_alive_at(&sock, not_running) } +#[cfg(windows)] +pub fn check_alive_with(not_running: &str) -> io::Result<()> { + let p = pipe(); + match send_to_pipe(&p, "GET", "/_ping", None, "X-Kiri-Background: 1\r\n") { + Ok(r) if r.ok() => Ok(()), + Err(e) if e.kind() == io::ErrorKind::PermissionDenied => Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!("cannot connect to Kiri's pipe ({p}): permission denied"), + )), + _ => Err(io::Error::new(io::ErrorKind::NotConnected, not_running)), + } +} + /// A POST whose answer is JSON lines arriving over time (a pull's /// progress): `on_line` sees each as it comes. Returns the HTTP status. /// `auth` is a registry sign-in for a pull (`X-Registry-Auth`, base64url). /// `opened` gets the connection once it is made, so another thread can /// shut it down to stop the request (Cancel on a pull). +#[cfg(unix)] pub fn post_lines_closable(path: &str, auth: Option<&str>, opened: impl FnOnce(&UnixStream), on_line: impl FnMut(Value)) -> io::Result { post_lines_inner(path, auth, Some(Duration::from_secs(120)), opened, on_line) } @@ -383,6 +569,7 @@ pub fn post_lines_unbounded(path: &str, on_line: impl FnMut(Value)) -> io::Resul post_lines_inner(path, None, None, |_| {}, on_line) } +#[cfg(unix)] fn post_lines_inner(path: &str, auth: Option<&str>, timeout: Option, opened: impl FnOnce(&UnixStream), mut on_line: impl FnMut(Value)) -> io::Result { if auth.is_some_and(|a| a.contains(['\r', '\n'])) { return Err(io::Error::new(io::ErrorKind::InvalidInput, "header contains a line break")); @@ -390,7 +577,7 @@ fn post_lines_inner(path: &str, auth: Option<&str>, timeout: Option, o let auth = auth.map(|a| format!("X-Registry-Auth: {a}\r\n")).unwrap_or_default(); let mut s = connect(timeout)?; opened(&s); - write!(s, "POST {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{auth}{}Content-Type: application/json\r\nContent-Length: 0\r\n\r\n", crate::diag::op_header())?; + write!(s, "POST {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{auth}{}Content-Type: application/json\r\nContent-Length: 0\r\n\r\n", op_header())?; let mut r = BufReader::new(s); let (status, len, chunked) = head(&mut r)?; let mut pending = Vec::new(); @@ -420,6 +607,7 @@ fn post_lines_inner(path: &str, auth: Option<&str>, timeout: Option, o } /// Calls `on_event` for each event until the connection ends or it returns false. +#[cfg(unix)] pub fn events(mut on_event: impl FnMut(Value) -> bool) -> io::Result<()> { let mut s = connect(None)?; write!(s, "GET /events HTTP/1.1\r\nHost: kiri\r\nX-Kiri-Background: 1\r\n\r\n")?; @@ -445,10 +633,12 @@ pub fn events(mut on_event: impl FnMut(Value) -> bool) -> io::Result<()> { /// A long-lived streamed response, such as `logs?follow=1`, read chunk by /// chunk. `closer` ends it from another thread. +#[cfg(unix)] pub struct Stream { reader: BufReader, } +#[cfg(unix)] impl Stream { pub fn open(path: &str) -> io::Result { let mut s = connect(None)?; @@ -473,6 +663,7 @@ impl Stream { /// Runs `cmd` in a running container and returns (exit code, output), /// through the exec API with a terminal, so output arrives unframed. +#[cfg(unix)] pub fn exec(container: &str, cmd: &[&str]) -> io::Result<(i64, String)> { let created = request("POST", &format!("/containers/{container}/exec"), Some(&serde_json::json!({"Cmd": cmd, "AttachStdout": true, "AttachStderr": true, "Tty": true})))?; if !created.ok() { @@ -497,7 +688,8 @@ pub fn exec(container: &str, cmd: &[&str]) -> io::Result<(i64, String)> { Ok((code, String::from_utf8_lossy(&out).replace("\r\n", "\n"))) } -/// A docker CLI: on PATH, else the one bundled in Kiri.app. +/// A docker CLI: on PATH, else the one bundled in Kiri.app (or Kiri's bin folder on Windows). +#[cfg(unix)] pub fn docker_cli() -> Option { let on_path = std::env::var_os("PATH").and_then(|p| std::env::split_paths(&p).map(|d| d.join("docker")).find(|d| d.is_file())); on_path @@ -508,6 +700,29 @@ pub fn docker_cli() -> Option { .or_else(lite_cli) } +#[cfg(windows)] +pub fn docker_cli() -> Option { + let beside = std::env::current_exe() + .ok() + .and_then(|e| e.parent().map(|d| d.join("docker.exe"))) + .filter(|d| d.is_file()); + let local = || { + let base = PathBuf::from(std::env::var_os("LOCALAPPDATA")?); + [ + base.join("Kiri").join("bin").join("docker.exe"), + base.join("Programs").join("Kiri").join("bin").join("docker.exe"), + base.join("Programs").join("Kiri").join("docker.exe"), + ] + .into_iter() + .find(|d| d.is_file()) + }; + let on_path = || { + std::env::var_os("PATH") + .and_then(|p| std::env::split_paths(&p).map(|d| d.join("docker.exe")).find(|d| d.is_file())) + }; + beside.or_else(local).or_else(on_path) +} + /// Kiri Lite's downloaded CLI. #[cfg(target_os = "macos")] fn lite_cli() -> Option { @@ -521,13 +736,21 @@ fn lite_cli() -> Option { #[cfg(test)] mod tests { + #[cfg(unix)] use std::ffi::OsStr; - use std::io::{self, Read, Write}; + #[cfg(unix)] + use std::io::{Read, Write}; + use std::io; + #[cfg(unix)] use std::os::unix::fs::PermissionsExt; + #[cfg(unix)] use std::os::unix::net::UnixListener; + #[cfg(unix)] use std::path::{Path, PathBuf}; + #[cfg(unix)] use std::sync::atomic::{AtomicU64, Ordering}; + #[cfg(unix)] fn temp_dir(tag: &str) -> PathBuf { static SEQ: AtomicU64 = AtomicU64::new(0); let dir = std::env::temp_dir().join(format!("kiri-client-{tag}-{}-{}", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed))); @@ -559,6 +782,7 @@ mod tests { assert!(super::refused(&io::Error::from(io::ErrorKind::BrokenPipe)) && !super::refused(&io::Error::other("x"))); } + #[cfg(unix)] #[test] fn socket_for_discovers_wsl_integration_sockets_and_symlinks() { let root = temp_dir("wsl-sock"); @@ -637,6 +861,7 @@ mod tests { let _ = std::fs::remove_dir_all(&root); } + #[cfg(unix)] #[test] fn check_alive_distinguishes_alive_not_running_and_permission_denied() { let dir = temp_dir("alive"); diff --git a/crates/kiri/src/diag/report.rs b/crates/kiri/src/diag/report.rs index 4fc5559..82af388 100644 --- a/crates/kiri/src/diag/report.rs +++ b/crates/kiri/src/diag/report.rs @@ -69,6 +69,10 @@ const MAC_REPORT_BUDGET: usize = 24 << 10; pub fn run(args: &[String]) -> io::Result<()> { match args.first().map(String::as_str) { + Some("-h" | "--help" | "help") => { + println!("{USAGE}"); + Ok(()) + } Some("logs") => logs_cli(&args[1..]), Some("report") => report_cli(&args[1..]), _ => Err(io::Error::other(USAGE)), @@ -175,6 +179,10 @@ pub fn render(v: &Value, utc: bool, color: bool) -> String { } fn logs_cli(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) { + println!("{USAGE}"); + return Ok(()); + } let (mut parts, mut follow, mut errors, mut n, mut op) = (Vec::new(), false, false, 50usize, None); let mut it = args.iter(); while let Some(a) = it.next() { @@ -556,6 +564,10 @@ pub fn reveal(path: &Path) { } fn report_cli(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) { + println!("{USAGE}"); + return Ok(()); + } let (mut out, mut send_it) = (None, false); let mut it = args.iter(); while let Some(a) = it.next() { diff --git a/crates/kiri/src/docker.rs b/crates/kiri/src/docker.rs index 10ea4b3..53d7fce 100644 --- a/crates/kiri/src/docker.rs +++ b/crates/kiri/src/docker.rs @@ -55,6 +55,7 @@ pub fn run(args: &[String]) -> io::Result<()> { /// Exits with docker's exit code. #[cfg(windows)] pub fn run(args: &[String]) -> io::Result<()> { + crate::setup_win::heal_quietly(); let beside = std::env::current_exe().ok().and_then(|e| Some(e.parent()?.join("docker.exe"))).filter(|d| d.is_file()); let status = std::process::Command::new(beside.unwrap_or_else(|| "docker.exe".into())) .args(["--context", crate::flavor::CONTEXT.get()]) diff --git a/crates/kiri/src/dockerctx.rs b/crates/kiri/src/dockerctx.rs index 19d600e..b77850b 100644 --- a/crates/kiri/src/dockerctx.rs +++ b/crates/kiri/src/dockerctx.rs @@ -274,6 +274,181 @@ pub fn switch(dir: &Path, meta: &Path, name: &str, ours: &str, description: &str set_current(&dir.join("config.json"), name) } +/// Lowercase hex SHA-256 of `data`, using `std` only so `dockerctx` stays +/// dependency-free across `kiri`, `kiri-win`, and host-side tests. +pub fn sha256_hex(data: &[u8]) -> String { + const K: [u32; 64] = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, + ]; + let mut h: [u32; 8] = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, + ]; + let bit_len = (data.len() as u64).wrapping_mul(8); + let mut msg = Vec::with_capacity((data.len() + 9).next_multiple_of(64)); + msg.extend_from_slice(data); + msg.push(0x80); + while msg.len() % 64 != 56 { + msg.push(0); + } + msg.extend_from_slice(&bit_len.to_be_bytes()); + for chunk in msg.as_chunks::<64>().0 { + let mut w = [0u32; 64]; + for (i, word) in chunk.as_chunks::<4>().0.iter().enumerate() { + w[i] = u32::from_be_bytes(*word); + } + for i in 16..64 { + let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3); + let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10); + w[i] = w[i - 16].wrapping_add(s0).wrapping_add(w[i - 7]).wrapping_add(s1); + } + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = h; + for i in 0..64 { + let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); + let ch = (e & f) ^ ((!e) & g); + let temp1 = hh.wrapping_add(s1).wrapping_add(ch).wrapping_add(K[i]).wrapping_add(w[i]); + let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); + let maj = (a & b) ^ (a & c) ^ (b & c); + let temp2 = s0.wrapping_add(maj); + hh = g; + g = f; + f = e; + e = d.wrapping_add(temp1); + d = c; + c = b; + b = a; + a = temp1.wrapping_add(temp2); + } + for (dst, add) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) { + *dst = dst.wrapping_add(add); + } + } + let mut out = String::with_capacity(64); + for word in h { + use std::fmt::Write as _; + let _ = write!(out, "{word:08x}"); + } + out +} + +/// The docker CLI's directory for a named context (`contexts/meta/`). +pub fn context_meta(dir: &Path, name: &str) -> PathBuf { + dir.join("contexts/meta").join(sha256_hex(name.as_bytes())) +} + +/// Candidate Windows `cli-plugins` folders for Kiri (`cli-plugins` beside +/// `kiri.exe`, `bin\cli-plugins` beside `kiri-win.exe`, `%LOCALAPPDATA%\Kiri\bin\cli-plugins`, +/// and `%LOCALAPPDATA%\Programs\Kiri\cli-plugins`), returning the first existing directory. +#[cfg_attr(not(any(windows, test)), allow(dead_code))] +pub fn find_windows_cli_plugins(exe: Option<&Path>, local_app_data: Option<&Path>) -> Option { + let mut candidates = Vec::new(); + if let Some(exe_dir) = exe.and_then(Path::parent) { + candidates.push(exe_dir.join("cli-plugins")); + candidates.push(exe_dir.join("bin").join("cli-plugins")); + } + if let Some(local) = local_app_data { + candidates.push(local.join("Kiri").join("bin").join("cli-plugins")); + candidates.push(local.join("Kiri").join("cli-plugins")); + candidates.push(local.join("Programs").join("Kiri").join("bin").join("cli-plugins")); + candidates.push(local.join("Programs").join("Kiri").join("cli-plugins")); + } + candidates.into_iter().find(|p| p.is_dir()) +} + +#[cfg_attr(not(any(windows, test)), allow(dead_code))] +fn same_windows_dir(a: &str, b: &str) -> bool { + let norm = |s: &str| s.replace('\\', "/").trim_end_matches('/').to_ascii_lowercase(); + norm(a) == norm(b) +} + +/// What [`repair_windows_config`] changed in `%USERPROFILE%\.docker`. +#[cfg_attr(not(any(windows, test)), allow(dead_code))] +#[derive(Debug, Default, PartialEq, Eq)] +pub struct WindowsRepair { + pub context_written: bool, + pub plugins_added: bool, + pub current_context_set: bool, +} + +/// Options for [`repair_windows_config`]. +#[cfg_attr(not(any(windows, test)), allow(dead_code))] +#[derive(Debug, Clone, Copy)] +pub struct WindowsRepairOpts<'a> { + pub ours: &'a str, + pub description: &'a str, + pub host: &'a str, + pub plugins_dir: Option<&'a Path>, + /// Always rewrite `contexts/meta//meta.json` (used by `kiri setup`). + pub force_context_write: bool, + /// Set `currentContext` to `ours` whenever `currentContext` is empty (`kiri setup`). + pub set_current_if_empty: bool, + /// Unconditionally set `currentContext` to `ours` (`kiri setup --use`). + pub force_use: bool, + /// Whether Docker Desktop (`Docker Desktop.exe`) is still installed on this PC. + pub desktop_installed: bool, +} + +/// Ensures Kiri's Windows Docker configuration in `dir` (`%USERPROFILE%\.docker`): +/// - writes `contexts/meta//meta.json` when missing (or when `force_context_write`), +/// - ensures `cliPluginsExtraDirs` in `config.json` includes `plugins_dir` (preserving logins, +/// credential helpers, aliases, and other plugin dirs), and +/// - sets `currentContext` to `ours` when `force_use` is set, when `currentContext` names a +/// non-existent context (such as a removed `desktop-linux`), when `currentContext` is empty and +/// `set_current_if_empty` is set, or when `config.json` was missing and Docker Desktop is not +/// installed (#984). +#[cfg_attr(not(any(windows, test)), allow(dead_code))] +pub fn repair_windows_config(dir: &Path, opts: WindowsRepairOpts<'_>) -> io::Result { + let config_path = dir.join("config.json"); + let config_existed = config_path.exists(); + let mut cfg = read_json(&config_path)?; + if !cfg.is_object() { + return Err(io::Error::new(io::ErrorKind::InvalidData, format!("{}: not a JSON object", config_path.display()))); + } + let mut out = WindowsRepair::default(); + let meta = context_meta(dir, opts.ours); + if opts.force_context_write || !meta.join("meta.json").is_file() { + write_context(&meta, opts.ours, opts.description, opts.host)?; + out.context_written = true; + } + let mut cfg_changed = false; + if let Some(plugins) = opts.plugins_dir { + let want = plugins.to_string_lossy().into_owned(); + let mut dirs: Vec = cfg.get("cliPluginsExtraDirs").and_then(Value::as_array).cloned().unwrap_or_default(); + if !dirs.iter().any(|d| d.as_str().is_some_and(|s| same_windows_dir(s, &want))) { + dirs.push(Value::String(want)); + cfg["cliPluginsExtraDirs"] = Value::Array(dirs); + out.plugins_added = true; + cfg_changed = true; + } + } + let cur = cfg.get("currentContext").and_then(Value::as_str).map(str::trim).unwrap_or("").to_owned(); + let dangling = !cur.is_empty() + && cur != "default" + && cur != opts.ours + && (!valid_name(&cur) + || !context_meta(dir, &cur).join("meta.json").is_file() + || (cur == "desktop-linux" && !opts.desktop_installed)); + let want_ours = opts.force_use + || dangling + || (cur.is_empty() && (opts.set_current_if_empty || (!config_existed && !opts.desktop_installed))); + if want_ours && cur != opts.ours { + cfg["currentContext"] = Value::String(opts.ours.to_owned()); + out.current_context_set = true; + cfg_changed = true; + } + if cfg_changed { + write_json(&config_path, &cfg)?; + } + Ok(out) +} + #[cfg(test)] mod tests { use super::*; @@ -499,6 +674,134 @@ mod tests { let _ = std::fs::remove_dir_all(&home); } + #[test] + fn sha256_hex_matches_known_vectors_and_docker_context_dir() { + assert_eq!( + sha256_hex(b""), + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + ); + assert_eq!( + sha256_hex(b"abc"), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + assert_eq!( + sha256_hex(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"), + "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" + ); + assert_eq!( + sha256_hex(b"kiri"), + "80d7688032dda428a5d1e0eea7ad434d219b770b7d3a0646fd58695e40107755" + ); + } + + #[test] + fn windows_config_repair_heals_wiped_config_plugins_and_dangling_desktop_context() { + let root = scratch_home("win-repair"); + let docker = root.join(".docker"); + let exe_dir = root.join("Kiri/bin"); + let plugins = exe_dir.join("cli-plugins"); + std::fs::create_dir_all(&plugins).unwrap(); + let exe = exe_dir.join("kiri.exe"); + std::fs::write(&exe, b"").unwrap(); + assert_eq!(find_windows_cli_plugins(Some(&exe), None).as_deref(), Some(plugins.as_path())); + + // 1. Docker Desktop uninstalled and wiped `%USERPROFILE%\.docker\config.json`: + // startup self-heal restores `kiri` context, `cliPluginsExtraDirs`, and `currentContext = "kiri"`. + let r = repair_windows_config( + &docker, + WindowsRepairOpts { + ours: "kiri", + description: "Kiri (WSL2)", + host: "npipe:////./pipe/kiri", + plugins_dir: Some(&plugins), + force_context_write: false, + set_current_if_empty: false, + force_use: false, + desktop_installed: false, + }, + ) + .unwrap(); + assert_eq!( + r, + WindowsRepair { context_written: true, plugins_added: true, current_context_set: true } + ); + let cfg = read_json(&docker.join("config.json")).unwrap(); + assert_eq!(cfg["currentContext"], "kiri"); + assert_eq!(cfg["cliPluginsExtraDirs"], json!([plugins.to_string_lossy()])); + // Idempotent on subsequent starts (no redundant writes). + let r2 = repair_windows_config( + &docker, + WindowsRepairOpts { + ours: "kiri", + description: "Kiri (WSL2)", + host: "npipe:////./pipe/kiri", + plugins_dir: Some(&plugins), + force_context_write: false, + set_current_if_empty: false, + force_use: false, + desktop_installed: false, + }, + ) + .unwrap(); + assert_eq!(r2, WindowsRepair::default()); + + // 2. Dangling `desktop-linux` context (meta removed or Docker Desktop uninstalled) is healed, + // preserving registry logins, credHelpers, and aliases. + write_json( + &docker.join("config.json"), + &json!({ + "auths": {"ghcr.io": {"auth": "c2VjcmV0"}}, + "credHelpers": {"ecr": "ecr-login"}, + "aliases": {"builder": "buildx"}, + "currentContext": "desktop-linux", + }), + ) + .unwrap(); + let r3 = repair_windows_config( + &docker, + WindowsRepairOpts { + ours: "kiri", + description: "Kiri (WSL2)", + host: "npipe:////./pipe/kiri", + plugins_dir: Some(&plugins), + force_context_write: false, + set_current_if_empty: false, + force_use: false, + desktop_installed: false, + }, + ) + .unwrap(); + assert!(r3.plugins_added && r3.current_context_set); + let after = read_json(&docker.join("config.json")).unwrap(); + assert_eq!(after["currentContext"], "kiri"); + assert_eq!(after["auths"]["ghcr.io"]["auth"], "c2VjcmV0"); + assert_eq!(after["credHelpers"]["ecr"], "ecr-login"); + assert_eq!(after["aliases"]["builder"], "buildx"); + + // 3. Corrupt config.json is never overwritten. + std::fs::write(docker.join("config.json"), "{broken").unwrap(); + assert_eq!( + repair_windows_config( + &docker, + WindowsRepairOpts { + ours: "kiri", + description: "Kiri (WSL2)", + host: "npipe:////./pipe/kiri", + plugins_dir: Some(&plugins), + force_context_write: true, + set_current_if_empty: true, + force_use: true, + desktop_installed: false, + }, + ) + .unwrap_err() + .kind(), + io::ErrorKind::InvalidData + ); + assert_eq!(std::fs::read_to_string(docker.join("config.json")).unwrap(), "{broken"); + let _ = std::fs::remove_dir_all(&root); + } + #[cfg(unix)] #[test] fn sock_at_detects_kiri_taken_and_free() { diff --git a/crates/kiri/src/domains_cli.rs b/crates/kiri/src/domains_cli.rs index 2f6f613..a077c0b 100644 --- a/crates/kiri/src/domains_cli.rs +++ b/crates/kiri/src/domains_cli.rs @@ -81,6 +81,12 @@ pub fn run(args: &[String]) -> io::Result<()> { } fn run_with(args: &[String], alive: impl FnOnce() -> bool) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } let json = args.iter().any(|a| a == "--json"); let args: Vec = args.iter().filter(|a| *a != "--json").cloned().collect(); let cmd = parse(&args).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; @@ -147,6 +153,13 @@ mod tests { assert_eq!(format(&moved), "HTTP 18780 on, a container has the port for now (set by KIRI_HTTP_PORT)\nHTTPS 18743 on\n"); } + #[test] + fn help_succeeds_without_touching_the_socket() { + for h in ["--help", "-h", "help", "set --help", "reset -h"] { + run_with(&args(h), || panic!("help must not check daemon: {h}")).unwrap(); + } + } + #[test] fn bad_arguments_fail_before_touching_the_socket() { for bad in ["set --http nope", "set --http 0", "set --https 70000", "set --http", "set", "set --port 80", "reset now", "show", "--unknown", "--json show"] { diff --git a/crates/kiri/src/hostaccess.rs b/crates/kiri/src/hostaccess.rs index e847d83..01cbc08 100644 --- a/crates/kiri/src/hostaccess.rs +++ b/crates/kiri/src/hostaccess.rs @@ -127,12 +127,23 @@ fn run_with( } } +const USAGE: &str = "usage: kiri host-access [--restart] USER"; + pub fn run(args: &[String]) -> io::Result { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(0); + } let (restart, args) = match args { [flag, rest @ ..] if flag == "--restart" => (true, rest), _ => (false, args), }; - let [user] = args else { return Err(io::Error::other("usage: kiri host-access [--restart] USER")) }; + let [user] = args else { return Err(io::Error::other(USAGE)) }; + if user.starts_with('-') { + return Err(io::Error::other(USAGE)); + } // SAFETY: geteuid has no preconditions. if unsafe { libc::geteuid() } != 0 { return Err(io::Error::other(format!("needs root: sudo kiri host-access {}{user}", if restart { "--restart " } else { "" }))); diff --git a/crates/kiri/src/images.rs b/crates/kiri/src/images.rs index 0c9ef1b..9973df8 100644 --- a/crates/kiri/src/images.rs +++ b/crates/kiri/src/images.rs @@ -15,7 +15,15 @@ fn invalid(msg: impl Into) -> io::Error { } pub fn pull(args: &[String]) -> io::Result<()> { - let name = args.first().ok_or_else(|| invalid("usage: kiri raw pull "))?; + const USAGE: &str = "usage: kiri raw pull "; + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) { + println!("{USAGE}"); + return Ok(()); + } + if args.len() != 1 || args[0].starts_with('-') { + return Err(invalid(USAGE)); + } + let name = &args[0]; let reference = Reference::parse(name).map_err(|e| invalid(e.to_string()))?; let store = store()?; let platform = Platform::host_linux(); @@ -54,7 +62,15 @@ pub fn pull(args: &[String]) -> io::Result<()> { Ok(()) } -pub fn list(_args: &[String]) -> io::Result<()> { +pub fn list(args: &[String]) -> io::Result<()> { + const USAGE: &str = "usage: kiri raw images"; + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) { + println!("{USAGE}"); + return Ok(()); + } + if !args.is_empty() { + return Err(invalid(USAGE)); + } let mut images = store()?.images()?; images.sort_by(|a, b| a.name.cmp(&b.name)); let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); @@ -74,8 +90,13 @@ pub fn list(_args: &[String]) -> io::Result<()> { } pub fn remove(args: &[String]) -> io::Result<()> { - if args.is_empty() { - return Err(invalid("usage: kiri raw rmi ...")); + const USAGE: &str = "usage: kiri raw rmi ..."; + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) { + println!("{USAGE}"); + return Ok(()); + } + if args.is_empty() || args.iter().any(|a| a.starts_with('-')) { + return Err(invalid(USAGE)); } let store = store()?; for name in args { diff --git a/crates/kiri/src/import.rs b/crates/kiri/src/import.rs index 754332c..097f166 100644 --- a/crates/kiri/src/import.rs +++ b/crates/kiri/src/import.rs @@ -34,6 +34,7 @@ fn cli() -> io::Result { let mut cmd = Command::new(docker()?); #[cfg(windows)] std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); + cmd.env_remove("DOCKER_HOST").env_remove("DOCKER_CONTEXT"); Ok(cmd) } @@ -1698,13 +1699,28 @@ fn pick(given: Option<&str>, answers: impl Fn(&str) -> bool) -> io::Result<&'sta } const KINDS: [&str; 3] = ["image", "volume", "container"]; -const USAGE: &str = "usage: kiri import [orbstack|desktop-linux] [--list | [--force] [image|volume|container NAME]]"; +#[cfg(windows)] +const USAGE: &str = "usage: kiri import [desktop-linux] [--images] [--volumes] [--containers] [--list | [--force] [image|volume|container NAME]]"; +#[cfg(not(windows))] +const USAGE: &str = "usage: kiri import [orbstack|desktop-linux] [--images] [--volumes] [--containers] [--list | [--force] [image|volume|container NAME]]"; + +/// Which resource kinds a bulk `kiri import` or `kiri import --list` includes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct KindFilter { + images: bool, + volumes: bool, + containers: bool, +} + +impl KindFilter { + const ALL: Self = Self { images: true, volumes: true, containers: true }; +} /// What `kiri import` was asked to do. #[derive(Debug, PartialEq)] enum Ask<'a> { - Everything, - List, + Everything(KindFilter), + List(KindFilter), One(&'a str, &'a str), } @@ -1715,38 +1731,80 @@ enum Ask<'a> { fn parse<'a>(args: &[&'a str]) -> io::Result<(Option<&'a str>, Ask<'a>, bool)> { let usage = || io::Error::other(USAGE); let (mut list, mut force) = (false, false); + let (mut f_images, mut f_volumes, mut f_containers) = (false, false, false); let mut words = Vec::new(); for a in args { match *a { "--list" => list = true, "--force" => force = true, + "--images" => f_images = true, + "--volumes" => f_volumes = true, + "--containers" => f_containers = true, f if f.starts_with('-') => return Err(usage()), w => words.push(w), } } + let explicit_filter = f_images || f_volumes || f_containers; + let filter = if explicit_filter { + KindFilter { images: f_images, volumes: f_volumes, containers: f_containers } + } else { + KindFilter::ALL + }; let (given, rest) = match words.split_first() { Some((first, rest)) if !KINDS.contains(first) => (Some(*first), rest), _ => (None, &words[..]), }; let ask = match (rest, list) { - ([], false) => Ask::Everything, - ([], true) if !force => Ask::List, - ([kind, name], false) if KINDS.contains(kind) => Ask::One(kind, name), + ([], false) => Ask::Everything(filter), + ([], true) if !force => Ask::List(filter), + ([kind, name], false) if !explicit_filter && KINDS.contains(kind) => Ask::One(kind, name), _ => return Err(usage()), }; Ok((given, ask, force)) } -/// `kiri import [orbstack|desktop-linux] [--list | [--force] [image|volume|container NAME]]`: +#[cfg(windows)] +fn ensure_windows_kiri_context() { + let Some(dir) = crate::dockerctx::docker_dir() else { return }; + let exe = std::env::current_exe().ok(); + let local = std::env::var_os("LOCALAPPDATA").map(PathBuf::from); + let plugins = crate::dockerctx::find_windows_cli_plugins(exe.as_deref(), local.as_deref()); + let desktop = std::env::var_os("ProgramFiles") + .is_some_and(|p| std::path::Path::new(&p).join(r"Docker\Docker\Docker Desktop.exe").is_file()); + let host = format!("npipe:{}", client::pipe().replace('\\', "/")); + let _ = crate::dockerctx::repair_windows_config( + &dir, + crate::dockerctx::WindowsRepairOpts { + ours: crate::flavor::CONTEXT.get(), + description: "Kiri (WSL2)", + host: &host, + plugins_dir: plugins.as_deref(), + force_context_write: false, + set_current_if_empty: false, + force_use: false, + desktop_installed: desktop, + }, + ); +} + +/// `kiri import [orbstack|desktop-linux] [--images] [--volumes] [--containers] [--list | [--force] [image|volume|container NAME]]`: /// one item, or every image, named volume and container Kiri lacks. +#[cfg_attr(not(any(target_os = "macos", windows)), allow(dead_code))] pub fn run(args: &[String]) -> io::Result<()> { - if args.iter().any(|a| a == "-h" || a == "--help") { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { println!("{USAGE}"); return Ok(()); } let args: Vec<&str> = args.iter().map(String::as_str).collect(); let (given, ask, force) = parse(&args)?; + #[cfg(windows)] + ensure_windows_kiri_context(); let source = pick(given, answers)?; + if !matches!(ask, Ask::List(_)) { + client::check_alive()?; + } if given.is_none() { println!("from {} ({source})", label(source)); } @@ -1760,8 +1818,11 @@ pub fn run(args: &[String]) -> io::Result<()> { } let inv = inventory(source)?; let list = |k: &str| inv[k].as_array().cloned().unwrap_or_default(); - if ask == Ask::List { - for k in ["images", "volumes", "containers"] { + if let Ask::List(filter) = ask { + for (k, on) in [("images", filter.images), ("volumes", filter.volumes), ("containers", filter.containers)] { + if !on { + continue; + } println!("{k}:"); for v in list(k) { println!(" {}{}", v["name"].as_str().unwrap_or(""), if v["have"] == true { " (already in Kiri)" } else { "" }); @@ -1769,6 +1830,7 @@ pub fn run(args: &[String]) -> io::Result<()> { } return Ok(()); } + let Ask::Everything(filter) = ask else { unreachable!() }; let mut failures: Vec<(&str, String, String)> = Vec::new(); let mut step = |what: &'static str, name: &str, r: io::Result<()>| match r { Ok(()) => println!("{what} {name}: done"), @@ -1779,23 +1841,29 @@ pub fn run(args: &[String]) -> io::Result<()> { failures.push((what, name.to_owned(), why.to_owned())); } }; - for v in list("images").iter().filter(|v| v["have"] != true) { - let n = v["name"].as_str().unwrap_or(""); - step("image", n, image(source, n)); + if filter.images { + for v in list("images").iter().filter(|v| v["have"] != true) { + let n = v["name"].as_str().unwrap_or(""); + step("image", n, image(source, n)); + } } - for v in list("volumes").iter().filter(|v| v["have"] != true && v["anonymous"] != true) { - let n = v["name"].as_str().unwrap_or(""); - step("volume", n, volume_with(source, n, force)); + if filter.volumes { + for v in list("volumes").iter().filter(|v| v["have"] != true && v["anonymous"] != true) { + let n = v["name"].as_str().unwrap_or(""); + step("volume", n, volume_with(source, n, force)); + } } - for v in list("containers") { - let n = v["name"].as_str().unwrap_or(""); - let already_had = v["have"] == true; - let already_imported = !already_had && has(crate::flavor::CONTEXT.get(), "container", n); - if let Some(why) = container_skip_reason(already_had, already_imported) { - println!("container {n}: skipped ({why})"); - continue; + if filter.containers { + for v in list("containers") { + let n = v["name"].as_str().unwrap_or(""); + let already_had = v["have"] == true; + let already_imported = !already_had && has(crate::flavor::CONTEXT.get(), "container", n); + if let Some(why) = container_skip_reason(already_had, already_imported) { + println!("container {n}: skipped ({why})"); + continue; + } + step("container", n, container_with(source, n, force, &[])); } - step("container", n, container_with(source, n, force, &[])); } if !failures.is_empty() { Err(io::Error::other(format_failures(&failures))) } else { Ok(()) } } @@ -1990,17 +2058,31 @@ mod tests { // everything"; the source may be left out before a kind. #[test] fn parses_what_to_import() { - use super::{Ask, parse}; - assert_eq!(parse(&[]).unwrap(), (None, Ask::Everything, false)); - assert_eq!(parse(&["orbstack"]).unwrap(), (Some("orbstack"), Ask::Everything, false)); - assert_eq!(parse(&["--list"]).unwrap(), (None, Ask::List, false)); - assert_eq!(parse(&["orbstack", "--list"]).unwrap(), (Some("orbstack"), Ask::List, false)); + use super::{Ask, KindFilter, parse}; + let all = KindFilter::ALL; + assert_eq!(parse(&[]).unwrap(), (None, Ask::Everything(all), false)); + assert_eq!(parse(&["orbstack"]).unwrap(), (Some("orbstack"), Ask::Everything(all), false)); + assert_eq!(parse(&["--list"]).unwrap(), (None, Ask::List(all), false)); + assert_eq!(parse(&["orbstack", "--list"]).unwrap(), (Some("orbstack"), Ask::List(all), false)); assert_eq!(parse(&["image", "nginx"]).unwrap(), (None, Ask::One("image", "nginx"), false)); assert_eq!(parse(&["desktop-linux", "volume", "pg"]).unwrap(), (Some("desktop-linux"), Ask::One("volume", "pg"), false)); // #345: --force copies volumes running containers use, one or all. assert_eq!(parse(&["orbstack", "volume", "pg", "--force"]).unwrap(), (Some("orbstack"), Ask::One("volume", "pg"), true)); assert_eq!(parse(&["--force", "container", "db"]).unwrap(), (None, Ask::One("container", "db"), true)); - assert_eq!(parse(&["orbstack", "--force"]).unwrap(), (Some("orbstack"), Ask::Everything, true)); + assert_eq!(parse(&["orbstack", "--force"]).unwrap(), (Some("orbstack"), Ask::Everything(all), true)); + // #984: --images, --volumes, --containers filter bulk import and --list. + assert_eq!( + parse(&["desktop-linux", "--images"]).unwrap(), + (Some("desktop-linux"), Ask::Everything(KindFilter { images: true, volumes: false, containers: false }), false) + ); + assert_eq!( + parse(&["--volumes", "--containers"]).unwrap(), + (None, Ask::Everything(KindFilter { images: false, volumes: true, containers: true }), false) + ); + assert_eq!( + parse(&["--list", "--containers"]).unwrap(), + (None, Ask::List(KindFilter { images: false, volumes: false, containers: true }), false) + ); for bad in [ &["orbstack", "image"][..], &["image"], @@ -2010,13 +2092,14 @@ mod tests { &["--list", "image", "nginx"], &["image", "nginx", "--list"], &["--list", "--force"], + &["--images", "image", "nginx"], // An unknown flag must not start a full import. &["--dry-run"], &["orbstack", "-l"], ] { assert!(parse(bad).unwrap_err().to_string().starts_with("usage:"), "{bad:?}"); } - assert_eq!(parse(&["podman"]).unwrap(), (Some("podman"), Ask::Everything, false)); + assert_eq!(parse(&["podman"]).unwrap(), (Some("podman"), Ask::Everything(all), false)); } // Volume helpers run only an image the engine pulled from an official diff --git a/crates/kiri/src/k8s.rs b/crates/kiri/src/k8s.rs index 7f99983..7f1eef4 100644 --- a/crates/kiri/src/k8s.rs +++ b/crates/kiri/src/k8s.rs @@ -504,6 +504,10 @@ fn ok(r: io::Result) -> io::Result { pub fn run(args: &[String]) -> io::Result<()> { let what = args.first().map(String::as_str).unwrap_or(""); + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) || what == "help" { + println!("{}", if what == "set" { USAGE_SET } else { USAGE_K8S }); + return Ok(()); + } let logged = matches!(what, "start" | "stop" | "delete" | "set"); // A recreate from the command line (`kiri k8s set`) is attributed to this // op, so the node's stop is logged as `k8s set`, not as a memory kill. A diff --git a/crates/kiri/src/machine.rs b/crates/kiri/src/machine.rs index ebede90..ec15973 100644 --- a/crates/kiri/src/machine.rs +++ b/crates/kiri/src/machine.rs @@ -35,12 +35,35 @@ fn ok(r: io::Result) -> io::Result { if r.ok() { Ok(r) } else { Err(io::Error::other(r.error())) } } +pub(crate) const USAGE: &str = "usage: kiri machine create NAME [--distro ubuntu|debian|alpine|fedora|arch|rocky|opensuse | --image IMAGE] [--systemd]\n kiri machine list [--json] | shell NAME [-- CMD...] | start | stop | restart | delete NAME"; + +/// True when `args` asks for `kiri machine`'s own help rather than passing +/// `--help` to a command inside `kiri machine shell NAME -- --help`. +pub(crate) fn wants_help(args: &[String]) -> bool { + if matches!(args.first().map(String::as_str), Some("help")) { + return true; + } + let scan_end = if args.first().map(String::as_str) == Some("shell") { + args.iter().position(|a| a == "--").unwrap_or(args.len()) + } else { + args.len() + }; + args[..scan_end].iter().any(|a| matches!(a.as_str(), "-h" | "--help")) +} + pub fn run(args: &[String]) -> io::Result<()> { + if wants_help(args) { + println!("{USAGE}"); + return Ok(()); + } + if args.is_empty() { + return Err(io::Error::other(USAGE)); + } if !client::alive() { return Err(io::Error::other("kiri daemon is not running: open Kiri.app or run `kiri daemon`")); } let name = args.get(1).map(String::as_str).unwrap_or_default(); - let need_name = || if name.is_empty() { Err(io::Error::other("name a machine")) } else { Ok(()) }; + let need_name = || if name.is_empty() || name.starts_with('-') { Err(io::Error::other("name a machine")) } else { Ok(()) }; match args.first().map(String::as_str) { Some("create") => { need_name()?; @@ -69,9 +92,7 @@ pub fn run(args: &[String]) -> io::Result<()> { println!("deleted machine {name}"); Ok(()) } - _ => Err(io::Error::other( - "usage: kiri machine create NAME [--distro ubuntu|debian|alpine|fedora|arch|rocky|opensuse | --image IMAGE] [--systemd]\n kiri machine list [--json] | shell NAME [-- CMD...] | start | stop | restart | delete NAME", - )), + _ => Err(io::Error::other(USAGE)), } } @@ -565,6 +586,20 @@ mod tests { } } + #[test] + fn wants_help_stops_at_double_dash_for_shell_commands() { + let s = |v: &[&str]| v.iter().map(|x| (*x).to_owned()).collect::>(); + assert!(super::wants_help(&s(&["--help"]))); + assert!(super::wants_help(&s(&["-h"]))); + assert!(super::wants_help(&s(&["help"]))); + assert!(super::wants_help(&s(&["create", "--help"]))); + assert!(super::wants_help(&s(&["shell", "--help"]))); + assert!(super::wants_help(&s(&["shell", "dev", "-h"]))); + assert!(!super::wants_help(&s(&["shell", "dev", "--", "ls", "--help"]))); + assert!(!super::wants_help(&s(&["shell", "dev", "--", "-h"]))); + assert!(!super::wants_help(&s(&[]))); + } + #[test] fn list_json_has_each_machines_name_image_and_state() { let rows = json!([{"Labels": {(super::LABEL): "dev"}, "Image": "ubuntu:24.04", "State": "running", "Status": "Up 2 hours"}]); diff --git a/crates/kiri/src/main.rs b/crates/kiri/src/main.rs index 064ca66..be25bd2 100644 --- a/crates/kiri/src/main.rs +++ b/crates/kiri/src/main.rs @@ -13,7 +13,7 @@ mod boot; // builds, cli_pins, scan and tools on Linux too: the daemon reads an // image's layers and scans it for kiri-win, whose window can't reach the // store inside WSL (daemon/api.rs). -#[cfg(unix)] +#[cfg(any(unix, windows))] #[cfg_attr(not(target_os = "macos"), allow(dead_code))] mod builds; // The engine stops when its app is deleted under it (kiri-win includes it @@ -21,7 +21,7 @@ mod builds; #[cfg(unix)] mod appwatch; // Which builder plain `docker build` uses: Docker's or Kiri's. -#[cfg(unix)] +#[cfg(any(unix, windows))] #[cfg_attr(not(target_os = "macos"), allow(dead_code))] mod buildwith; // Linux only, but its tests run anywhere with unix sockets. @@ -33,15 +33,23 @@ mod bridge; mod hostrelay; #[cfg(unix)] mod cli_pins; -#[cfg(unix)] +#[cfg(any(unix, windows))] mod client; #[cfg(unix)] mod daemon; +#[cfg(windows)] +#[path = "daemon/time.rs"] +#[allow(dead_code)] +mod daemon_time; +#[cfg(windows)] +mod daemon { + pub(crate) use super::daemon_time as time; +} #[cfg(unix)] mod diag; #[cfg(any(unix, windows))] mod docker; -#[cfg(any(target_os = "macos", all(target_os = "linux", feature = "window"), test))] +#[cfg(any(target_os = "macos", all(target_os = "linux", feature = "window"), windows, test))] #[cfg_attr(not(any(target_os = "macos", all(target_os = "linux", feature = "window"))), allow(dead_code))] mod dockerctx; // `kiri doctor`: whether this installation works (Windows: docker here, the engine in WSL). @@ -51,12 +59,14 @@ mod doctor; #[cfg(unix)] mod domains_cli; mod flavor; +#[cfg(unix)] mod images; #[cfg(unix)] mod guest; #[cfg(target_os = "linux")] mod hostaccess; -#[cfg(target_os = "macos")] +#[cfg(any(target_os = "macos", windows))] +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] mod import; #[cfg(unix)] mod k8s; @@ -77,6 +87,8 @@ mod scan; mod scan_cli; #[cfg(target_os = "macos")] mod setup; +#[cfg(any(windows, test))] +mod setup_win; #[cfg(unix)] mod usb; #[cfg(unix)] @@ -109,8 +121,10 @@ const USAGE_LINES: &[&str] = &[ " kiri ui [--start] [--view containers|images|volumes|networks|builds]", #[cfg(target_os = "macos")] " kiri setup [--use] [--no-agent] [--no-profiles] | kiri setup --uninstall", - #[cfg(unix)] - " kiri build-with [docker|kiri] which builder docker build uses", + #[cfg(windows)] + " kiri setup [--use] ensure Kiri's docker context and CLI plugins in ~/.docker", + #[cfg(any(unix, windows))] + " kiri build-with [docker|kiri|status] which builder docker build uses", " kiri domains [set [--http N] [--https N] | reset] the *.kiri.local routers' ports", " kiri storage [status | reclaim] storage location, disk usage, and reclaiming VM disk space", " kiri registry [insecure|mirror] [list | add X... | remove X...] daemon.json's insecure registries and Docker Hub mirrors", @@ -130,7 +144,9 @@ const USAGE_LINES: &[&str] = &[ #[cfg(target_os = "macos")] " kiri vm [status | set --shared-nat on|off] VM networking (off avoids macOS InternetSharing)", #[cfg(target_os = "macos")] - " kiri import [orbstack | desktop-linux] [--list | [--force] [image|volume|container NAME]]", + " kiri import [orbstack | desktop-linux] [--images] [--volumes] [--containers] [--list | [--force] [image|volume|container NAME]]", + #[cfg(windows)] + " kiri import [desktop-linux] [--images] [--volumes] [--containers] [--list | [--force] [image|volume|container NAME]]", #[cfg(target_os = "macos")] " kiri bench [--runs N] [--image IMAGE] [--network none|bridge]", #[cfg(target_os = "macos")] @@ -148,19 +164,56 @@ fn usage() -> String { #[cfg(any(windows, test))] const WINDOWS_DAEMON_ERROR: &str = "on Windows, Kiri's engine runs in WSL without `kiri daemon`: run `kiri start` or open Kiri"; +const START_USAGE: &str = "usage: kiri start start Kiri after a Stop (the window's Start)"; +#[cfg(unix)] +const DAEMON_USAGE: &str = "usage: kiri daemon"; +#[cfg(unix)] +const RAW_USAGE: &str = "usage: kiri raw run [--rm] [-e KEY=VALUE]... [-u USER] [-w DIR] [--timings] IMAGE [COMMAND...]\n kiri raw pull | raw images | raw rmi ..."; +#[cfg(any(target_os = "macos", target_os = "linux", test))] +const UI_USAGE: &str = "usage: kiri ui [--start] [--view containers|images|volumes|networks|builds]"; + +#[cfg(any(target_os = "macos", target_os = "linux", test))] +fn parse_ui_args(rest: &[String]) -> std::io::Result)>> { + if rest.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(rest.first().map(String::as_str), Some("help")) + { + return Ok(None); + } + let mut start = false; + let mut view = None; + let mut it = rest.iter(); + while let Some(a) = it.next() { + match a.as_str() { + "--start" => start = true, + "--view" => { + let v = it + .next() + .filter(|s| !s.is_empty() && !s.starts_with('-')) + .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, UI_USAGE))?; + view = Some(v.clone()); + } + _ => return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, UI_USAGE)), + } + } + Ok(Some((start, view))) +} + #[derive(Debug, PartialEq, Eq)] enum Command<'a> { - #[cfg(unix)] + Help, + Version, Daemon(&'a [String]), - #[cfg(windows)] - Daemon, #[cfg(target_os = "linux")] Bridge(&'a [String]), #[cfg(target_os = "linux")] - HostRelay, + HostRelay(&'a [String]), #[cfg(target_os = "linux")] HostAccess(&'a [String]), #[cfg(unix)] + RawHelp, + #[cfg(unix)] + RawInvalid, + #[cfg(unix)] RawRun(&'a [String]), #[cfg(unix)] RawPull(&'a [String]), @@ -172,15 +225,12 @@ enum Command<'a> { Bench(&'a [String]), #[cfg(target_os = "macos")] Boot(&'a [String]), - #[cfg(target_os = "macos")] + #[cfg(any(target_os = "macos", windows))] Setup(&'a [String]), #[cfg(any(unix, windows))] Share(&'a [String]), - #[cfg(unix)] - Start, - #[cfg(windows)] Start(&'a [String]), - #[cfg(unix)] + #[cfg(any(unix, windows))] BuildWith(&'a [String]), #[cfg(unix)] Domains(&'a [String]), @@ -198,7 +248,7 @@ enum Command<'a> { Machine(&'a [String]), #[cfg(unix)] Usb(&'a [String]), - #[cfg(target_os = "macos")] + #[cfg(any(target_os = "macos", windows))] Import(&'a [String]), #[cfg(target_os = "macos")] Vm(&'a [String]), @@ -217,14 +267,13 @@ enum Command<'a> { impl<'a> Command<'a> { fn parse(args: &'a [String]) -> Option> { match args.first().map(String::as_str) { - #[cfg(unix)] + Some("-h" | "--help" | "help") => Some(Command::Help), + Some("--version" | "-V" | "-v") if args.len() == 1 => Some(Command::Version), Some("daemon") => Some(Command::Daemon(&args[1..])), - #[cfg(windows)] - Some("daemon") => Some(Command::Daemon), #[cfg(target_os = "linux")] Some("bridge") => Some(Command::Bridge(&args[1..])), #[cfg(target_os = "linux")] - Some("hostrelay") => Some(Command::HostRelay), + Some("hostrelay") => Some(Command::HostRelay(&args[1..])), #[cfg(target_os = "linux")] Some("host-access") => Some(Command::HostAccess(&args[1..])), #[cfg(unix)] @@ -233,26 +282,27 @@ impl<'a> Command<'a> { Some("pull") => Some(Command::RawPull(&args[2..])), Some("images") => Some(Command::RawImages(&args[2..])), Some("rmi") => Some(Command::RawRmi(&args[2..])), - _ => None, + Some("-h" | "--help" | "help") => Some(Command::RawHelp), + _ => Some(Command::RawInvalid), }, #[cfg(target_os = "macos")] Some("bench") => Some(Command::Bench(&args[1..])), #[cfg(target_os = "macos")] Some("boot") => Some(Command::Boot(&args[1..])), - #[cfg(target_os = "macos")] + #[cfg(any(target_os = "macos", windows))] Some("setup") => Some(Command::Setup(&args[1..])), #[cfg(any(unix, windows))] Some("share") => Some(Command::Share(&args[1..])), // `kiri 3000`: share a port straight away. #[cfg(any(unix, windows))] Some(a) if share::is_shorthand(a) => Some(Command::Share(args)), - // Bare: the window's Start (`kiri start NAME` is docker's start). + // Bare (or `-h`/`--help`): the window's Start (`kiri start NAME` is docker's start). #[cfg(unix)] - Some("start") if args.len() == 1 => Some(Command::Start), + Some("start") if args[1..].iter().all(|a| matches!(a.as_str(), "-h" | "--help")) => Some(Command::Start(&args[1..])), // On Windows, by the `kiri` in WSL, once kiri-start has the daemon up. #[cfg(windows)] - Some("start") if args.len() == 1 => Some(Command::Start(args)), - #[cfg(unix)] + Some("start") if args[1..].iter().all(|a| matches!(a.as_str(), "-h" | "--help")) => Some(Command::Start(args)), + #[cfg(any(unix, windows))] Some("build-with") => Some(Command::BuildWith(&args[1..])), #[cfg(unix)] Some("domains") => Some(Command::Domains(&args[1..])), @@ -270,7 +320,7 @@ impl<'a> Command<'a> { Some("machine") => Some(Command::Machine(&args[1..])), #[cfg(unix)] Some("usb") => Some(Command::Usb(&args[1..])), - #[cfg(target_os = "macos")] + #[cfg(any(target_os = "macos", windows))] Some("import") => Some(Command::Import(&args[1..])), #[cfg(target_os = "macos")] Some("vm") => Some(Command::Vm(&args[1..])), @@ -293,27 +343,76 @@ impl<'a> Command<'a> { fn main() -> ExitCode { flavor::init(); let args: Vec = std::env::args().skip(1).collect(); + let parsed = Command::parse(&args); + match parsed { + Some(Command::Help) => { + println!("{}", usage()); + return ExitCode::SUCCESS; + } + Some(Command::Version) => { + println!("kiri {}", env!("CARGO_PKG_VERSION")); + return ExitCode::SUCCESS; + } + _ => {} + } // Which process this is, for its log and crash reports. #[cfg(unix)] - diag::init(match args.first().map(String::as_str) { - Some("daemon") => diag::Part::Daemon, - // Only a build with the window: elsewhere `kiri ui` is a plain - // command whose message must reach the terminal, not the log's pipe. - #[cfg(any(target_os = "macos", all(target_os = "linux", feature = "window")))] - Some("ui") => diag::Part::Ui, - #[cfg(target_os = "macos")] - None if setup::launched_from_app() => diag::Part::Ui, - _ => diag::Part::Cli, - }); - let result: std::io::Result<()> = match Command::parse(&args) { + { + let asking_help = args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.get(1).map(String::as_str), Some("help")); + diag::init(match args.first().map(String::as_str) { + Some("daemon") if !asking_help && args.len() == 1 => diag::Part::Daemon, + // Only a build with the window: elsewhere `kiri ui` is a plain + // command whose message must reach the terminal, not the log's pipe. + #[cfg(any(target_os = "macos", all(target_os = "linux", feature = "window")))] + Some("ui") if !asking_help => diag::Part::Ui, + #[cfg(target_os = "macos")] + None if setup::launched_from_app() => diag::Part::Ui, + _ => diag::Part::Cli, + }); + } + let result: std::io::Result<()> = match parsed { + Some(Command::Help | Command::Version) => unreachable!(), #[cfg(unix)] - Some(Command::Daemon(rest)) => daemon::run(rest), + Some(Command::Daemon(rest)) => { + if rest.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(rest.first().map(String::as_str), Some("help")) + { + println!("{DAEMON_USAGE}"); + Ok(()) + } else if !rest.is_empty() { + Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, DAEMON_USAGE)) + } else { + daemon::run(rest) + } + } #[cfg(windows)] - Some(Command::Daemon) => Err(std::io::Error::other(WINDOWS_DAEMON_ERROR)), + Some(Command::Daemon(rest)) => { + if rest.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(rest.first().map(String::as_str), Some("help")) + { + println!("{START_USAGE}"); + Ok(()) + } else { + Err(std::io::Error::other(WINDOWS_DAEMON_ERROR)) + } + } #[cfg(target_os = "linux")] Some(Command::Bridge(rest)) => bridge::run(rest), #[cfg(target_os = "linux")] - Some(Command::HostRelay) => hostrelay::run(), + Some(Command::HostRelay(rest)) => { + const HOSTRELAY_USAGE: &str = "usage: kiri hostrelay"; + if rest.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(rest.first().map(String::as_str), Some("help")) + { + println!("{HOSTRELAY_USAGE}"); + Ok(()) + } else if !rest.is_empty() { + Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, HOSTRELAY_USAGE)) + } else { + hostrelay::run() + } + } // Linux hosts: what the window's onboarding needs root for (through pkexec). #[cfg(target_os = "linux")] Some(Command::HostAccess(rest)) => match hostaccess::run(rest) { @@ -321,6 +420,13 @@ fn main() -> ExitCode { Err(e) => Err(e), }, #[cfg(unix)] + Some(Command::RawHelp) => { + println!("{RAW_USAGE}"); + Ok(()) + } + #[cfg(unix)] + Some(Command::RawInvalid) => Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, RAW_USAGE)), + #[cfg(unix)] Some(Command::RawRun(rest)) => run::run(rest), #[cfg(unix)] Some(Command::RawPull(rest)) => images::pull(rest), @@ -334,13 +440,22 @@ fn main() -> ExitCode { Some(Command::Boot(rest)) => boot::run(rest), #[cfg(target_os = "macos")] Some(Command::Setup(rest)) => setup::run(rest), + #[cfg(windows)] + Some(Command::Setup(rest)) => setup_win::run(rest), #[cfg(any(unix, windows))] Some(Command::Share(rest)) => share::run(rest), #[cfg(unix)] - Some(Command::Start) => engine_start(), + Some(Command::Start(rest)) => { + if !rest.is_empty() { + println!("{START_USAGE}"); + Ok(()) + } else { + engine_start() + } + } #[cfg(windows)] Some(Command::Start(all)) => wsl::run(all), - #[cfg(unix)] + #[cfg(any(unix, windows))] Some(Command::BuildWith(rest)) => buildwith::cli(rest), #[cfg(unix)] Some(Command::Domains(rest)) => domains_cli::run(rest), @@ -358,7 +473,7 @@ fn main() -> ExitCode { Some(Command::Machine(rest)) => machine::run(rest), #[cfg(unix)] Some(Command::Usb(rest)) => usb::run(rest), - #[cfg(target_os = "macos")] + #[cfg(any(target_os = "macos", windows))] Some(Command::Import(rest)) => import::run(rest), #[cfg(target_os = "macos")] Some(Command::Vm(rest)) => vm_cli::run(rest), @@ -367,13 +482,24 @@ fn main() -> ExitCode { #[cfg(unix)] Some(Command::Diag(rest)) => diag::run(rest), #[cfg(any(target_os = "macos", all(target_os = "linux", feature = "window")))] - Some(Command::Ui(all)) => ui::run( - all.iter().any(|a| a == "--start"), - all.iter().position(|a| a == "--view").and_then(|i| all.get(i + 1)).cloned(), - ), + Some(Command::Ui(all)) => match parse_ui_args(&all[1..]) { + Ok(None) => { + println!("{UI_USAGE}"); + Ok(()) + } + Ok(Some((start, view))) => ui::run(start, view), + Err(e) => Err(e), + }, // The static engine has no window: the package's own build of it. #[cfg(all(target_os = "linux", not(feature = "window")))] - Some(Command::Ui(all)) => window(all), + Some(Command::Ui(all)) => match parse_ui_args(&all[1..]) { + Ok(None) => { + println!("{UI_USAGE}"); + Ok(()) + } + Ok(Some(_)) => window(all), + Err(e) => Err(e), + }, #[cfg(any(unix, windows))] Some(Command::Docker(all)) => { engine_version_check(); @@ -545,7 +671,14 @@ mod tests { } #[cfg(windows)] { - for unix_or_mac in ["daemon", "bridge", "ui", "setup", "build-with", "update", "vm", "import", "bench", "boot", "raw"] { + for win_cmd in ["setup", "build-with", "import"] { + assert!(cmds.contains(&win_cmd), "Windows help missing `{win_cmd}`:\n{help}"); + } + assert!( + help.contains("kiri import [desktop-linux] [--images] [--volumes] [--containers]"), + "Windows help missing `kiri import [desktop-linux] [--images] [--volumes] [--containers]`:\n{help}" + ); + for unix_or_mac in ["daemon", "bridge", "ui", "update", "vm", "bench", "boot", "raw"] { assert!(!cmds.contains(&unix_or_mac), "Windows help must not list `{unix_or_mac}`:\n{help}"); } } @@ -596,8 +729,28 @@ mod tests { } } assert!(count > 0); - assert!(parse(&["--help"]).is_none()); - assert!(parse(&["-h"]).is_none()); + for h in ["--help", "-h", "help"] { + assert_eq!(Command::parse(&[h.to_owned()]), Some(Command::Help), "{h}"); + } + for v in ["--version", "-V", "-v"] { + assert_eq!(Command::parse(&[v.to_owned()]), Some(Command::Version), "{v}"); + } + // `kiri version` (without leading dash) remains Docker's `version` passthrough. + assert!(matches!(Command::parse(&["version".to_owned()]), Some(Command::Docker(_)))); + // `kiri start --help` / `-h` dispatches to Kiri's Start, while `kiri start web --help` stays Docker's. + assert!(matches!(Command::parse(&["start".to_owned(), "--help".to_owned()]), Some(Command::Start(_)))); + assert!(matches!(Command::parse(&["start".to_owned(), "-h".to_owned()]), Some(Command::Start(_)))); + assert!(matches!(Command::parse(&["start".to_owned(), "web".to_owned(), "--help".to_owned()]), Some(Command::Docker(_)))); + assert!(matches!(Command::parse(&["run".to_owned(), "alpine".to_owned(), "--help".to_owned()]), Some(Command::Docker(_)))); + assert!(matches!(Command::parse(&["ps".to_owned(), "--help".to_owned()]), Some(Command::Docker(_)))); + + #[cfg(unix)] + { + assert_eq!(Command::parse(&["raw".to_owned(), "--help".to_owned()]), Some(Command::RawHelp)); + assert_eq!(Command::parse(&["raw".to_owned(), "-h".to_owned()]), Some(Command::RawHelp)); + assert_eq!(Command::parse(&["raw".to_owned()]), Some(Command::RawInvalid)); + } + #[cfg(any(target_os = "macos", target_os = "linux"))] for args in [ vec!["update".to_owned()], @@ -617,15 +770,153 @@ mod tests { } #[cfg(windows)] { - for unix_cmd in ["bridge", "ui", "setup", "build-with", "vm", "import", "bench", "boot", "raw"] { + for unix_cmd in ["bridge", "ui", "vm", "bench", "boot", "raw"] { assert!(parse(&[unix_cmd]).is_none(), "`kiri {unix_cmd}` should not dispatch on Windows"); } + for win_cmd in ["setup", "build-with", "import"] { + assert!(parse(&[win_cmd]).is_some(), "`kiri {win_cmd}` must dispatch on Windows"); + } let daemon_args = ["daemon".to_owned()]; - assert_eq!(Command::parse(&daemon_args), Some(Command::Daemon)); + assert_eq!(Command::parse(&daemon_args), Some(Command::Daemon(&[]))); } assert_eq!( super::WINDOWS_DAEMON_ERROR, "on Windows, Kiri's engine runs in WSL without `kiri daemon`: run `kiri start` or open Kiri" ); } + + #[test] + fn parse_ui_args_handles_help_views_and_invalid_flags() { + let s = |v: &[&str]| v.iter().map(|x| (*x).to_owned()).collect::>(); + assert_eq!(super::parse_ui_args(&s(&["--help"])).unwrap(), None); + assert_eq!(super::parse_ui_args(&s(&["-h"])).unwrap(), None); + assert_eq!(super::parse_ui_args(&s(&["--start", "--help"])).unwrap(), None); + assert_eq!(super::parse_ui_args(&s(&[])).unwrap(), Some((false, None))); + assert_eq!( + super::parse_ui_args(&s(&["--start", "--view", "containers"])).unwrap(), + Some((true, Some("containers".into()))) + ); + assert!(super::parse_ui_args(&s(&["--view"])).is_err()); + assert!(super::parse_ui_args(&s(&["--bogus"])).is_err()); + } + + #[test] + fn cli_help_and_version_exit_zero_on_stdout_without_side_effects() { + let Some(bin) = option_env!("CARGO_BIN_EXE_kiri").map(std::path::PathBuf::from).or_else(|| { + // In `cargo test --bin kiri`, the `kiri` binary sits in the parent of `deps/`. + let test_exe = std::env::current_exe().ok()?; + let dir = test_exe.parent()?.parent()?; + let name = if cfg!(windows) { "kiri.exe" } else { "kiri" }; + Some(dir.join(name)).filter(|p| p.is_file()) + }) else { + return; + }; + let run_kiri = |args: &[&str]| { + std::process::Command::new(&bin) + .args(args) + .env("KIRI_SOCKET", "/nonexistent/kiri-test.sock") + .output() + .expect("spawn kiri") + }; + + // Bare `kiri` prints usage to stderr and exits 1. + let bare = run_kiri(&[]); + assert!(!bare.status.success()); + assert!(bare.stdout.is_empty()); + assert!(String::from_utf8_lossy(&bare.stderr).starts_with("usage: kiri COMMAND")); + + // Top-level help flags print usage to stdout and exit 0. + for flag in ["--help", "-h", "help"] { + let out = run_kiri(&[flag]); + assert!(out.status.success(), "`kiri {flag}` failed: {:?}", String::from_utf8_lossy(&out.stderr)); + assert!(out.stderr.is_empty(), "`kiri {flag}` wrote stderr: {:?}", String::from_utf8_lossy(&out.stderr)); + assert_eq!(String::from_utf8_lossy(&out.stdout).trim_end(), usage()); + } + + // Top-level version flags print `kiri ` to stdout and exit 0. + for flag in ["--version", "-V", "-v"] { + let out = run_kiri(&[flag]); + assert!(out.status.success(), "`kiri {flag}` failed"); + assert!(out.stderr.is_empty()); + assert_eq!(String::from_utf8_lossy(&out.stdout), format!("kiri {}\n", env!("CARGO_PKG_VERSION"))); + } + + // Every Kiri subcommand prints usage to stdout and exits 0 on `--help` and `-h` with zero side effects. + let mut subcommands: Vec<&[&str]> = vec![ + &["daemon"], + &["start"], + &["share"], + &["3000"], + &["build-with"], + &["domains"], + &["doctor"], + &["storage"], + &["storage", "reclaim"], + &["registry"], + &["registry", "insecure"], + &["scan"], + &["k8s"], + &["k8s", "set"], + &["machine"], + &["machine", "create"], + &["machine", "shell"], + &["usb"], + &["usb", "attach"], + &["diag"], + &["diag", "logs"], + &["diag", "report"], + ]; + #[cfg(any(target_os = "macos", target_os = "linux"))] + { + subcommands.extend([&["ui"][..], &["update"]]); + } + #[cfg(unix)] + { + subcommands.extend([ + &["raw"][..], + &["raw", "run"], + &["raw", "pull"], + &["raw", "images"], + &["raw", "rmi"], + ]); + } + #[cfg(any(target_os = "macos", windows))] + { + subcommands.extend([&["setup"][..], &["import"]]); + } + #[cfg(target_os = "macos")] + { + subcommands.extend([&["vm"][..], &["vm", "set"], &["bench"], &["boot"]]); + } + #[cfg(target_os = "linux")] + { + subcommands.extend([&["bridge"][..], &["hostrelay"], &["host-access"]]); + } + for sub in subcommands { + for flag in ["--help", "-h"] { + let mut argv: Vec<&str> = sub.to_vec(); + argv.push(flag); + let out = run_kiri(&argv); + assert!( + out.status.success(), + "`kiri {}` exited {:?}, stderr: {}", + argv.join(" "), + out.status.code(), + String::from_utf8_lossy(&out.stderr) + ); + assert!( + out.stderr.is_empty(), + "`kiri {}` wrote unexpected stderr: {}", + argv.join(" "), + String::from_utf8_lossy(&out.stderr) + ); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!( + stdout.starts_with("usage: kiri "), + "`kiri {}` stdout did not start with usage: {stdout:?}", + argv.join(" ") + ); + } + } + } } diff --git a/crates/kiri/src/registry_cli.rs b/crates/kiri/src/registry_cli.rs index 913722b..74432d1 100644 --- a/crates/kiri/src/registry_cli.rs +++ b/crates/kiri/src/registry_cli.rs @@ -37,13 +37,15 @@ const INSECURE: &str = "insecure-registries"; const MIRRORS: &str = "registry-mirrors"; pub fn run(args: &[String]) -> io::Result<()> { - let json = args.iter().any(|a| a == "--json"); - let args: Vec = args.iter().filter(|a| *a != "--json").cloned().collect(); - let arg = |i: usize| args.get(i).map(String::as_str); - if matches!(arg(0), Some("-h" | "--help" | "help")) { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { println!("{USAGE}"); return Ok(()); } + let json = args.iter().any(|a| a == "--json"); + let args: Vec = args.iter().filter(|a| *a != "--json").cloned().collect(); + let arg = |i: usize| args.get(i).map(String::as_str); if !client::alive() { return Err(io::Error::other("kiri daemon is not running: open Kiri or run `kiri daemon`")); } diff --git a/crates/kiri/src/run.rs b/crates/kiri/src/run.rs index 77a8e89..b86b2a5 100644 --- a/crates/kiri/src/run.rs +++ b/crates/kiri/src/run.rs @@ -14,7 +14,7 @@ const USAGE: &str = "usage: kiri raw run [--rm] [-e KEY=VALUE]... [-u USER] [-w Containers get their own network namespace with only loopback for now (like docker run --network none); bridged networking comes next."; -#[derive(Debug, Default)] +#[derive(Debug, Default, PartialEq, Eq)] struct Options { remove: bool, env: Vec, @@ -25,7 +25,7 @@ struct Options { command: Vec, } -fn parse(args: &[String]) -> io::Result { +fn parse(args: &[String]) -> io::Result> { let bad = |m: String| io::Error::new(io::ErrorKind::InvalidInput, format!("{m}\n\n{USAGE}")); let mut o = Options::default(); let mut it = args.iter(); @@ -43,7 +43,14 @@ fn parse(args: &[String]) -> io::Result { return Err(bad(format!("--network {v} is not supported yet; only none"))); } } - "-h" | "--help" => return Err(bad(String::new())), + "-h" | "--help" => return Ok(None), + "--" => { + if let Some(img) = it.next() { + o.image = img.clone(); + o.command = it.cloned().collect(); + } + break; + } s if s.starts_with('-') => return Err(bad(format!("unknown option {s}"))), _ => { o.image = a.clone(); @@ -55,7 +62,7 @@ fn parse(args: &[String]) -> io::Result { if o.image.is_empty() { return Err(bad("no image given".into())); } - Ok(o) + Ok(Some(o)) } /// Finds the image locally, pulling it first if needed, and holds every blob @@ -109,7 +116,10 @@ pub fn new_id() -> String { } pub fn run(args: &[String]) -> io::Result<()> { - let o = parse(args)?; + let Some(o) = parse(args)? else { + println!("{USAGE}"); + return Ok(()); + }; let t0 = Instant::now(); let store = Store::open(Store::default_root()?)?; let (image, _blob_pins) = image(&store, &o.image)?; @@ -163,3 +173,37 @@ pub fn run(args: &[String]) -> io::Result<()> { } std::process::exit(r.code); } + +#[cfg(test)] +mod tests { + use super::{Options, parse}; + + fn s(words: &[&str]) -> Vec { + words.iter().map(|w| (*w).to_owned()).collect() + } + + #[test] + fn help_before_image_returns_none_while_help_after_image_stays_in_command() { + assert_eq!(parse(&s(&["--help"])).unwrap(), None); + assert_eq!(parse(&s(&["-h"])).unwrap(), None); + assert_eq!(parse(&s(&["--rm", "--help"])).unwrap(), None); + + let with_cmd_help = parse(&s(&["--rm", "alpine:latest", "ls", "--help"])).unwrap().unwrap(); + assert!(with_cmd_help.remove); + assert_eq!(with_cmd_help.image, "alpine:latest"); + assert_eq!(with_cmd_help.command, s(&["ls", "--help"])); + + let direct_help = parse(&s(&["alpine", "--help"])).unwrap().unwrap(); + assert_eq!(direct_help.image, "alpine"); + assert_eq!(direct_help.command, s(&["--help"])); + + let double_dash = parse(&s(&["--", "alpine", "-h"])).unwrap().unwrap(); + assert_eq!( + double_dash, + Options { image: "alpine".into(), command: s(&["-h"]), ..Options::default() } + ); + + assert!(parse(&[]).is_err()); + assert!(parse(&s(&["--unknown", "alpine"])).is_err()); + } +} diff --git a/crates/kiri/src/setup.rs b/crates/kiri/src/setup.rs index 41e616d..c98c388 100644 --- a/crates/kiri/src/setup.rs +++ b/crates/kiri/src/setup.rs @@ -170,7 +170,23 @@ fn step(what: &'static str) -> impl Fn(io::Error) -> io::Error { move |e| io::Error::new(e.kind(), format!("{what}: {e}")) } +const USAGE: &str = "usage: kiri setup [--use] [--no-agent] [--no-profiles] [--no-domains]\n kiri setup --domains | --docker-socket | --uninstall"; + pub fn run(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } + for a in args { + if !matches!( + a.as_str(), + "--uninstall" | "--domains" | "--docker-socket" | "--use" | "--no-profiles" | "--no-agent" | "--no-domains" + ) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, USAGE)); + } + } let flag = |f: &str| args.iter().any(|a| a == f); if flag("--uninstall") { return uninstall(); diff --git a/crates/kiri/src/setup_win.rs b/crates/kiri/src/setup_win.rs new file mode 100644 index 0000000..4b32664 --- /dev/null +++ b/crates/kiri/src/setup_win.rs @@ -0,0 +1,310 @@ +//! `kiri setup` on Windows: ensures `%USERPROFILE%\.docker\config.json` has +//! Kiri's `cli-plugins` folder (`docker compose`, `docker buildx`), writes the +//! `kiri` Docker context (`npipe:////./pipe/kiri`), and sets `currentContext` +//! to `kiri` when `--use` is given or when `currentContext` is empty or points +//! at a removed engine such as `desktop-linux` after uninstalling Docker +//! Desktop (#984). + +#![cfg_attr(not(windows), allow(dead_code))] + +use std::io; +use std::path::{Path, PathBuf}; + +use crate::dockerctx::{ + WindowsRepair, WindowsRepairOpts, find_windows_cli_plugins, repair_windows_config, +}; + +const USAGE: &str = "usage: kiri setup [--use]"; + +fn npipe_host(pipe: &str) -> String { + format!("npipe:{}", pipe.replace('\\', "/")) +} + +/// Best-effort background self-heal of `%USERPROFILE%\.docker\config.json` and +/// Kiri's `kiri` Docker context before invoking `docker.exe --context kiri` on +/// Windows (#984). +#[cfg(windows)] +pub fn heal_quietly() { + let Some(dir) = crate::dockerctx::docker_dir() else { + return; + }; + let exe = std::env::current_exe().ok(); + let local = std::env::var_os("LOCALAPPDATA").map(PathBuf::from); + let plugins = find_windows_cli_plugins(exe.as_deref(), local.as_deref()); + let desktop = std::env::var_os("ProgramFiles").is_some_and(|p| { + Path::new(&p) + .join(r"Docker\Docker\Docker Desktop.exe") + .is_file() + }); + let host = npipe_host(&crate::client::pipe()); + let _ = repair_windows_config( + &dir, + WindowsRepairOpts { + ours: crate::flavor::CONTEXT.get(), + description: "Kiri (WSL2)", + host: &host, + plugins_dir: plugins.as_deref(), + force_context_write: false, + set_current_if_empty: false, + force_use: false, + desktop_installed: desktop, + }, + ); +} + +pub fn run(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } + let mut force_use = false; + for a in args { + match a.as_str() { + "--use" => force_use = true, + _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, USAGE)), + } + } + let dir = + crate::dockerctx::docker_dir().ok_or_else(|| io::Error::other("USERPROFILE is not set"))?; + let exe = std::env::current_exe().ok(); + let local = std::env::var_os("LOCALAPPDATA").map(PathBuf::from); + let plugins = find_windows_cli_plugins(exe.as_deref(), local.as_deref()); + let desktop = std::env::var_os("ProgramFiles").is_some_and(|p| { + Path::new(&p) + .join(r"Docker\Docker\Docker Desktop.exe") + .is_file() + }); + #[cfg(windows)] + let host = npipe_host(&crate::client::pipe()); + #[cfg(not(windows))] + let host = "npipe:////./pipe/kiri".to_owned(); + + let mut out = Vec::new(); + run_in( + &dir, + &host, + plugins.as_deref(), + force_use, + desktop, + &mut out, + )?; + print!("{}", String::from_utf8_lossy(&out)); + + #[cfg(windows)] + if crate::client::alive() { + match crate::builds::builder() { + Ok(true) => match crate::buildwith::places().map(|p| p.saved()) { + Ok(Some(crate::buildwith::With::Kiri)) => { + println!( + "docker build uses BuildKit in Kiri (builder `{}`)", + crate::builds::BUILDER + ); + } + _ => println!( + "docker build follows docker's context, and builds on Kiri when docker uses Kiri (`kiri build-with kiri` sends every build to Kiri)" + ), + }, + Ok(false) => {} + Err(e) => println!( + "docker build: the `{}` builder comes later ({e})", + crate::builds::BUILDER + ), + } + } + Ok(()) +} + +fn run_in( + dir: &Path, + host: &str, + plugins: Option<&Path>, + force_use: bool, + desktop_installed: bool, + out: &mut impl io::Write, +) -> io::Result { + let ours = crate::flavor::CONTEXT.get(); + let r = repair_windows_config( + dir, + WindowsRepairOpts { + ours, + description: "Kiri (WSL2)", + host, + plugins_dir: plugins, + force_context_write: true, + set_current_if_empty: true, + force_use, + desktop_installed, + }, + )?; + writeln!(out, "docker context `{ours}` → {host}")?; + if r.current_context_set || force_use { + writeln!( + out, + "docker now uses Kiri by default (`docker context use default` to switch back)" + )?; + } + if let Some(p) = plugins { + writeln!(out, "docker cli-plugins → {}", p.display())?; + } + Ok(r) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::dockerctx::{context_meta, read_json, write_context, write_json}; + use serde_json::json; + + fn scratch(tag: &str) -> PathBuf { + static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let d = std::env::temp_dir().join(format!( + "kiri-setup-win-{tag}-{}-{}", + std::process::id(), + SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + )); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + #[test] + fn help_and_invalid_flags_have_no_side_effects() { + for h in [&["--help"][..], &["-h"], &["help"], &["--use", "--help"]] { + let v: Vec = h.iter().map(|s| (*s).to_owned()).collect(); + run(&v).unwrap(); + } + for bad in [&["--bogus"][..], &["--uninstall"], &["extra"]] { + let v: Vec = bad.iter().map(|s| (*s).to_owned()).collect(); + let err = run(&v).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidInput); + assert_eq!(err.to_string(), USAGE); + } + } + + #[test] + fn repairs_wiped_docker_config_and_dangling_desktop_linux_context() { + let root = scratch("repair"); + let docker = root.join(".docker"); + let plugins = root.join("Kiri/bin/cli-plugins"); + std::fs::create_dir_all(&plugins).unwrap(); + + // 1. Fresh / wiped config.json after Docker Desktop uninstall: creates `kiri` context, + // registers cliPluginsExtraDirs, and sets currentContext = "kiri". + let mut out = Vec::new(); + let r = run_in( + &docker, + "npipe:////./pipe/kiri", + Some(&plugins), + false, + false, + &mut out, + ) + .unwrap(); + assert_eq!( + r, + WindowsRepair { + context_written: true, + plugins_added: true, + current_context_set: true + } + ); + let cfg = read_json(&docker.join("config.json")).unwrap(); + assert_eq!(cfg["currentContext"], "kiri"); + assert_eq!( + cfg["cliPluginsExtraDirs"], + json!([plugins.to_string_lossy()]) + ); + let meta = read_json(&context_meta(&docker, "kiri").join("meta.json")).unwrap(); + assert_eq!(meta["Endpoints"]["docker"]["Host"], "npipe:////./pipe/kiri"); + let printed = String::from_utf8(out).unwrap(); + assert!( + printed.contains("docker context `kiri` → npipe:////./pipe/kiri"), + "{printed}" + ); + assert!( + printed.contains("docker now uses Kiri by default"), + "{printed}" + ); + assert!(printed.contains("docker cli-plugins →"), "{printed}"); + + // 2. Existing config with logins and an active `desktop-linux` context while Docker Desktop + // is still installed: keeps `desktop-linux` without `--use`, switches with `--use`. + write_context( + &context_meta(&docker, "desktop-linux"), + "desktop-linux", + "Docker Desktop", + "npipe:////./pipe/dockerDesktopLinuxEngine", + ) + .unwrap(); + write_json( + &docker.join("config.json"), + &json!({ + "auths": {"ghcr.io": {"auth": "dG9rZW4="}}, + "currentContext": "desktop-linux", + }), + ) + .unwrap(); + let mut out = Vec::new(); + let r = run_in( + &docker, + "npipe:////./pipe/kiri", + Some(&plugins), + false, + true, + &mut out, + ) + .unwrap(); + assert!(!r.current_context_set); + let cfg = read_json(&docker.join("config.json")).unwrap(); + assert_eq!(cfg["currentContext"], "desktop-linux"); + assert_eq!(cfg["auths"]["ghcr.io"]["auth"], "dG9rZW4="); + assert_eq!( + cfg["cliPluginsExtraDirs"], + json!([plugins.to_string_lossy()]) + ); + + // Docker Desktop uninstalled (`desktop_installed = false`), leaving stale `desktop-linux`: + // `kiri setup` heals `currentContext` to `kiri` automatically! + let mut out = Vec::new(); + let r = run_in( + &docker, + "npipe:////./pipe/kiri", + Some(&plugins), + false, + false, + &mut out, + ) + .unwrap(); + assert!(r.current_context_set); + assert_eq!( + read_json(&docker.join("config.json")).unwrap()["currentContext"], + "kiri" + ); + + // With Docker Desktop installed and `--use`: explicitly switches to `kiri`. + write_json( + &docker.join("config.json"), + &json!({"currentContext": "desktop-linux"}), + ) + .unwrap(); + let mut out = Vec::new(); + let r = run_in( + &docker, + "npipe:////./pipe/kiri", + Some(&plugins), + true, + true, + &mut out, + ) + .unwrap(); + assert!(r.current_context_set); + assert_eq!( + read_json(&docker.join("config.json")).unwrap()["currentContext"], + "kiri" + ); + + let _ = std::fs::remove_dir_all(&root); + } +} diff --git a/crates/kiri/src/share.rs b/crates/kiri/src/share.rs index ea854e4..009faf7 100644 --- a/crates/kiri/src/share.rs +++ b/crates/kiri/src/share.rs @@ -2043,8 +2043,14 @@ fn printer(target: String) -> impl Fn(Event) + Send + Sync + 'static { } pub fn run(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } match args.first().map(String::as_str) { - None | Some("-h" | "--help" | "help") => Err(io::Error::other(USAGE)), + None => Err(io::Error::other(USAGE)), Some("login") => login_cli(&args[1..]), Some("logout") => { logout()?; diff --git a/crates/kiri/src/usb.rs b/crates/kiri/src/usb.rs index 4507f3f..6085e95 100644 --- a/crates/kiri/src/usb.rs +++ b/crates/kiri/src/usb.rs @@ -29,6 +29,12 @@ const USAGE: &str = "usage: kiri usb [list [--json]] | attach DEVICE | detach DE DEVICE is a location (0x02114000), vendor:product (1532:00d7) or part of the name"; pub fn run(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } match (args.first().map(String::as_str), args.get(1)) { // The window's own list: each device's key, name, id, state, paths… (None | Some("list" | "ls" | "--json"), _) if args.iter().any(|a| a == "--json") => list_json(), diff --git a/crates/kiri/src/wsl.rs b/crates/kiri/src/wsl.rs index 42079ab..79ffac7 100644 --- a/crates/kiri/src/wsl.rs +++ b/crates/kiri/src/wsl.rs @@ -294,8 +294,63 @@ fn wake_via_pipe(_pipe_name: &str) -> Option> { None } +/// Usage text for WSL-forwarded commands when `-h` / `--help` is passed on +/// Windows, so asking for help never wakes WSL or executes side effects (#982). +/// For `kiri machine shell NAME -- --help`, stops scanning at `--` so +/// `--help` meant for the container command passes through untouched. +pub(crate) fn help_for(args: &[String]) -> Option<&'static str> { + let cmd = args.first()?.as_str(); + let sub = &args[1..]; + let scan_end = if cmd == "machine" && sub.first().map(String::as_str) == Some("shell") { + sub.iter().position(|a| a == "--").unwrap_or(sub.len()) + } else { + sub.len() + }; + let has_flag = sub[..scan_end].iter().any(|a| matches!(a.as_str(), "-h" | "--help")); + let help_word = sub.first().map(String::as_str) == Some("help") + && matches!(cmd, "k8s" | "machine" | "diag" | "usb" | "domains" | "registry" | "storage"); + if !has_flag && !help_word { + return None; + } + match cmd { + "start" => Some("usage: kiri start start Kiri after a Stop (the window's Start)"), + "k8s" if sub.first().map(String::as_str) == Some("set") => Some( + "usage: kiri k8s set [--lan on|off] [--tls-san NAME,…] [--port N] [--version TAG|default] [--k3s-arg ARG]… [--clear-k3s-args]", + ), + "k8s" => Some( + "usage: kiri k8s start [--use] | stop | status [--json] | delete | set [--lan on|off] [--tls-san NAME,…] [--port N] [--version TAG|default] [--k3s-arg ARG]… [--clear-k3s-args]", + ), + "machine" => Some( + "usage: kiri machine create NAME [--distro ubuntu|debian|alpine|fedora|arch|rocky|opensuse | --image IMAGE] [--systemd]\n kiri machine list [--json] | shell NAME [-- CMD...] | start | stop | restart | delete NAME", + ), + "diag" => Some( + "usage: kiri diag logs [-f] [--ui|--engine|--cli] [--errors] [--op ID] [-n N]\n kiri diag report [--out PATH] [--send]", + ), + "usb" => Some( + "usage: kiri usb [list [--json]] | attach DEVICE | detach DEVICE\n DEVICE is a location (0x02114000), vendor:product (1532:00d7) or part of the name", + ), + "domains" => Some( + "usage: kiri domains the routers' ports, and whether each runs\n kiri domains set [--http N] [--https N] move them (no restart)\n kiri domains reset back to the ports a start gives (a test copy's: off)\n --json, with any of them, prints the engine's answer as one line of JSON", + ), + "registry" => Some( + "usage: kiri registry both lists and the file they are in\n kiri registry insecure [list] | add HOST... | remove HOST...\n kiri registry mirror [list] | add URL... | remove URL...\n --json, with any of them: one line of JSON", + ), + "scan" => Some( + "usage: kiri scan [--json] [--history] \n --json the full report, as JSON\n --history the image's kept scans, newest first, without scanning again", + ), + "storage" => Some( + "usage: kiri storage [status] show storage location, disk usage, and reclaimable space\n kiri storage reclaim reclaim unused VM disk space back to the host", + ), + _ => None, + } +} + /// Runs `kiri ` in WSL and exits with its exit code. pub fn run(args: &[String]) -> io::Result<()> { + if let Some(help) = help_for(args) { + println!("{help}"); + return Ok(()); + } if let [m, verb, name, rest @ ..] = args && m == "machine" && verb == "shell" @@ -508,4 +563,50 @@ mod tests { assert_eq!(parse_diag_report_args(&s(&["--out"])), None); assert_eq!(parse_diag_report_args(&s(&["--unknown"])), None); } + + #[test] + fn help_for_intercepts_wsl_commands_without_intercepting_container_help() { + use super::help_for; + let s = |list: &[&str]| list.iter().map(|x| (*x).to_owned()).collect::>(); + for cmd in [ + &["start", "--help"][..], + &["start", "-h"], + &["k8s", "--help"], + &["k8s", "-h"], + &["k8s", "help"], + &["k8s", "set", "--help"], + &["machine", "--help"], + &["machine", "create", "-h"], + &["machine", "shell", "--help"], + &["machine", "shell", "dev", "--help"], + &["diag", "--help"], + &["diag", "report", "--help"], + &["diag", "logs", "-h"], + &["usb", "--help"], + &["usb", "attach", "-h"], + &["domains", "--help"], + &["registry", "--help"], + &["scan", "--help"], + &["storage", "--help"], + &["storage", "reclaim", "-h"], + ] { + let text = help_for(&s(cmd)).unwrap_or_else(|| panic!("expected help for {cmd:?}")); + assert!(text.starts_with("usage: kiri "), "{cmd:?}: {text}"); + } + assert!(help_for(&s(&["k8s", "set", "--help"])).unwrap().contains("kiri k8s set")); + + // Must NOT intercept container commands after `--` or non-help invocations. + for pass_through in [ + &["start"][..], + &["k8s", "status"], + &["machine", "list"], + &["machine", "shell", "dev", "--", "uname", "--help"], + &["machine", "shell", "dev", "--", "-h"], + &["scan", "alpine"], + &["scan", "help"], + &["diag", "report"], + ] { + assert_eq!(help_for(&s(pass_through)), None, "must not intercept {pass_through:?}"); + } + } } diff --git a/docs/fix-registry.md b/docs/fix-registry.md index 2d72f27..ca598cd 100644 --- a/docs/fix-registry.md +++ b/docs/fix-registry.md @@ -43,6 +43,12 @@ A log of every merged bug fix in Kiri, newest first, together with any later bug - Caused by: - - Check: `tests/ui/volumes-size.js`, `crates/kiri/src/daemon/ops.rs` +### #982, #984 CLI & Windows: exit 0 without side effects on `--help` / `-h` and `--version` / `-V` / `-v`, enable Windows `kiri import` / `setup` / `build-with`, self-heal `~/.docker/config.json`, and allow `runkiri.com` / `canestack.com` About links (unreleased) +- Fixes: #982 `--help` / `-h` executes commands instead of printing usage, #984 Windows 0.2.2: `kiri import` missing from Windows CLI, uninstalling Docker Desktop wipes `~/.docker/config.json`, and `kiri setup` / `kiri build-with` / `kiri --version` fail +- Caused: none known +- Caused by: - +- Check: `crates/kiri/src/main.rs`, `crates/kiri/src/setup_win.rs`, `crates/kiri/src/dockerctx.rs`, `crates/kiri-win/src/engine.rs` + ### #932 Networking: return `NODATA` for external `AAAA` queries on IPv4-only networks and relay enterprise macOS VPN tunnels through the host (unreleased) - Fixes: #932 Containers and the Kubernetes node fail to reach Docker Hub with IPv6 `Network unreachable` and `TLS handshake timeout` under macOS VPN / packet-tunnel extensions - Caused: none known diff --git a/tests/regressions.tsv b/tests/regressions.tsv index 2cd199e..1485313 100644 --- a/tests/regressions.tsv +++ b/tests/regressions.tsv @@ -364,6 +364,8 @@ crates/kiri-init/src/linux/dns.rs #932 IPv4-only container networks forwarded ex tests/ui/volumes-size.js #936 Volumes view did not show each volume's disk size, and loading sizes synchronously or via GET /system/df could stall list refreshes or wake a sleeping VM crates/kiri/src/builds.rs #923 a running build's steps were read with `buildx history logs`, which follows the build until it ends: the Builds pane stayed on "Loading the steps..." and each 2 s ask left a docker and buildx process running tests/ui/builds-running.js #923 the Builds view asked for a running build's steps on every tick, not once the last ask was answered +crates/kiri/src/setup_win.rs #984 on Windows, `kiri setup`, `kiri import` and `kiri build-with` were missing from `kiri.exe`, uninstalling Docker Desktop wiped `%USERPROFILE%\.docker\config.json` (`cliPluginsExtraDirs`, `kiri` context, dangling `desktop-linux`), and `kiri` subcommands executed side effects or exited 1 on `--help` / `-h` (#982) +crates/kiri-win/src/engine.rs #984 Windows `allowed_url` lacked `runkiri.com` and `canestack.com`, so Settings -> About links did not open, and `kiri-win` startup did not self-heal a wiped `~/.docker/config.json` vm-swap-as-set #326 the VM had no swap, so a container that outgrew the VM's memory was killed instead of slowing down vm-swap-container-over-memory #326 a container over its --memory with --memory-swap room left was killed: the VM had no swap for its pages crates/kiri-init/src/linux/net.rs #443 a second Kiri engine starting in a shared Linux/WSL 2 network namespace overwrote nft table ip kiri, claimed existing kiri0 bridges, and tore down the first engine's network on exit