| 1 | //! Convenience `codew` alias. |
| 2 | //! |
| 3 | //! Forwards argv to the `codewhale` dispatcher silently. This is a |
| 4 | //! permanent short-form alias — six fewer keystrokes, same binary. |
| 5 | |
| 6 | use std::env; |
| 7 | use std::path::{Path, PathBuf}; |
| 8 | use std::process::Command; |
| 9 | |
| 10 | fn main() { |
| 11 | let args: Vec<String> = env::args_os() |
| 12 | .skip(1) |
| 13 | .map(|a| a.to_string_lossy().into_owned()) |
| 14 | .collect(); |
| 15 | |
| 16 | let status = match spawn_codewhale(&args) { |
| 17 | Ok(s) => s, |
| 18 | Err(e) => { |
| 19 | eprintln!( |
| 20 | "error: failed to spawn `codewhale`: {e}. Is it on PATH? \ |
| 21 | Install with `cargo install codewhale-cli` or via npm/Homebrew." |
| 22 | ); |
| 23 | std::process::exit(127); |
| 24 | } |
| 25 | }; |
| 26 | std::process::exit(status.code().unwrap_or(1)); |
| 27 | } |
| 28 | |
| 29 | fn spawn_codewhale(args: &[String]) -> std::io::Result<std::process::ExitStatus> { |
| 30 | // Prefer the dispatcher installed next to this shim. Falling back to PATH |
| 31 | // first can silently run an older global `codewhale` after a fresh install. |
| 32 | if let Ok(exe_path) = env::current_exe() |
| 33 | && let Some(sibling) = sibling_codewhale_path(&exe_path) |
| 34 | && sibling.is_file() |
| 35 | { |
| 36 | return Command::new(sibling).args(args).status(); |
| 37 | } |
| 38 | |
| 39 | // Fall back to PATH for unusual installs that ship only the shim. |
| 40 | match Command::new("codewhale").args(args).status() { |
| 41 | Ok(s) => return Ok(s), |
| 42 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} |
| 43 | Err(e) => return Err(e), |
| 44 | } |
| 45 | |
| 46 | Err(std::io::Error::new( |
| 47 | std::io::ErrorKind::NotFound, |
| 48 | "codewhale not found on PATH or in sibling directory", |
| 49 | )) |
| 50 | } |
| 51 | |
| 52 | fn sibling_codewhale_path(exe_path: &Path) -> Option<PathBuf> { |
| 53 | exe_path |
| 54 | .parent() |
| 55 | .map(|dir| dir.join(format!("codewhale{}", std::env::consts::EXE_SUFFIX))) |
| 56 | } |
| 57 | |
| 58 | #[cfg(test)] |
| 59 | mod tests { |
| 60 | use super::sibling_codewhale_path; |
| 61 | use std::path::Path; |
| 62 | |
| 63 | #[test] |
| 64 | fn sibling_dispatcher_uses_platform_executable_suffix() { |
| 65 | let path = Path::new("/tmp/codewhale-bin/codew"); |
| 66 | let sibling = sibling_codewhale_path(path).expect("sibling"); |
| 67 | |
| 68 | assert_eq!( |
| 69 | sibling, |
| 70 | Path::new("/tmp/codewhale-bin") |
| 71 | .join(format!("codewhale{}", std::env::consts::EXE_SUFFIX)) |
| 72 | ); |
| 73 | } |
| 74 | } |
| 75 |