Compare commits

...
2 Commits
Author SHA1 Message Date
Florian BRUNIAUXandClaude Sonnet 4.6 2aff2fa773 chore: bump version references to 0.28.2 for consistency with develop
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Florian BRUNIAUX <florian@bruniaux.com>
2026-03-11 00:35:53 +01:00
Florian BRUNIAUXandClaude Sonnet 4.6 d14e63911c fix: PATHEXT resolution on Windows for JS/TS and Python tools (#212)
Add `which` crate (v8) and two central helpers in utils.rs:
- `resolve_binary(name)` resolves a binary to its full path, honoring
  PATHEXT on Windows so `.CMD`/`.BAT`/`.PS1` wrappers are found
- `tool_exists(name)` replaces all `Command::new("which")` usages
  (which does not exist on Windows) with a cross-platform check

Apply `resolve_binary()` to:
- All JS/TS tool entry points (tsc, next, prisma, playwright, npm, pnpm,
  ruff, golangci-lint, vitest via package_manager_exec)
- Python tool entry points (mypy, pytest, pip/uv)
- The 3 central passthrough/TOML/proxy entry points in main.rs
- `package_manager_exec()` in utils.rs (covers vitest, prettier, lint,
  format, biome automatically)

Remove 4 local `which_command()` duplicates (mypy_cmd, pytest_cmd,
pip_cmd, ccusage) and the `binary_exists()` helper in ccusage.

Fixes: https://github.com/rtk-ai/rtk/issues/212

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Florian BRUNIAUX <florian@bruniaux.com>
2026-03-11 00:35:53 +01:00
22 changed files with 117 additions and 125 deletions

No files matched your search

+1 -1
View File
@@ -1488,4 +1488,4 @@ When implementing a new command, consider:
**Last Updated**: 2026-02-22
**Architecture Version**: 2.2
**rtk Version**: 0.28.0
**rtk Version**: 0.28.2
+1 -1
View File
@@ -16,7 +16,7 @@ This is a fork with critical fixes for git argument parsing and modern JavaScrip
**Verify correct installation:**
```bash
rtk --version # Should show "rtk 0.28.0" (or newer)
rtk --version # Should show "rtk 0.28.2" (or newer)
rtk gain # Should show token savings stats (NOT "command not found")
```
Generated
+10
View File
@@ -858,6 +858,7 @@ dependencies = [
"toml",
"ureq",
"walkdir",
"which",
]
[[package]]
@@ -1301,6 +1302,15 @@ dependencies = [
"rustls-pki-types",
]
[[package]]
name = "which"
version = "8.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81995fafaaaf6ae47a7d0cc83c67caf92aeb7e5331650ae6ff856f7c0c60c459"
dependencies = [
"libc",
]
[[package]]
name = "winapi-util"
version = "0.1.11"
+1
View File
@@ -30,6 +30,7 @@ tempfile = "3"
sha2 = "0.10"
ureq = "2"
hostname = "0.4"
which = "8"
[build-dependencies]
toml = "0.8"
+1 -1
View File
@@ -90,7 +90,7 @@ Download from [releases](https://github.com/rtk-ai/rtk/releases):
### Verify Installation
```bash
rtk --version # Should show "rtk 0.28.0"
rtk --version # Should show "rtk 0.28.2"
rtk gain # Should show token savings stats
```
+5 -13
View File
@@ -4,6 +4,7 @@
//! Claude Code API usage metrics. Handles subprocess execution, JSON parsing,
//! and graceful degradation when ccusage is unavailable.
use crate::utils::{resolve_binary, tool_exists};
use anyhow::{Context, Result};
use serde::Deserialize;
use std::process::Command;
@@ -82,23 +83,14 @@ struct MonthlyEntry {
// ── Public API ──
/// Check if ccusage binary exists in PATH
fn binary_exists() -> bool {
Command::new("which")
.arg("ccusage")
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}
/// Build the ccusage command, falling back to npx if binary not in PATH
fn build_command() -> Option<Command> {
if binary_exists() {
return Some(Command::new("ccusage"));
if tool_exists("ccusage") {
return Some(Command::new(resolve_binary("ccusage")));
}
// Fallback: try npx
let npx_check = Command::new("npx")
let npx_check = Command::new(resolve_binary("npx"))
.arg("ccusage")
.arg("--help")
.stdout(std::process::Stdio::null())
@@ -106,7 +98,7 @@ fn build_command() -> Option<Command> {
.status();
if npx_check.map(|s| s.success()).unwrap_or(false) {
let mut cmd = Command::new("npx");
let mut cmd = Command::new(resolve_binary("npx"));
cmd.arg("ccusage");
return Some(cmd);
}
+3 -3
View File
@@ -1,7 +1,7 @@
use crate::prettier_cmd;
use crate::ruff_cmd;
use crate::tracking;
use crate::utils::package_manager_exec;
use crate::utils::{package_manager_exec, resolve_binary};
use anyhow::{Context, Result};
use std::path::Path;
use std::process::Command;
@@ -72,9 +72,9 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
// Build command based on formatter
let mut cmd = match formatter.as_str() {
"prettier" => package_manager_exec("prettier"),
"black" | "ruff" => Command::new(formatter.as_str()),
"black" | "ruff" => Command::new(resolve_binary(formatter.as_str())),
"biome" => package_manager_exec("biome"),
_ => Command::new(formatter.as_str()),
_ => Command::new(resolve_binary(formatter.as_str())),
};
// Add formatter-specific flags
+2 -2
View File
@@ -1,5 +1,5 @@
use crate::tracking;
use crate::utils::truncate;
use crate::utils::{resolve_binary, truncate};
use anyhow::{Context, Result};
use serde::Deserialize;
use std::collections::HashMap;
@@ -34,7 +34,7 @@ struct GolangciOutput {
pub fn run(args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
let mut cmd = Command::new("golangci-lint");
let mut cmd = Command::new(resolve_binary("golangci-lint"));
// Force JSON output
let has_format = args
+2 -2
View File
@@ -1,7 +1,7 @@
use crate::mypy_cmd;
use crate::ruff_cmd;
use crate::tracking;
use crate::utils::{package_manager_exec, truncate};
use crate::utils::{package_manager_exec, resolve_binary, truncate};
use anyhow::{Context, Result};
use regex::Regex;
use serde::{Deserialize, Serialize};
@@ -93,7 +93,7 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
// Python linters use Command::new() directly (they're on PATH via pip/pipx)
// JS linters use package_manager_exec (npx/pnpm exec)
let mut cmd = if is_python_linter(linter) {
Command::new(linter)
Command::new(resolve_binary(linter))
} else {
package_manager_exec(linter)
};
+6 -5
View File
@@ -63,6 +63,7 @@ use clap::error::ErrorKind;
use clap::{Parser, Subcommand};
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use utils::resolve_binary;
#[derive(Parser)]
#[command(
@@ -998,7 +999,7 @@ fn run_fallback(parse_error: clap::Error) -> Result<()> {
if let Some(filter) = toml_match {
// TOML match: capture stdout for filtering
let result = std::process::Command::new(&args[0])
let result = std::process::Command::new(resolve_binary(&args[0]))
.args(&args[1..])
.stdin(std::process::Stdio::inherit())
.stdout(std::process::Stdio::piped()) // capture
@@ -1043,7 +1044,7 @@ fn run_fallback(parse_error: clap::Error) -> Result<()> {
}
} else {
// No TOML match: original passthrough behaviour (Stdio::inherit, streaming)
let status = std::process::Command::new(&args[0])
let status = std::process::Command::new(resolve_binary(&args[0]))
.args(&args[1..])
.stdin(std::process::Stdio::inherit())
.stdout(std::process::Stdio::inherit())
@@ -1734,7 +1735,7 @@ fn main() -> Result<()> {
_ => {
// Passthrough other prisma subcommands
let timer = tracking::TimedExecution::start();
let mut cmd = std::process::Command::new("npx");
let mut cmd = std::process::Command::new(resolve_binary("npx"));
for arg in &args {
cmd.arg(arg);
}
@@ -1751,7 +1752,7 @@ fn main() -> Result<()> {
}
} else {
let timer = tracking::TimedExecution::start();
let status = std::process::Command::new("npx")
let status = std::process::Command::new(resolve_binary("npx"))
.arg("prisma")
.status()
.context("Failed to run npx prisma")?;
@@ -1867,7 +1868,7 @@ fn main() -> Result<()> {
eprintln!("Proxy mode: {} {}", cmd_name, cmd_args.join(" "));
}
let mut child = Command::new(cmd_name.as_ref())
let mut child = Command::new(resolve_binary(cmd_name.as_ref()))
.args(&cmd_args)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
+4 -15
View File
@@ -1,5 +1,5 @@
use crate::tracking;
use crate::utils::{strip_ansi, truncate};
use crate::utils::{resolve_binary, strip_ansi, tool_exists, truncate};
use anyhow::{Context, Result};
use regex::Regex;
use std::collections::HashMap;
@@ -8,10 +8,10 @@ use std::process::Command;
pub fn run(args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
let mut cmd = if which_command("mypy").is_some() {
Command::new("mypy")
let mut cmd = if tool_exists("mypy") {
Command::new(resolve_binary("mypy"))
} else {
let mut c = Command::new("python3");
let mut c = Command::new(resolve_binary("python3"));
c.arg("-m").arg("mypy");
c
};
@@ -47,17 +47,6 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
std::process::exit(output.status.code().unwrap_or(1));
}
fn which_command(cmd: &str) -> Option<String> {
Command::new("which")
.arg(cmd)
.output()
.ok()
.filter(|o| o.status.success())
.and_then(|o| String::from_utf8(o.stdout).ok())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
}
struct MypyError {
file: String,
line: usize,
+4 -8
View File
@@ -1,5 +1,5 @@
use crate::tracking;
use crate::utils::{strip_ansi, truncate};
use crate::utils::{resolve_binary, strip_ansi, tool_exists, truncate};
use anyhow::{Context, Result};
use regex::Regex;
use std::process::Command;
@@ -8,16 +8,12 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
// Try next directly first, fallback to npx if not found
let next_exists = Command::new("which")
.arg("next")
.output()
.map(|o| o.status.success())
.unwrap_or(false);
let next_exists = tool_exists("next");
let mut cmd = if next_exists {
Command::new("next")
Command::new(resolve_binary("next"))
} else {
let mut c = Command::new("npx");
let mut c = Command::new(resolve_binary("npx"));
c.arg("next");
c
};
+2 -1
View File
@@ -1,11 +1,12 @@
use crate::tracking;
use crate::utils::resolve_binary;
use anyhow::{Context, Result};
use std::process::Command;
pub fn run(args: &[String], verbose: u8, skip_env: bool) -> Result<()> {
let timer = tracking::TimedExecution::start();
let mut cmd = Command::new("npm");
let mut cmd = Command::new(resolve_binary("npm"));
cmd.arg("run");
// Strip leading "run" to avoid doubling (rtk npm run build → npm run build, not npm run run build)
+5 -16
View File
@@ -1,4 +1,5 @@
use crate::tracking;
use crate::utils::{resolve_binary, tool_exists};
use anyhow::{Context, Result};
use serde::Deserialize;
use std::process::Command;
@@ -15,7 +16,7 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
// Auto-detect uv vs pip
let use_uv = which_command("uv").is_some();
let use_uv = tool_exists("uv");
let base_cmd = if use_uv { "uv" } else { "pip" };
if verbose > 0 && use_uv {
@@ -51,7 +52,7 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
}
fn run_list(base_cmd: &str, args: &[String], verbose: u8) -> Result<(String, String)> {
let mut cmd = Command::new(base_cmd);
let mut cmd = Command::new(resolve_binary(base_cmd));
if base_cmd == "uv" {
cmd.arg("pip");
@@ -86,7 +87,7 @@ fn run_list(base_cmd: &str, args: &[String], verbose: u8) -> Result<(String, Str
}
fn run_outdated(base_cmd: &str, args: &[String], verbose: u8) -> Result<(String, String)> {
let mut cmd = Command::new(base_cmd);
let mut cmd = Command::new(resolve_binary(base_cmd));
if base_cmd == "uv" {
cmd.arg("pip");
@@ -121,7 +122,7 @@ fn run_outdated(base_cmd: &str, args: &[String], verbose: u8) -> Result<(String,
}
fn run_passthrough(base_cmd: &str, args: &[String], verbose: u8) -> Result<(String, String)> {
let mut cmd = Command::new(base_cmd);
let mut cmd = Command::new(resolve_binary(base_cmd));
if base_cmd == "uv" {
cmd.arg("pip");
@@ -153,18 +154,6 @@ fn run_passthrough(base_cmd: &str, args: &[String], verbose: u8) -> Result<(Stri
Ok((raw.clone(), raw))
}
/// Check if a command exists in PATH
fn which_command(cmd: &str) -> Option<String> {
Command::new("which")
.arg(cmd)
.output()
.ok()
.filter(|o| o.status.success())
.and_then(|o| String::from_utf8(o.stdout).ok())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
}
/// Filter pip list JSON output
fn filter_pip_list(output: &str) -> String {
let packages: Vec<Package> = match serde_json::from_str(output) {
+4 -4
View File
@@ -1,5 +1,5 @@
use crate::tracking;
use crate::utils::{detect_package_manager, strip_ansi};
use crate::utils::{detect_package_manager, resolve_binary, strip_ansi};
use anyhow::{Context, Result};
use regex::Regex;
use serde::Deserialize;
@@ -246,17 +246,17 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
let pm = detect_package_manager();
let mut cmd = match pm {
"pnpm" => {
let mut c = std::process::Command::new("pnpm");
let mut c = std::process::Command::new(resolve_binary("pnpm"));
c.arg("exec").arg("--").arg("playwright");
c
}
"yarn" => {
let mut c = std::process::Command::new("yarn");
let mut c = std::process::Command::new(resolve_binary("yarn"));
c.arg("exec").arg("--").arg("playwright");
c
}
_ => {
let mut c = std::process::Command::new("npx");
let mut c = std::process::Command::new(resolve_binary("npx"));
c.arg("--no-install").arg("--").arg("playwright");
c
}
+5 -4
View File
@@ -1,4 +1,5 @@
use crate::tracking;
use crate::utils::resolve_binary;
use anyhow::{Context, Result};
use serde::Deserialize;
use std::collections::HashMap;
@@ -294,7 +295,7 @@ pub fn run(cmd: PnpmCommand, args: &[String], verbose: u8) -> Result<()> {
fn run_list(depth: usize, args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
let mut cmd = Command::new("pnpm");
let mut cmd = Command::new(resolve_binary("pnpm"));
cmd.arg("list");
cmd.arg(format!("--depth={}", depth));
cmd.arg("--json");
@@ -350,7 +351,7 @@ fn run_list(depth: usize, args: &[String], verbose: u8) -> Result<()> {
fn run_outdated(args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
let mut cmd = Command::new("pnpm");
let mut cmd = Command::new(resolve_binary("pnpm"));
cmd.arg("outdated");
cmd.arg("--format");
cmd.arg("json");
@@ -411,7 +412,7 @@ fn run_install(packages: &[String], args: &[String], verbose: u8) -> Result<()>
}
}
let mut cmd = Command::new("pnpm");
let mut cmd = Command::new(resolve_binary("pnpm"));
cmd.arg("install");
for pkg in packages {
@@ -495,7 +496,7 @@ pub fn run_passthrough(args: &[OsString], verbose: u8) -> Result<()> {
if verbose > 0 {
eprintln!("pnpm passthrough: {:?}", args);
}
let status = Command::new("pnpm")
let status = Command::new(resolve_binary("pnpm"))
.args(args)
.status()
.context("Failed to run pnpm")?;
+4 -9
View File
@@ -1,4 +1,5 @@
use crate::tracking;
use crate::utils::{resolve_binary, tool_exists};
use anyhow::{Context, Result};
use std::process::Command;
@@ -26,16 +27,10 @@ pub fn run(cmd: PrismaCommand, args: &[String], verbose: u8) -> Result<()> {
/// Create a Command that will run prisma (tries global first, then npx)
fn create_prisma_command() -> Command {
let prisma_exists = Command::new("which")
.arg("prisma")
.output()
.map(|o| o.status.success())
.unwrap_or(false);
if prisma_exists {
Command::new("prisma")
if tool_exists("prisma") {
Command::new(resolve_binary("prisma"))
} else {
let mut c = Command::new("npx");
let mut c = Command::new(resolve_binary("npx"));
c.arg("prisma");
c
}
+4 -16
View File
@@ -1,5 +1,5 @@
use crate::tracking;
use crate::utils::truncate;
use crate::utils::{resolve_binary, tool_exists, truncate};
use anyhow::{Context, Result};
use std::process::Command;
@@ -15,11 +15,11 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
// Try to detect pytest command (could be "pytest", "python -m pytest", etc.)
let mut cmd = if which_command("pytest").is_some() {
Command::new("pytest")
let mut cmd = if tool_exists("pytest") {
Command::new(resolve_binary("pytest"))
} else {
// Fallback to python -m pytest
let mut c = Command::new("python");
let mut c = Command::new(resolve_binary("python"));
c.arg("-m").arg("pytest");
c
};
@@ -83,18 +83,6 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
Ok(())
}
/// Check if a command exists in PATH
fn which_command(cmd: &str) -> Option<String> {
Command::new("which")
.arg(cmd)
.output()
.ok()
.filter(|o| o.status.success())
.and_then(|o| String::from_utf8(o.stdout).ok())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
}
/// Parse pytest output using state machine
fn filter_pytest_output(output: &str) -> String {
let mut state = ParseState::Header;
+2 -2
View File
@@ -1,5 +1,5 @@
use crate::tracking;
use crate::utils::truncate;
use crate::utils::{resolve_binary, truncate};
use anyhow::{Context, Result};
use serde::Deserialize;
use std::collections::HashMap;
@@ -38,7 +38,7 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
let is_format = args.iter().any(|a| a == "format");
let mut cmd = Command::new("ruff");
let mut cmd = Command::new(resolve_binary("ruff"));
if is_check {
// Force JSON output for check command
+3 -3
View File
@@ -7,6 +7,7 @@
//! unless -a flag is present (respecting user intent).
use crate::tracking;
use crate::utils::{resolve_binary, tool_exists};
use anyhow::{Context, Result};
use std::process::Command;
@@ -44,8 +45,7 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
// Check if tree is installed
let tree_check = Command::new("which").arg("tree").output();
if tree_check.is_err() || !tree_check.unwrap().status.success() {
if !tool_exists("tree") {
anyhow::bail!(
"tree command not found. Install it first:\n\
- macOS: brew install tree\n\
@@ -55,7 +55,7 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
);
}
let mut cmd = Command::new("tree");
let mut cmd = Command::new(resolve_binary("tree"));
// Determine if user wants all files or default behavior
let show_all = args.iter().any(|a| a == "-a" || a == "--all");
+4 -8
View File
@@ -1,5 +1,5 @@
use crate::tracking;
use crate::utils::truncate;
use crate::utils::{resolve_binary, tool_exists, truncate};
use anyhow::{Context, Result};
use regex::Regex;
use std::collections::HashMap;
@@ -9,16 +9,12 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
// Try tsc directly first, fallback to npx if not found
let tsc_exists = Command::new("which")
.arg("tsc")
.output()
.map(|o| o.status.success())
.unwrap_or(false);
let tsc_exists = tool_exists("tsc");
let mut cmd = if tsc_exists {
Command::new("tsc")
Command::new(resolve_binary("tsc"))
} else {
let mut c = Command::new("npx");
let mut c = Command::new(resolve_binary("npx"));
c.arg("tsc");
c
};
+44 -11
View File
@@ -226,32 +226,39 @@ pub fn detect_package_manager() -> &'static str {
}
}
/// Resolve a binary name to its full path, honoring PATHEXT on Windows.
/// Falls back to the original name if not found (lets Command::new produce its usual error).
pub fn resolve_binary(name: &str) -> std::ffi::OsString {
which::which(name)
.map(|p| p.into_os_string())
.unwrap_or_else(|_| name.into())
}
/// Check if a tool exists on PATH (cross-platform replacement for `Command::new("which")`).
pub fn tool_exists(name: &str) -> bool {
which::which(name).is_ok()
}
/// Build a Command using the detected package manager's exec mechanism.
/// Returns a Command ready to have tool-specific args appended.
pub fn package_manager_exec(tool: &str) -> Command {
let tool_exists = Command::new("which")
.arg(tool)
.output()
.map(|o| o.status.success())
.unwrap_or(false);
if tool_exists {
Command::new(tool)
if tool_exists(tool) {
Command::new(resolve_binary(tool))
} else {
let pm = detect_package_manager();
match pm {
"pnpm" => {
let mut c = Command::new("pnpm");
let mut c = Command::new(resolve_binary("pnpm"));
c.arg("exec").arg("--").arg(tool);
c
}
"yarn" => {
let mut c = Command::new("yarn");
let mut c = Command::new(resolve_binary("yarn"));
c.arg("exec").arg("--").arg(tool);
c
}
_ => {
let mut c = Command::new("npx");
let mut c = Command::new(resolve_binary("npx"));
c.arg("--no-install").arg("--").arg(tool);
c
}
@@ -398,6 +405,32 @@ mod tests {
assert_eq!(format_cpt(f64::NAN), "$0.00/MTok"); // NaN
}
#[test]
fn test_resolve_binary_known() {
// cargo exists on all dev machines
let resolved = resolve_binary("cargo");
assert!(!resolved.is_empty());
}
#[test]
fn test_resolve_binary_unknown() {
let resolved = resolve_binary("nonexistent_tool_xyz_99999");
assert_eq!(
resolved,
std::ffi::OsString::from("nonexistent_tool_xyz_99999")
);
}
#[test]
fn test_tool_exists_positive() {
assert!(tool_exists("cargo"));
}
#[test]
fn test_tool_exists_negative() {
assert!(!tool_exists("nonexistent_tool_xyz_99999"));
}
#[test]
fn test_detect_package_manager_default() {
// In the test environment (rtk repo), there's no JS lockfile