Compare commits

...
Author SHA1 Message Date
Patrick szymkowiak c8e5618e6a docs: fix Linux binary filename in README (gnu → musl)
README still referenced x86_64-unknown-linux-gnu.tar.gz which was
replaced by x86_64-unknown-linux-musl in PR #267 (v0.23.0+).

Fixes #323
2026-03-06 11:25:25 +01:00
Alex Tsanis 884e37edbf stream proxy output while command is running (#268) 2026-03-06 11:02:59 +01:00
patrick szymkowiak 27b35d84a3 fix: strip npx/bunx/pnpm prefixes in lint linter detection (#186) (#366)
When running `rtk lint npx eslint ...`, args[0] was "npx" instead of
"eslint", causing no JSON format flag injection and duplicated output.

Extract strip_pm_prefix() and detect_linter() helpers, skip package
manager prefixes before identifying the actual linter name.
2026-03-06 10:51:11 +01:00
Radu Ursache 0a1bcb05e5 fix: pass through -R/--repo flag in gh view commands (#328)
gh view/checks commands (pr view, issue view, pr checks, run view)
were ignoring extra flags like -R/--repo, causing failures outside
git repositories where gh needs -R to know which repo to query.

The root cause: these functions took args[0] as the identifier and
discarded everything else, while constructing hardcoded gh commands.

Changes:
- Add extract_identifier_and_extra_args() to separate the positional
  identifier from flags, handling both `view 123 -R owner/repo` and
  `view -R owner/repo 123` argument orders
- Pass extra args through to gh in view_pr, view_issue, pr_checks,
  and view_run
- Add has_json_flag() check at top of run() to passthrough when user
  explicitly requests --json output (related fix from #313)

Fixes #223
2026-03-06 10:31:10 +01:00
Sam Kvale 799f0856e4 fix: gh pr edit/comment pass correct subcommand to gh (#332)
* fix: gh pr edit/comment pass correct subcommand to gh

pr_action was receiving the past-tense display label ("edited",
"commented") and using it as both the gh subcommand and the
ok_confirmation message. This caused `gh pr edited` to be invoked
instead of `gh pr edit`, which fails with "unknown flag" errors.

Split the parameter into subcmd (for the gh invocation) and
display_label (for ok_confirmation output).

* smaller diff
2026-03-06 09:59:00 +01:00
github-actions[bot] 093e431193 chore(master): release 0.27.1 (#362)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-06 09:46:33 +01:00
patrick szymkowiak 409aed6dbc fix: support git commit -am, --amend and other flags (#327) (#360)
Clap was rejecting -a, --amend, --allow-empty etc. because Commit only
declared -m/--message. Switch to trailing_var_arg like other git
subcommands so all flags pass through to git directly.

Fixes #327
2026-03-06 09:41:23 +01:00
patrick szymkowiak 85b0b3eb0b fix: prettier false positive when not installed (#221) (#359)
* fix: prettier reports "All OK" when not installed (#221)

Empty or failed prettier output was incorrectly treated as "all files
formatted". Now detects empty output and non-zero exit code, shows the
actual error message instead of a false positive.

* test: add smoke tests for rewrite, verify, proxy, discover, diff, wc, smart, docker, json edge cases

Covers bug fixes #196, #344, #345, #346, #347 and previously untested
commands. Adds assert_fails helper. 118 assertions total (was 69).

* chore: update benchmark.sh with missing commands and fix paths

- Add cargo (build/test/clippy/check), diff, smart, wc, curl, wget sections
- Fix Python commands: use dedicated rtk ruff/pytest instead of rtk test
- Fix Go commands: use dedicated rtk go/golangci-lint, add go build/vet
- Make BENCH_DIR absolute so debug files work from temp fixture dirs
- Fallback to installed rtk if target/release/rtk not found
2026-03-06 09:40:24 +01:00
patrick szymkowiak dbc950395e fix: only rewrite docker compose ps/logs/build, skip unsupported subcommands (#336) (#363)
The rewrite pattern matched all `docker` commands but the regex didn't
cover `docker compose`, so compose subcommands were never rewritten.
Meanwhile unsupported compose commands (up, down, config) would fail
if manually prefixed with rtk.

- Extend regex to match `docker compose (ps|logs|build)`
- Unsupported compose subcommands (up, down, config, exec, etc.) are
  correctly skipped by the regex and not rewritten
- 6 new tests covering supported and unsupported compose subcommands

Fixes #336
2026-03-06 09:24:28 +01:00
Radu Ursache 45f9344f03 fix: preserve -- separator for cargo commands and silence fallback (#326)
Two fixes for command passthrough issues:

1. Restore `--` separator stripped by clap (#287): When running
   `rtk cargo test -- --nocapture`, clap consumes `--` and passes only
   `["--nocapture"]` to cargo, which rejects it. Now detect `--` from
   the original command line and re-insert it in the correct position.

2. Remove noisy `[rtk: parse failed, running raw]` stderr message (#286):
   Unrecognized commands like `rtk make` or `rtk ruby` pass through
   silently via the fallback, matching the documented behavior.

Fixes #286
Fixes #287
2026-03-06 09:00:13 +01:00
15 changed files with 806 additions and 133 deletions

No files matched your search

+1 -1
View File
@@ -1,3 +1,3 @@
{
".": "0.27.0"
".": "0.27.1"
}
+10
View File
@@ -5,6 +5,16 @@ All notable changes to rtk (Rust Token Killer) will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.27.1](https://github.com/rtk-ai/rtk/compare/v0.27.0...v0.27.1) (2026-03-06)
### Bug Fixes
* only rewrite docker compose ps/logs/build, skip unsupported subcommands ([#336](https://github.com/rtk-ai/rtk/issues/336)) ([#363](https://github.com/rtk-ai/rtk/issues/363)) ([dbc9503](https://github.com/rtk-ai/rtk/commit/dbc950395e31b4b0bc48710dc52ad01d4d73f9ba))
* preserve -- separator for cargo commands and silence fallback ([#326](https://github.com/rtk-ai/rtk/issues/326)) ([45f9344](https://github.com/rtk-ai/rtk/commit/45f9344f033d27bc370ff54c4fc0c61e52446076)), closes [#286](https://github.com/rtk-ai/rtk/issues/286) [#287](https://github.com/rtk-ai/rtk/issues/287)
* prettier false positive when not installed ([#221](https://github.com/rtk-ai/rtk/issues/221)) ([#359](https://github.com/rtk-ai/rtk/issues/359)) ([85b0b3e](https://github.com/rtk-ai/rtk/commit/85b0b3eb0bad9cbacdc32d2e9ba525728acd7cbe))
* support git commit -am, --amend and other flags ([#327](https://github.com/rtk-ai/rtk/issues/327)) ([#360](https://github.com/rtk-ai/rtk/issues/360)) ([409aed6](https://github.com/rtk-ai/rtk/commit/409aed6dbcdd7cac2a48ec5655e6f1fd8d5248e3))
## [0.27.0](https://github.com/rtk-ai/rtk/compare/v0.26.0...v0.27.0) (2026-03-05)
Generated
+1 -1
View File
@@ -838,7 +838,7 @@ dependencies = [
[[package]]
name = "rtk"
version = "0.27.0"
version = "0.27.1"
dependencies = [
"anyhow",
"chrono",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "rtk"
version = "0.27.0"
version = "0.27.1"
edition = "2021"
authors = ["Patrick Szymkowiak"]
description = "Rust Token Killer - High-performance CLI proxy to minimize LLM token consumption"
+1 -1
View File
@@ -103,7 +103,7 @@ cargo install rtk
Download from [rtk-ai/releases](https://github.com/rtk-ai/rtk/releases):
- macOS: `rtk-x86_64-apple-darwin.tar.gz` / `rtk-aarch64-apple-darwin.tar.gz`
- Linux: `rtk-x86_64-unknown-linux-gnu.tar.gz` / `rtk-aarch64-unknown-linux-gnu.tar.gz`
- Linux: `rtk-x86_64-unknown-linux-musl.tar.gz` / `rtk-aarch64-unknown-linux-gnu.tar.gz`
- Windows: `rtk-x86_64-pc-windows-msvc.zip`
## Quick Start
+60 -6
View File
@@ -1,8 +1,16 @@
#!/bin/bash
set -e
RTK="$(cd "$(dirname ./target/release/rtk)" && pwd)/$(basename ./target/release/rtk)"
BENCH_DIR="./scripts/benchmark"
# Use local release build if available, otherwise fall back to installed rtk
if [ -f "./target/release/rtk" ]; then
RTK="$(cd "$(dirname ./target/release/rtk)" && pwd)/$(basename ./target/release/rtk)"
elif command -v rtk &> /dev/null; then
RTK="$(command -v rtk)"
else
echo "Error: rtk not found. Run 'cargo build --release' or install rtk."
exit 1
fi
BENCH_DIR="$(pwd)/scripts/benchmark"
# Mode local : générer les fichiers debug
if [ -z "$CI" ]; then
@@ -258,6 +266,50 @@ section "summary"
bench "summary cargo --help" "cargo --help" "$RTK summary cargo --help"
bench "summary rustc --help" "rustc --help 2>/dev/null || echo 'rustc not found'" "$RTK summary rustc --help"
# ===================
# cargo
# ===================
section "cargo"
bench "cargo build" "cargo build 2>&1 || true" "$RTK cargo build"
bench "cargo test" "cargo test 2>&1 || true" "$RTK cargo test"
bench "cargo clippy" "cargo clippy 2>&1 || true" "$RTK cargo clippy"
bench "cargo check" "cargo check 2>&1 || true" "$RTK cargo check"
# ===================
# diff
# ===================
section "diff"
bench "diff" "diff Cargo.toml LICENSE 2>&1 || true" "$RTK diff Cargo.toml LICENSE"
# ===================
# smart
# ===================
section "smart"
bench "smart main.rs" "cat src/main.rs" "$RTK smart src/main.rs"
# ===================
# wc
# ===================
section "wc"
bench "wc" "wc Cargo.toml src/main.rs" "$RTK wc Cargo.toml src/main.rs"
# ===================
# curl
# ===================
section "curl"
if command -v curl &> /dev/null; then
bench "curl json" "curl -s https://httpbin.org/json" "$RTK curl https://httpbin.org/json"
bench "curl text" "curl -s https://httpbin.org/robots.txt" "$RTK curl https://httpbin.org/robots.txt"
fi
# ===================
# wget
# ===================
if command -v wget &> /dev/null; then
section "wget"
bench "wget" "wget -qO- https://httpbin.org/robots.txt" "$RTK wget https://httpbin.org/robots.txt -O"
fi
# ===================
# Modern JavaScript Stack (skip si pas de package.json)
# ===================
@@ -381,8 +433,8 @@ def test_process_data_none():
assert process_data(None) == []
PYEOF
bench "ruff check" "ruff check . 2>&1 || true" "$RTK test ruff check ."
bench "pytest" "pytest -v 2>&1 || true" "$RTK test pytest -v"
bench "ruff check" "ruff check . 2>&1 || true" "$RTK ruff check ."
bench "pytest" "pytest -v 2>&1 || true" "$RTK pytest -v"
cd - > /dev/null
rm -rf "$PYTHON_FIXTURE"
@@ -445,8 +497,10 @@ func TestMultiply(t *testing.T) {
}
GOEOF
bench "golangci-lint" "golangci-lint run 2>&1 || true" "$RTK test golangci-lint run"
bench "go test" "go test -v 2>&1 || true" "$RTK test go test -v"
bench "golangci-lint" "golangci-lint run 2>&1 || true" "$RTK golangci-lint run"
bench "go test" "go test -v 2>&1 || true" "$RTK go test -v"
bench "go build" "go build ./... 2>&1 || true" "$RTK go build ./..."
bench "go vet" "go vet ./... 2>&1 || true" "$RTK go vet ./..."
cd - > /dev/null
rm -rf "$GO_FIXTURE"
+98
View File
@@ -68,6 +68,19 @@ assert_exit_ok() {
fi
}
assert_fails() {
local name="$1"
shift
if "$@" >/dev/null 2>&1; then
FAIL=$((FAIL + 1))
FAILURES+=("$name (expected failure, got success)")
printf " ${RED}FAIL${NC} %s (expected failure)\n" "$name"
else
PASS=$((PASS + 1))
printf " ${GREEN}PASS${NC} %s\n" "$name"
fi
}
assert_help() {
local name="$1"
shift
@@ -433,6 +446,91 @@ section "Learn"
assert_ok "rtk learn --help" rtk learn --help
assert_ok "rtk learn (no sessions)" rtk learn --since 0 2>&1 || true
# ── 32. Rewrite ───────────────────────────────────────
section "Rewrite"
assert_contains "rewrite git status" "rtk git status" rtk rewrite "git status"
assert_contains "rewrite cargo test" "rtk cargo test" rtk rewrite "cargo test"
assert_contains "rewrite compound &&" "rtk git status" rtk rewrite "git status && cargo test"
assert_contains "rewrite pipe preserves" "| head" rtk rewrite "git log | head"
section "Rewrite (#345: RTK_DISABLED skip)"
assert_fails "rewrite RTK_DISABLED=1 skip" rtk rewrite "RTK_DISABLED=1 git status"
assert_fails "rewrite env RTK_DISABLED skip" rtk rewrite "FOO=1 RTK_DISABLED=1 cargo test"
section "Rewrite (#346: 2>&1 preserved)"
assert_contains "rewrite 2>&1 preserved" "2>&1" rtk rewrite "cargo test 2>&1 | head"
section "Rewrite (#196: gh --json skip)"
assert_fails "rewrite gh --json skip" rtk rewrite "gh pr list --json number"
assert_fails "rewrite gh --jq skip" rtk rewrite "gh api /repos --jq .name"
assert_fails "rewrite gh --template skip" rtk rewrite "gh pr view 1 --template '{{.title}}'"
assert_contains "rewrite gh normal works" "rtk gh pr list" rtk rewrite "gh pr list"
# ── 33. Verify ────────────────────────────────────────
section "Verify"
assert_ok "rtk verify" rtk verify
# ── 34. Proxy ─────────────────────────────────────────
section "Proxy"
assert_ok "rtk proxy echo hello" rtk proxy echo hello
assert_contains "rtk proxy passthrough" "hello" rtk proxy echo hello
# ── 35. Discover ──────────────────────────────────────
section "Discover"
assert_ok "rtk discover" rtk discover
# ── 36. Diff ──────────────────────────────────────────
section "Diff"
assert_ok "rtk diff two files" rtk diff Cargo.toml LICENSE
# ── 37. Wc ────────────────────────────────────────────
section "Wc"
assert_ok "rtk wc Cargo.toml" rtk wc Cargo.toml
# ── 38. Smart ─────────────────────────────────────────
section "Smart"
assert_ok "rtk smart src/main.rs" rtk smart src/main.rs
# ── 39. Json edge cases ──────────────────────────────
section "Json (edge cases)"
assert_fails "rtk json on TOML (#347)" rtk json Cargo.toml
# ── 40. Docker (conditional) ─────────────────────────
section "Docker (conditional)"
if command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1; then
assert_ok "rtk docker ps" rtk docker ps
assert_ok "rtk docker images" rtk docker images
else
skip_test "rtk docker" "docker not running"
fi
# ── 41. Hook check ───────────────────────────────────
section "Hook check (#344)"
assert_contains "rtk init --show hook version" "version" rtk init --show
# ══════════════════════════════════════════════════════
# Report
# ══════════════════════════════════════════════════════
+109 -4
View File
@@ -27,6 +27,40 @@ pub fn run(cmd: CargoCommand, args: &[String], verbose: u8) -> Result<()> {
}
}
/// Reconstruct args with `--` separator preserved from the original command line.
/// Clap strips `--` from parsed args, but cargo subcommands need it to separate
/// their own flags from test runner flags (e.g. `cargo test -- --nocapture`).
fn restore_double_dash(args: &[String]) -> Vec<String> {
let raw_args: Vec<String> = std::env::args().collect();
restore_double_dash_with_raw(args, &raw_args)
}
/// Testable version that takes raw_args explicitly.
fn restore_double_dash_with_raw(args: &[String], raw_args: &[String]) -> Vec<String> {
if args.is_empty() {
return args.to_vec();
}
// Find `--` in the original command line
let sep_pos = match raw_args.iter().position(|a| a == "--") {
Some(pos) => pos,
None => return args.to_vec(),
};
// Count how many of our parsed args appeared before `--` in the original.
// Args before `--` are positional (e.g. test name), args after are flags.
let args_before_sep = raw_args[..sep_pos]
.iter()
.filter(|a| args.contains(a))
.count();
let mut result = Vec::with_capacity(args.len() + 1);
result.extend_from_slice(&args[..args_before_sep]);
result.push("--".to_string());
result.extend_from_slice(&args[args_before_sep..]);
result
}
/// Generic cargo command runner with filtering
fn run_cargo_filtered<F>(subcommand: &str, args: &[String], verbose: u8, filter_fn: F) -> Result<()>
where
@@ -36,12 +70,14 @@ where
let mut cmd = Command::new("cargo");
cmd.arg(subcommand);
for arg in args {
let restored_args = restore_double_dash(args);
for arg in &restored_args {
cmd.arg(arg);
}
if verbose > 0 {
eprintln!("Running: cargo {} {}", subcommand, args.join(" "));
eprintln!("Running: cargo {} {}", subcommand, restored_args.join(" "));
}
let output = cmd
@@ -65,8 +101,8 @@ where
}
timer.track(
&format!("cargo {} {}", subcommand, args.join(" ")),
&format!("rtk cargo {} {}", subcommand, args.join(" ")),
&format!("cargo {} {}", subcommand, restored_args.join(" ")),
&format!("rtk cargo {} {}", subcommand, restored_args.join(" ")),
&raw,
&filtered,
);
@@ -950,6 +986,75 @@ pub fn run_passthrough(args: &[OsString], verbose: u8) -> Result<()> {
mod tests {
use super::*;
#[test]
fn test_restore_double_dash_with_separator() {
// rtk cargo test -- --nocapture → clap gives ["--nocapture"]
let args: Vec<String> = vec!["--nocapture".into()];
let raw = vec![
"rtk".into(),
"cargo".into(),
"test".into(),
"--".into(),
"--nocapture".into(),
];
let result = restore_double_dash_with_raw(&args, &raw);
assert_eq!(result, vec!["--", "--nocapture"]);
}
#[test]
fn test_restore_double_dash_with_test_name() {
// rtk cargo test my_test -- --nocapture → clap gives ["my_test", "--nocapture"]
let args: Vec<String> = vec!["my_test".into(), "--nocapture".into()];
let raw = vec![
"rtk".into(),
"cargo".into(),
"test".into(),
"my_test".into(),
"--".into(),
"--nocapture".into(),
];
let result = restore_double_dash_with_raw(&args, &raw);
assert_eq!(result, vec!["my_test", "--", "--nocapture"]);
}
#[test]
fn test_restore_double_dash_without_separator() {
// rtk cargo test my_test → no --, args unchanged
let args: Vec<String> = vec!["my_test".into()];
let raw = vec![
"rtk".into(),
"cargo".into(),
"test".into(),
"my_test".into(),
];
let result = restore_double_dash_with_raw(&args, &raw);
assert_eq!(result, vec!["my_test"]);
}
#[test]
fn test_restore_double_dash_empty_args() {
let args: Vec<String> = vec![];
let raw = vec!["rtk".into(), "cargo".into(), "test".into()];
let result = restore_double_dash_with_raw(&args, &raw);
assert!(result.is_empty());
}
#[test]
fn test_restore_double_dash_clippy() {
// rtk cargo clippy -- -D warnings → clap gives ["-D", "warnings"]
let args: Vec<String> = vec!["-D".into(), "warnings".into()];
let raw = vec![
"rtk".into(),
"cargo".into(),
"clippy".into(),
"--".into(),
"-D".into(),
"warnings".into(),
];
let result = restore_double_dash_with_raw(&args, &raw);
assert_eq!(result, vec!["--", "-D", "warnings"]);
}
#[test]
fn test_filter_cargo_build_success() {
let output = r#" Compiling libc v0.2.153
+45 -4
View File
@@ -1261,6 +1261,50 @@ mod tests {
);
}
// --- #336: docker compose supported subcommands rewritten, unsupported skipped ---
#[test]
fn test_rewrite_docker_compose_ps() {
assert_eq!(
rewrite_command("docker compose ps", &[]),
Some("rtk docker compose ps".into())
);
}
#[test]
fn test_rewrite_docker_compose_logs() {
assert_eq!(
rewrite_command("docker compose logs web", &[]),
Some("rtk docker compose logs web".into())
);
}
#[test]
fn test_rewrite_docker_compose_build() {
assert_eq!(
rewrite_command("docker compose build", &[]),
Some("rtk docker compose build".into())
);
}
#[test]
fn test_rewrite_docker_compose_up_skipped() {
assert_eq!(rewrite_command("docker compose up -d", &[]), None);
}
#[test]
fn test_rewrite_docker_compose_down_skipped() {
assert_eq!(rewrite_command("docker compose down", &[]), None);
}
#[test]
fn test_rewrite_docker_compose_config_skipped() {
assert_eq!(
rewrite_command("docker compose -f foo.yaml config --services", &[]),
None
);
}
// --- AWS / psql (PR #216) ---
#[test]
@@ -1779,10 +1823,7 @@ mod tests {
#[test]
fn test_rewrite_gh_json_skipped() {
assert_eq!(
rewrite_command("gh pr list --json number,title", &[]),
None
);
assert_eq!(rewrite_command("gh pr list --json number,title", &[]), None);
}
#[test]
+1 -1
View File
@@ -30,7 +30,7 @@ pub const PATTERNS: &[&str] = &[
r"^(pnpm\s+|npx\s+)?(vitest|jest|test)(\s|$)",
r"^(npx\s+|pnpm\s+)?playwright",
r"^(npx\s+|pnpm\s+)?prisma",
r"^docker\s+(ps|images|logs|run|exec|build)",
r"^docker\s+(ps|images|logs|run|exec|build|compose\s+(ps|logs|build))",
r"^kubectl\s+(get|logs|describe|apply)",
r"^tree(\s|$)",
r"^diff\s+",
+164 -37
View File
@@ -108,8 +108,58 @@ fn filter_markdown_segment(text: &str) -> String {
s
}
/// Check if args contain --json flag (user wants specific JSON fields, not RTK filtering)
fn has_json_flag(args: &[String]) -> bool {
args.iter().any(|a| a == "--json")
}
/// Extract a positional identifier (PR/issue number) from args, returning it
/// separately from the remaining extra flags (like -R, --repo, etc.).
/// Handles both `view 123 -R owner/repo` and `view -R owner/repo 123`.
fn extract_identifier_and_extra_args(args: &[String]) -> Option<(String, Vec<String>)> {
if args.is_empty() {
return None;
}
// Known gh flags that take a value — skip these and their values
let flags_with_value = ["-R", "--repo", "-q", "--jq", "-t", "--template"];
let mut identifier = None;
let mut extra = Vec::new();
let mut skip_next = false;
for arg in args {
if skip_next {
extra.push(arg.clone());
skip_next = false;
continue;
}
if flags_with_value.contains(&arg.as_str()) {
extra.push(arg.clone());
skip_next = true;
continue;
}
if arg.starts_with('-') {
extra.push(arg.clone());
continue;
}
// First non-flag arg is the identifier (number/URL)
if identifier.is_none() {
identifier = Some(arg.clone());
} else {
extra.push(arg.clone());
}
}
identifier.map(|id| (id, extra))
}
/// Run a gh command with token-optimized output
pub fn run(subcommand: &str, args: &[String], verbose: u8, ultra_compact: bool) -> Result<()> {
// When user explicitly passes --json, they want raw gh JSON output, not RTK filtering
if has_json_flag(args) {
return run_passthrough("gh", subcommand, args);
}
match subcommand {
"pr" => run_pr(args, verbose, ultra_compact),
"issue" => run_issue(args, verbose, ultra_compact),
@@ -136,8 +186,8 @@ fn run_pr(args: &[String], verbose: u8, ultra_compact: bool) -> Result<()> {
"create" => pr_create(&args[1..], verbose),
"merge" => pr_merge(&args[1..], verbose),
"diff" => pr_diff(&args[1..], verbose),
"comment" => pr_action("commented", &args[1..], verbose),
"edit" => pr_action("edited", &args[1..], verbose),
"comment" => pr_action("commented", &args, verbose),
"edit" => pr_action("edited", &args, verbose),
_ => run_passthrough("gh", "pr", args),
}
}
@@ -229,20 +279,22 @@ fn list_prs(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
fn view_pr(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
let timer = tracking::TimedExecution::start();
if args.is_empty() {
return Err(anyhow::anyhow!("PR number required"));
}
let pr_number = &args[0];
let (pr_number, extra_args) = match extract_identifier_and_extra_args(args) {
Some(result) => result,
None => return Err(anyhow::anyhow!("PR number required")),
};
let mut cmd = Command::new("gh");
cmd.args([
"pr",
"view",
pr_number,
&pr_number,
"--json",
"number,title,state,author,body,url,mergeable,reviews,statusCheckRollup",
]);
for arg in &extra_args {
cmd.arg(arg);
}
let output = cmd.output().context("Failed to run gh pr view")?;
let raw = String::from_utf8_lossy(&output.stdout).to_string();
@@ -398,14 +450,16 @@ fn view_pr(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
fn pr_checks(args: &[String], _verbose: u8, _ultra_compact: bool) -> Result<()> {
let timer = tracking::TimedExecution::start();
if args.is_empty() {
return Err(anyhow::anyhow!("PR number required"));
}
let pr_number = &args[0];
let (pr_number, extra_args) = match extract_identifier_and_extra_args(args) {
Some(result) => result,
None => return Err(anyhow::anyhow!("PR number required")),
};
let mut cmd = Command::new("gh");
cmd.args(["pr", "checks", pr_number]);
cmd.args(["pr", "checks", &pr_number]);
for arg in &extra_args {
cmd.arg(arg);
}
let output = cmd.output().context("Failed to run gh pr checks")?;
let raw = String::from_utf8_lossy(&output.stdout).to_string();
@@ -607,20 +661,22 @@ fn list_issues(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()>
fn view_issue(args: &[String], _verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
if args.is_empty() {
return Err(anyhow::anyhow!("Issue number required"));
}
let issue_number = &args[0];
let (issue_number, extra_args) = match extract_identifier_and_extra_args(args) {
Some(result) => result,
None => return Err(anyhow::anyhow!("Issue number required")),
};
let mut cmd = Command::new("gh");
cmd.args([
"issue",
"view",
issue_number,
&issue_number,
"--json",
"number,title,state,author,body,url",
]);
for arg in &extra_args {
cmd.arg(arg);
}
let output = cmd.output().context("Failed to run gh issue view")?;
let raw = String::from_utf8_lossy(&output.stdout).to_string();
@@ -796,22 +852,23 @@ fn should_passthrough_run_view(extra_args: &[String]) -> bool {
}
fn view_run(args: &[String], _verbose: u8) -> Result<()> {
if args.is_empty() {
return Err(anyhow::anyhow!("Run ID required"));
}
let run_id = &args[0];
let extra_args = &args[1..];
let (run_id, extra_args) = match extract_identifier_and_extra_args(args) {
Some(result) => result,
None => return Err(anyhow::anyhow!("Run ID required")),
};
// Pass through when user requests logs or JSON — the filter would strip them
if should_passthrough_run_view(extra_args) {
return run_passthrough_with_extra("gh", &["run", "view", run_id], extra_args);
if should_passthrough_run_view(&extra_args) {
return run_passthrough_with_extra("gh", &["run", "view", &run_id], &extra_args);
}
let timer = tracking::TimedExecution::start();
let mut cmd = Command::new("gh");
cmd.args(["run", "view", run_id]);
cmd.args(["run", "view", &run_id]);
for arg in &extra_args {
cmd.arg(arg);
}
let output = cmd.output().context("Failed to run gh run view")?;
let raw = String::from_utf8_lossy(&output.stdout).to_string();
@@ -1070,23 +1127,24 @@ fn pr_diff(args: &[String], _verbose: u8) -> Result<()> {
/// Generic PR action handler for comment/edit
fn pr_action(action: &str, args: &[String], _verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
let subcmd = &args[0];
let mut cmd = Command::new("gh");
cmd.args(["pr", action]);
cmd.arg("pr");
for arg in args {
cmd.arg(arg);
}
let output = cmd
.output()
.context(format!("Failed to run gh pr {}", action))?;
.context(format!("Failed to run gh pr {}", subcmd))?;
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
timer.track(
&format!("gh pr {}", action),
&format!("rtk gh pr {}", action),
&format!("gh pr {}", subcmd),
&format!("rtk gh pr {}", subcmd),
&stderr,
&stderr,
);
@@ -1094,8 +1152,8 @@ fn pr_action(action: &str, args: &[String], _verbose: u8) -> Result<()> {
std::process::exit(output.status.code().unwrap_or(1));
}
// Extract PR number from args
let pr_num = args
// Extract PR number from args (skip args[0] which is the subcommand)
let pr_num = args[1..]
.iter()
.find(|a| !a.starts_with('-'))
.map(|s| format!("#{}", s))
@@ -1112,8 +1170,8 @@ fn pr_action(action: &str, args: &[String], _verbose: u8) -> Result<()> {
};
timer.track(
&format!("gh pr {}", action),
&format!("rtk gh pr {}", action),
&format!("gh pr {}", subcmd),
&format!("rtk gh pr {}", subcmd),
&raw,
&filtered,
);
@@ -1277,6 +1335,75 @@ mod tests {
assert_eq!(result, "ok edited #42");
}
#[test]
fn test_has_json_flag_present() {
assert!(has_json_flag(&[
"view".into(),
"--json".into(),
"number,url".into()
]));
}
#[test]
fn test_has_json_flag_absent() {
assert!(!has_json_flag(&["view".into(), "42".into()]));
}
#[test]
fn test_extract_identifier_simple() {
let args: Vec<String> = vec!["123".into()];
let (id, extra) = extract_identifier_and_extra_args(&args).unwrap();
assert_eq!(id, "123");
assert!(extra.is_empty());
}
#[test]
fn test_extract_identifier_with_repo_flag_after() {
// gh issue view 185 -R rtk-ai/rtk
let args: Vec<String> = vec!["185".into(), "-R".into(), "rtk-ai/rtk".into()];
let (id, extra) = extract_identifier_and_extra_args(&args).unwrap();
assert_eq!(id, "185");
assert_eq!(extra, vec!["-R", "rtk-ai/rtk"]);
}
#[test]
fn test_extract_identifier_with_repo_flag_before() {
// gh issue view -R rtk-ai/rtk 185
let args: Vec<String> = vec!["-R".into(), "rtk-ai/rtk".into(), "185".into()];
let (id, extra) = extract_identifier_and_extra_args(&args).unwrap();
assert_eq!(id, "185");
assert_eq!(extra, vec!["-R", "rtk-ai/rtk"]);
}
#[test]
fn test_extract_identifier_with_long_repo_flag() {
let args: Vec<String> = vec!["42".into(), "--repo".into(), "owner/repo".into()];
let (id, extra) = extract_identifier_and_extra_args(&args).unwrap();
assert_eq!(id, "42");
assert_eq!(extra, vec!["--repo", "owner/repo"]);
}
#[test]
fn test_extract_identifier_empty() {
let args: Vec<String> = vec![];
assert!(extract_identifier_and_extra_args(&args).is_none());
}
#[test]
fn test_extract_identifier_only_flags() {
// No positional identifier, only flags
let args: Vec<String> = vec!["-R".into(), "rtk-ai/rtk".into()];
assert!(extract_identifier_and_extra_args(&args).is_none());
}
#[test]
fn test_extract_identifier_with_web_flag() {
let args: Vec<String> = vec!["123".into(), "--web".into()];
let (id, extra) = extract_identifier_and_extra_args(&args).unwrap();
assert_eq!(id, "123");
assert_eq!(extra, vec!["--web"]);
}
#[test]
fn test_run_view_passthrough_log_failed() {
assert!(should_passthrough_run_view(&["--log-failed".into()]));
+39 -41
View File
@@ -10,7 +10,7 @@ pub enum GitCommand {
Status,
Show,
Add,
Commit { messages: Vec<String> },
Commit,
Push,
Pull,
Branch,
@@ -42,7 +42,7 @@ pub fn run(
GitCommand::Status => run_status(args, verbose, global_args),
GitCommand::Show => run_show(args, max_lines, verbose, global_args),
GitCommand::Add => run_add(args, verbose, global_args),
GitCommand::Commit { messages } => run_commit(&messages, verbose, global_args),
GitCommand::Commit => run_commit(args, verbose, global_args),
GitCommand::Push => run_push(args, verbose, global_args),
GitCommand::Pull => run_pull(args, verbose, global_args),
GitCommand::Branch => run_branch(args, verbose, global_args),
@@ -703,30 +703,25 @@ fn run_add(args: &[String], verbose: u8, global_args: &[String]) -> Result<()> {
Ok(())
}
fn build_commit_command(messages: &[String], global_args: &[String]) -> Command {
fn build_commit_command(args: &[String], global_args: &[String]) -> Command {
let mut cmd = git_cmd(global_args);
cmd.arg("commit");
for msg in messages {
cmd.args(["-m", msg]);
for arg in args {
cmd.arg(arg);
}
cmd
}
fn run_commit(messages: &[String], verbose: u8, global_args: &[String]) -> Result<()> {
fn run_commit(args: &[String], verbose: u8, global_args: &[String]) -> Result<()> {
let timer = tracking::TimedExecution::start();
let original_cmd = messages
.iter()
.map(|m| format!("-m \"{}\"", m))
.collect::<Vec<_>>()
.join(" ");
let original_cmd = format!("git commit {}", original_cmd);
let original_cmd = format!("git commit {}", args.join(" "));
if verbose > 0 {
eprintln!("{}", original_cmd);
}
let output = build_commit_command(messages, global_args)
let output = build_commit_command(args, global_args)
.output()
.context("Failed to run git commit")?;
@@ -1721,28 +1716,30 @@ no changes added to commit (use "git add" and/or "git commit -a")
#[test]
fn test_commit_single_message() {
let messages = vec!["fix: typo".to_string()];
let cmd = build_commit_command(&messages, &[]);
let args: Vec<_> = cmd
let args = vec!["-m".to_string(), "fix: typo".to_string()];
let cmd = build_commit_command(&args, &[]);
let cmd_args: Vec<_> = cmd
.get_args()
.map(|a| a.to_string_lossy().to_string())
.collect();
assert_eq!(args, vec!["commit", "-m", "fix: typo"]);
assert_eq!(cmd_args, vec!["commit", "-m", "fix: typo"]);
}
#[test]
fn test_commit_multiple_messages() {
let messages = vec![
let args = vec![
"-m".to_string(),
"feat: add multi-paragraph support".to_string(),
"-m".to_string(),
"This allows git commit -m \"title\" -m \"body\".".to_string(),
];
let cmd = build_commit_command(&messages, &[]);
let args: Vec<_> = cmd
let cmd = build_commit_command(&args, &[]);
let cmd_args: Vec<_> = cmd
.get_args()
.map(|a| a.to_string_lossy().to_string())
.collect();
assert_eq!(
args,
cmd_args,
vec![
"commit",
"-m",
@@ -1753,29 +1750,30 @@ no changes added to commit (use "git add" and/or "git commit -a")
);
}
// #327: git commit -am "msg" must pass -am through to git
#[test]
fn test_commit_three_messages() {
let messages = vec![
"title".to_string(),
"body".to_string(),
"footer: refs #202".to_string(),
];
let cmd = build_commit_command(&messages, &[]);
let args: Vec<_> = cmd
fn test_commit_am_flag() {
let args = vec!["-am".to_string(), "quick fix".to_string()];
let cmd = build_commit_command(&args, &[]);
let cmd_args: Vec<_> = cmd
.get_args()
.map(|a| a.to_string_lossy().to_string())
.collect();
assert_eq!(
args,
vec![
"commit",
"-m",
"title",
"-m",
"body",
"-m",
"footer: refs #202"
]
);
assert_eq!(cmd_args, vec!["commit", "-am", "quick fix"]);
}
#[test]
fn test_commit_amend() {
let args = vec![
"--amend".to_string(),
"-m".to_string(),
"new msg".to_string(),
];
let cmd = build_commit_command(&args, &[]);
let cmd_args: Vec<_> = cmd
.get_args()
.map(|a| a.to_string_lossy().to_string())
.collect();
assert_eq!(cmd_args, vec!["commit", "--amend", "-m", "new msg"]);
}
}
+112 -11
View File
@@ -52,16 +52,43 @@ fn is_python_linter(linter: &str) -> bool {
matches!(linter, "ruff" | "pylint" | "mypy" | "flake8")
}
pub fn run(args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
/// Strip package manager prefixes (npx, bunx, pnpm, pnpm exec, yarn) from args.
/// Returns the number of args to skip.
fn strip_pm_prefix(args: &[String]) -> usize {
let pm_names = ["npx", "bunx", "pnpm", "yarn"];
let mut skip = 0;
for arg in args {
if pm_names.contains(&arg.as_str()) || arg == "exec" {
skip += 1;
} else {
break;
}
}
skip
}
// Detect linter name (first arg if not a path/flag, else default to eslint)
/// Detect the linter name from args (after stripping PM prefixes).
/// Returns the linter name and whether it was explicitly specified.
fn detect_linter(args: &[String]) -> (&str, bool) {
let is_path_or_flag = args.is_empty()
|| args[0].starts_with('-')
|| args[0].contains('/')
|| args[0].contains('.');
let linter = if is_path_or_flag { "eslint" } else { &args[0] };
if is_path_or_flag {
("eslint", false)
} else {
(&args[0], true)
}
}
pub fn run(args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
let skip = strip_pm_prefix(args);
let effective_args = &args[skip..];
let (linter, explicit) = detect_linter(effective_args);
// Python linters use Command::new() directly (they're on PATH via pip/pipx)
// JS linters use package_manager_exec (npx/pnpm exec)
@@ -78,13 +105,13 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
}
"ruff" => {
// Force JSON output for ruff check
if !args.contains(&"--output-format".to_string()) {
if !effective_args.contains(&"--output-format".to_string()) {
cmd.arg("check").arg("--output-format=json");
}
}
"pylint" => {
// Force JSON2 output for pylint
if !args.contains(&"--output-format".to_string()) {
if !effective_args.contains(&"--output-format".to_string()) {
cmd.arg("--output-format=json2");
}
}
@@ -97,11 +124,11 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
}
// Add user arguments (skip first if it was the linter name, and skip "check" for ruff if we added it)
let start_idx = if is_path_or_flag {
let start_idx = if !explicit {
0
} else if linter == "ruff" && !args.is_empty() && args[0] == "ruff" {
} else if linter == "ruff" && !effective_args.is_empty() && effective_args[0] == "ruff" {
// Skip "ruff" and "check" if we already added "check"
if args.len() > 1 && args[1] == "check" {
if effective_args.len() > 1 && effective_args[1] == "check" {
2
} else {
1
@@ -110,7 +137,7 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
1
};
for arg in &args[start_idx..] {
for arg in &effective_args[start_idx..] {
// Skip --output-format if we already added it
if linter == "ruff" && arg.starts_with("--output-format") {
continue;
@@ -123,7 +150,7 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
// Default to current directory if no path specified (for ruff/pylint/mypy/eslint)
if matches!(linter, "ruff" | "pylint" | "mypy" | "eslint") {
let has_path = args
let has_path = effective_args
.iter()
.skip(start_idx)
.any(|a| !a.starts_with('-') && !a.contains('='));
@@ -580,6 +607,80 @@ mod tests {
assert!(result.contains("utils.py"));
}
#[test]
fn test_strip_pm_prefix_npx() {
let args: Vec<String> = vec!["npx".into(), "eslint".into(), "src/".into()];
assert_eq!(strip_pm_prefix(&args), 1);
}
#[test]
fn test_strip_pm_prefix_bunx() {
let args: Vec<String> = vec!["bunx".into(), "eslint".into(), ".".into()];
assert_eq!(strip_pm_prefix(&args), 1);
}
#[test]
fn test_strip_pm_prefix_pnpm_exec() {
let args: Vec<String> = vec!["pnpm".into(), "exec".into(), "eslint".into()];
assert_eq!(strip_pm_prefix(&args), 2);
}
#[test]
fn test_strip_pm_prefix_none() {
let args: Vec<String> = vec!["eslint".into(), "src/".into()];
assert_eq!(strip_pm_prefix(&args), 0);
}
#[test]
fn test_strip_pm_prefix_empty() {
let args: Vec<String> = vec![];
assert_eq!(strip_pm_prefix(&args), 0);
}
#[test]
fn test_detect_linter_eslint() {
let args: Vec<String> = vec!["eslint".into(), "src/".into()];
let (linter, explicit) = detect_linter(&args);
assert_eq!(linter, "eslint");
assert!(explicit);
}
#[test]
fn test_detect_linter_default_on_path() {
let args: Vec<String> = vec!["src/".into()];
let (linter, explicit) = detect_linter(&args);
assert_eq!(linter, "eslint");
assert!(!explicit);
}
#[test]
fn test_detect_linter_default_on_flag() {
let args: Vec<String> = vec!["--max-warnings=0".into()];
let (linter, explicit) = detect_linter(&args);
assert_eq!(linter, "eslint");
assert!(!explicit);
}
#[test]
fn test_detect_linter_after_npx_strip() {
// Simulates: rtk lint npx eslint src/ → after strip_pm_prefix, args = ["eslint", "src/"]
let full_args: Vec<String> = vec!["npx".into(), "eslint".into(), "src/".into()];
let skip = strip_pm_prefix(&full_args);
let effective = &full_args[skip..];
let (linter, _) = detect_linter(effective);
assert_eq!(linter, "eslint");
}
#[test]
fn test_detect_linter_after_pnpm_exec_strip() {
let full_args: Vec<String> =
vec!["pnpm".into(), "exec".into(), "biome".into(), "check".into()];
let skip = strip_pm_prefix(&full_args);
let effective = &full_args[skip..];
let (linter, _) = detect_linter(effective);
assert_eq!(linter, "biome");
}
#[test]
fn test_is_python_linter() {
assert!(is_python_linter("ruff"));
+124 -25
View File
@@ -649,9 +649,9 @@ enum GitCommands {
},
/// Commit → "ok ✓ \<hash\>"
Commit {
/// Commit message (can be repeated for multi-paragraph)
#[arg(short, long)]
message: Vec<String>,
/// Git commit arguments (supports -a, -m, --amend, --allow-empty, etc)
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
args: Vec<String>,
},
/// Push → "ok ✓ \<branch\>"
Push {
@@ -955,8 +955,6 @@ fn run_fallback(parse_error: clap::Error) -> Result<()> {
parse_error.exit();
}
eprintln!("[rtk: parse failed, running raw]");
let raw_command = args.join(" ");
let error_message = utils::strip_ansi(&parse_error.to_string());
@@ -1121,10 +1119,10 @@ fn main() -> Result<()> {
GitCommands::Add { args } => {
git::run(git::GitCommand::Add, &args, None, cli.verbose, &global_args)?;
}
GitCommands::Commit { message } => {
GitCommands::Commit { args } => {
git::run(
git::GitCommand::Commit { messages: message },
&[],
git::GitCommand::Commit,
&args,
None,
cli.verbose,
&global_args,
@@ -1700,7 +1698,9 @@ fn main() -> Result<()> {
}
Commands::Proxy { args } => {
use std::process::Command;
use std::io::{Read, Write};
use std::process::{Command, Stdio};
use std::thread;
if args.is_empty() {
anyhow::bail!(
@@ -1720,18 +1720,74 @@ fn main() -> Result<()> {
eprintln!("Proxy mode: {} {}", cmd_name, cmd_args.join(" "));
}
let output = Command::new(cmd_name.as_ref())
let mut child = Command::new(cmd_name.as_ref())
.args(&cmd_args)
.output()
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.context(format!("Failed to execute command: {}", cmd_name))?;
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let full_output = format!("{}{}", stdout, stderr);
let stdout_pipe = child
.stdout
.take()
.context("Failed to capture child stdout")?;
let stderr_pipe = child
.stderr
.take()
.context("Failed to capture child stderr")?;
// Print output
print!("{}", stdout);
eprint!("{}", stderr);
let stdout_handle = thread::spawn(move || -> std::io::Result<Vec<u8>> {
let mut reader = stdout_pipe;
let mut captured = Vec::new();
let mut buf = [0u8; 8192];
loop {
let count = reader.read(&mut buf)?;
if count == 0 {
break;
}
captured.extend_from_slice(&buf[..count]);
let mut out = std::io::stdout().lock();
out.write_all(&buf[..count])?;
out.flush()?;
}
Ok(captured)
});
let stderr_handle = thread::spawn(move || -> std::io::Result<Vec<u8>> {
let mut reader = stderr_pipe;
let mut captured = Vec::new();
let mut buf = [0u8; 8192];
loop {
let count = reader.read(&mut buf)?;
if count == 0 {
break;
}
captured.extend_from_slice(&buf[..count]);
let mut err = std::io::stderr().lock();
err.write_all(&buf[..count])?;
err.flush()?;
}
Ok(captured)
});
let status = child
.wait()
.context(format!("Failed waiting for command: {}", cmd_name))?;
let stdout_bytes = stdout_handle
.join()
.map_err(|_| anyhow::anyhow!("stdout streaming thread panicked"))??;
let stderr_bytes = stderr_handle
.join()
.map_err(|_| anyhow::anyhow!("stderr streaming thread panicked"))??;
let stdout = String::from_utf8_lossy(&stdout_bytes);
let stderr = String::from_utf8_lossy(&stderr_bytes);
let full_output = format!("{}{}", stdout, stderr);
// Track usage (input = output since no filtering)
timer.track(
@@ -1742,8 +1798,8 @@ fn main() -> Result<()> {
);
// Exit with same code as child process
if !output.status.success() {
std::process::exit(output.status.code().unwrap_or(1));
if !status.success() {
std::process::exit(status.code().unwrap_or(1));
}
}
@@ -1817,10 +1873,10 @@ mod tests {
let cli = Cli::try_parse_from(["rtk", "git", "commit", "-m", "fix: typo"]).unwrap();
match cli.command {
Commands::Git {
command: GitCommands::Commit { message },
command: GitCommands::Commit { args },
..
} => {
assert_eq!(message, vec!["fix: typo"]);
assert_eq!(args, vec!["-m", "fix: typo"]);
}
_ => panic!("Expected Git Commit command"),
}
@@ -1840,10 +1896,43 @@ mod tests {
.unwrap();
match cli.command {
Commands::Git {
command: GitCommands::Commit { message },
command: GitCommands::Commit { args },
..
} => {
assert_eq!(message, vec!["feat: add support", "Body paragraph here."]);
assert_eq!(
args,
vec!["-m", "feat: add support", "-m", "Body paragraph here."]
);
}
_ => panic!("Expected Git Commit command"),
}
}
// #327: git commit -am "msg" was rejected by Clap
#[test]
fn test_git_commit_am_flag() {
let cli = Cli::try_parse_from(["rtk", "git", "commit", "-am", "quick fix"]).unwrap();
match cli.command {
Commands::Git {
command: GitCommands::Commit { args },
..
} => {
assert_eq!(args, vec!["-am", "quick fix"]);
}
_ => panic!("Expected Git Commit command"),
}
}
#[test]
fn test_git_commit_amend() {
let cli =
Cli::try_parse_from(["rtk", "git", "commit", "--amend", "-m", "new msg"]).unwrap();
match cli.command {
Commands::Git {
command: GitCommands::Commit { args },
..
} => {
assert_eq!(args, vec!["--amend", "-m", "new msg"]);
}
_ => panic!("Expected Git Commit command"),
}
@@ -1887,10 +1976,20 @@ mod tests {
.unwrap();
match cli.command {
Commands::Git {
command: GitCommands::Commit { message },
command: GitCommands::Commit { args },
..
} => {
assert_eq!(message, vec!["title", "body", "footer"]);
assert_eq!(
args,
vec![
"--message",
"title",
"--message",
"body",
"--message",
"footer"
]
);
}
_ => panic!("Expected Git Commit command"),
}
+40
View File
@@ -24,6 +24,25 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
// #221: If prettier is not installed or produced no meaningful output,
// show stderr as-is instead of a misleading "All files formatted" message.
let has_output = stdout.lines().any(|l| !l.trim().is_empty());
if !has_output && !output.status.success() {
let msg = stderr.trim();
if msg.is_empty() {
eprintln!("Error: prettier not found or produced no output");
} else {
eprintln!("{}", msg);
}
timer.track(
&format!("prettier {}", args.join(" ")),
&format!("rtk prettier {}", args.join(" ")),
&raw,
&raw,
);
std::process::exit(output.status.code().unwrap_or(1));
}
let filtered = filter_prettier_output(&raw);
println!("{}", filtered);
@@ -45,6 +64,11 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
/// Filter Prettier output - show only files that need formatting
pub fn filter_prettier_output(output: &str) -> String {
// #221: empty or whitespace-only output means prettier didn't run
if output.trim().is_empty() {
return "Error: prettier produced no output".to_string();
}
let mut files_to_format: Vec<String> = Vec::new();
let mut files_checked = 0;
let mut is_check_mode = true;
@@ -178,4 +202,20 @@ Code style issues found in the above file(s). Forgot to run Prettier?
assert!(result.contains("15 files need formatting"));
assert!(result.contains("... +5 more files"));
}
// --- #221: empty output should not say "All files formatted" ---
#[test]
fn test_filter_empty_output() {
let result = filter_prettier_output("");
assert!(result.contains("Error"));
assert!(!result.contains("All files formatted"));
}
#[test]
fn test_filter_whitespace_only_output() {
let result = filter_prettier_output(" \n\n ");
assert!(result.contains("Error"));
assert!(!result.contains("All files formatted"));
}
}