Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
05fa9b416f | ||
|
|
d0396da1ce |
No files matched your search
@@ -19,6 +19,8 @@ secrets.json
|
||||
*.swo
|
||||
*~
|
||||
|
||||
.next
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
@@ -40,3 +42,6 @@ claudedocs
|
||||
# Vitals provenance data
|
||||
.vitals/
|
||||
.worktrees/
|
||||
|
||||
# icm
|
||||
.fastembed_cache/
|
||||
Generated
+11
@@ -767,6 +767,15 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quick-xml"
|
||||
version = "0.37.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "331e97a1af0bf59823e6eadffe373d7b27f485be8748f71471c662c1f269b7fb"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.43"
|
||||
@@ -845,9 +854,11 @@ dependencies = [
|
||||
"clap",
|
||||
"colored",
|
||||
"dirs",
|
||||
"flate2",
|
||||
"hostname",
|
||||
"ignore",
|
||||
"lazy_static",
|
||||
"quick-xml",
|
||||
"regex",
|
||||
"rusqlite",
|
||||
"serde",
|
||||
|
||||
@@ -30,6 +30,8 @@ tempfile = "3"
|
||||
sha2 = "0.10"
|
||||
ureq = "2"
|
||||
hostname = "0.4"
|
||||
flate2 = "1.0"
|
||||
quick-xml = "0.37"
|
||||
|
||||
[build-dependencies]
|
||||
toml = "0.8"
|
||||
|
||||
@@ -102,6 +102,7 @@ rtk gain # Should show token savings stats
|
||||
# 1. Install hook for Claude Code (recommended)
|
||||
rtk init --global
|
||||
# Follow instructions to register in ~/.claude/settings.json
|
||||
# Claude Code only by default (use --opencode for OpenCode)
|
||||
|
||||
# 2. Restart Claude Code, then test
|
||||
git status # Automatically rewritten to rtk git status
|
||||
@@ -272,6 +273,7 @@ The most effective way to use rtk. The hook transparently intercepts Bash comman
|
||||
|
||||
```bash
|
||||
rtk init -g # Install hook + RTK.md (recommended)
|
||||
rtk init -g --opencode # OpenCode plugin (instead of Claude Code)
|
||||
rtk init -g --auto-patch # Non-interactive (CI/CD)
|
||||
rtk init -g --hook-only # Hook only, no RTK.md
|
||||
rtk init --show # Verify installation
|
||||
@@ -279,6 +281,28 @@ rtk init --show # Verify installation
|
||||
|
||||
After install, **restart Claude Code**.
|
||||
|
||||
## OpenCode Plugin (Global)
|
||||
|
||||
OpenCode supports plugins that can intercept tool execution. RTK provides a global plugin that mirrors the Claude auto-rewrite behavior by rewriting Bash tool commands to `rtk ...` before they execute. This plugin is **not** installed by default.
|
||||
|
||||
> **Note**: This plugin uses OpenCode's `tool.execute.before` hook. Known limitation: plugin hooks do not intercept subagent tool calls ([upstream issue](https://github.com/sst/opencode/issues/5894)). See [OpenCode plugin docs](https://open-code.ai/en/docs/plugins) for API details.
|
||||
|
||||
**Install OpenCode plugin:**
|
||||
```bash
|
||||
rtk init -g --opencode
|
||||
```
|
||||
|
||||
**What it creates:**
|
||||
- `~/.config/opencode/plugins/rtk.ts`
|
||||
|
||||
**Restart Required**: Restart OpenCode, then test with `git status` in a session.
|
||||
|
||||
**Manual install (fallback):**
|
||||
```bash
|
||||
mkdir -p ~/.config/opencode/plugins
|
||||
cp hooks/opencode-rtk.ts ~/.config/opencode/plugins/rtk.ts
|
||||
```
|
||||
|
||||
### Commands Rewritten
|
||||
|
||||
| Raw Command | Rewritten To |
|
||||
|
||||
@@ -167,6 +167,39 @@ Then add to `~/.claude/settings.json` (replace `~` with full path):
|
||||
|
||||
---
|
||||
|
||||
## Problem: RTK not working in OpenCode
|
||||
|
||||
### Symptom
|
||||
OpenCode runs commands without rtk, outputs are verbose.
|
||||
|
||||
### Checklist
|
||||
|
||||
**1. Verify rtk is installed and correct:**
|
||||
```bash
|
||||
rtk --version
|
||||
rtk gain # Must show stats
|
||||
```
|
||||
|
||||
**2. Install the OpenCode plugin (global only):**
|
||||
```bash
|
||||
rtk init -g --opencode
|
||||
```
|
||||
|
||||
**3. Verify plugin file exists:**
|
||||
```bash
|
||||
ls -la ~/.config/opencode/plugins/rtk.ts
|
||||
```
|
||||
|
||||
**4. Restart OpenCode**
|
||||
OpenCode must be restarted to load the plugin.
|
||||
|
||||
**5. Verify status:**
|
||||
```bash
|
||||
rtk init --show # Should show "OpenCode: plugin installed"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Problem: "command not found: rtk" after installation
|
||||
|
||||
### Symptom
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { Plugin } from "@opencode-ai/plugin"
|
||||
|
||||
// RTK OpenCode plugin — rewrites commands to use rtk for token savings.
|
||||
// Requires: rtk >= 0.23.0 in PATH.
|
||||
//
|
||||
// This is a thin delegating plugin: all rewrite logic lives in `rtk rewrite`,
|
||||
// which is the single source of truth (src/discover/registry.rs).
|
||||
// To add or change rewrite rules, edit the Rust registry — not this file.
|
||||
|
||||
export const RtkOpenCodePlugin: Plugin = async ({ $ }) => {
|
||||
try {
|
||||
await $`which rtk`.quiet()
|
||||
} catch {
|
||||
console.warn("[rtk] rtk binary not found in PATH — plugin disabled")
|
||||
return {}
|
||||
}
|
||||
|
||||
return {
|
||||
"tool.execute.before": async (input, output) => {
|
||||
const tool = String(input?.tool ?? "").toLowerCase()
|
||||
if (tool !== "bash" && tool !== "shell") return
|
||||
const args = output?.args
|
||||
if (!args || typeof args !== "object") return
|
||||
|
||||
const command = (args as Record<string, unknown>).command
|
||||
if (typeof command !== "string" || !command) return
|
||||
|
||||
try {
|
||||
const result = await $`rtk rewrite ${command}`.quiet().nothrow()
|
||||
const rewritten = String(result.stdout).trim()
|
||||
if (rewritten && rewritten !== command) {
|
||||
;(args as Record<string, unknown>).command = rewritten
|
||||
}
|
||||
} catch {
|
||||
// rtk rewrite failed — pass through unchanged
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
+60
-9
@@ -174,7 +174,7 @@ section "git"
|
||||
bench "git status" "git status" "$RTK git status"
|
||||
bench "git log -n 10" "git log -10" "$RTK git log -n 10"
|
||||
bench "git log -n 5" "git log -5" "$RTK git log -n 5"
|
||||
bench "git diff" "git diff HEAD~1 2>/dev/null || echo ''" "$RTK git diff"
|
||||
bench "git diff" "git diff HEAD~1 2>/dev/null || echo ''" "$RTK git diff HEAD~1"
|
||||
|
||||
# ===================
|
||||
# grep
|
||||
@@ -228,13 +228,21 @@ bench "env --show-all" "env" "$RTK env --show-all"
|
||||
# err
|
||||
# ===================
|
||||
section "err"
|
||||
bench "err cargo build" "cargo build 2>&1 || true" "$RTK err cargo build"
|
||||
if command -v cargo &>/dev/null; then
|
||||
bench "err cargo build" "cargo build 2>&1 || true" "$RTK err cargo build"
|
||||
else
|
||||
echo "⏭️ err cargo build (cargo not in PATH, skipped)"
|
||||
fi
|
||||
|
||||
# ===================
|
||||
# test
|
||||
# ===================
|
||||
section "test"
|
||||
bench "test cargo test" "cargo test 2>&1 || true" "$RTK test cargo test"
|
||||
if command -v cargo &>/dev/null; then
|
||||
bench "test cargo test" "cargo test 2>&1 || true" "$RTK test cargo test"
|
||||
else
|
||||
echo "⏭️ test cargo test (cargo not in PATH, skipped)"
|
||||
fi
|
||||
|
||||
# ===================
|
||||
# log
|
||||
@@ -263,17 +271,29 @@ rm -f "$LOG_FILE"
|
||||
# summary
|
||||
# ===================
|
||||
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"
|
||||
if command -v cargo &>/dev/null; then
|
||||
bench "summary cargo --help" "cargo --help" "$RTK summary cargo --help"
|
||||
else
|
||||
echo "⏭️ summary cargo --help (cargo not in PATH, skipped)"
|
||||
fi
|
||||
if command -v rustc &>/dev/null; then
|
||||
bench "summary rustc --help" "rustc --help 2>/dev/null || echo 'rustc not found'" "$RTK summary rustc --help"
|
||||
else
|
||||
echo "⏭️ summary rustc --help (rustc not in PATH, skipped)"
|
||||
fi
|
||||
|
||||
# ===================
|
||||
# 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"
|
||||
if command -v cargo &>/dev/null; then
|
||||
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"
|
||||
else
|
||||
echo "⏭️ cargo build/test/clippy/check (cargo not in PATH, skipped)"
|
||||
fi
|
||||
|
||||
# ===================
|
||||
# diff
|
||||
@@ -506,6 +526,37 @@ GOEOF
|
||||
rm -rf "$GO_FIXTURE"
|
||||
fi
|
||||
|
||||
# ===================
|
||||
# rewrite (verify rewrite works with and without quotes)
|
||||
# ===================
|
||||
section "rewrite"
|
||||
|
||||
# bench_rewrite: verifies rewrite produces expected output (not token comparison)
|
||||
bench_rewrite() {
|
||||
local name="$1"
|
||||
local cmd="$2"
|
||||
local expected="$3"
|
||||
|
||||
result=$(eval "$cmd" 2>&1 || true)
|
||||
|
||||
TOTAL_TESTS=$((TOTAL_TESTS + 1))
|
||||
|
||||
if [ "$result" = "$expected" ]; then
|
||||
printf "✅ %-24s │ %-40s │ %s\n" "$name" "$cmd" "$result"
|
||||
GOOD_TESTS=$((GOOD_TESTS + 1))
|
||||
else
|
||||
printf "❌ %-24s │ %-40s │ got: %s (expected: %s)\n" "$name" "$cmd" "$result" "$expected"
|
||||
FAIL_TESTS=$((FAIL_TESTS + 1))
|
||||
fi
|
||||
}
|
||||
|
||||
bench_rewrite "rewrite quoted" "$RTK rewrite 'git status'" "rtk git status"
|
||||
bench_rewrite "rewrite unquoted" "$RTK rewrite git status" "rtk git status"
|
||||
bench_rewrite "rewrite ls -al" "$RTK rewrite ls -al" "rtk ls -al"
|
||||
bench_rewrite "rewrite npm exec" "$RTK rewrite npm exec" "rtk npm exec"
|
||||
bench_rewrite "rewrite cargo test" "$RTK rewrite cargo test" "rtk cargo test"
|
||||
bench_rewrite "rewrite compound" "$RTK rewrite 'cargo test && git push'" "rtk cargo test && rtk git push"
|
||||
|
||||
# ===================
|
||||
# Résumé global
|
||||
# ===================
|
||||
|
||||
+1645
File diff suppressed because it is too large.
Load diff
+36
-1
@@ -7,7 +7,10 @@ use anyhow::Result;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use provider::{ClaudeProvider, SessionProvider};
|
||||
use registry::{category_avg_tokens, classify_command, split_command_chain, Classification};
|
||||
use registry::{
|
||||
category_avg_tokens, classify_command, has_rtk_disabled_prefix, split_command_chain,
|
||||
strip_disabled_prefix, Classification,
|
||||
};
|
||||
use report::{DiscoverReport, SupportedEntry, UnsupportedEntry};
|
||||
|
||||
/// Aggregation bucket for supported commands.
|
||||
@@ -62,6 +65,8 @@ pub fn run(
|
||||
let mut total_commands: usize = 0;
|
||||
let mut already_rtk: usize = 0;
|
||||
let mut parse_errors: usize = 0;
|
||||
let mut rtk_disabled_count: usize = 0;
|
||||
let mut rtk_disabled_cmds: HashMap<String, usize> = HashMap::new();
|
||||
let mut supported_map: HashMap<&'static str, SupportedBucket> = HashMap::new();
|
||||
let mut unsupported_map: HashMap<String, UnsupportedBucket> = HashMap::new();
|
||||
|
||||
@@ -82,6 +87,23 @@ pub fn run(
|
||||
for part in parts {
|
||||
total_commands += 1;
|
||||
|
||||
// Detect RTK_DISABLED= bypass before classification
|
||||
if has_rtk_disabled_prefix(part) {
|
||||
let actual_cmd = strip_disabled_prefix(part);
|
||||
// Only count if the underlying command is one RTK supports
|
||||
match classify_command(actual_cmd) {
|
||||
Classification::Supported { .. } => {
|
||||
rtk_disabled_count += 1;
|
||||
let display = truncate_command(actual_cmd);
|
||||
*rtk_disabled_cmds.entry(display).or_insert(0) += 1;
|
||||
}
|
||||
_ => {
|
||||
// RTK_DISABLED on unsupported/ignored command — not interesting
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
match classify_command(part) {
|
||||
Classification::Supported {
|
||||
rtk_equivalent,
|
||||
@@ -198,6 +220,17 @@ pub fn run(
|
||||
// Sort by count descending
|
||||
unsupported.sort_by(|a, b| b.count.cmp(&a.count));
|
||||
|
||||
// Build RTK_DISABLED examples sorted by frequency (top 5)
|
||||
let rtk_disabled_examples: Vec<String> = {
|
||||
let mut sorted: Vec<_> = rtk_disabled_cmds.into_iter().collect();
|
||||
sorted.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
|
||||
sorted
|
||||
.into_iter()
|
||||
.take(5)
|
||||
.map(|(cmd, count)| format!("{} ({}x)", cmd, count))
|
||||
.collect()
|
||||
};
|
||||
|
||||
let report = DiscoverReport {
|
||||
sessions_scanned: sessions.len(),
|
||||
total_commands,
|
||||
@@ -206,6 +239,8 @@ pub fn run(
|
||||
supported,
|
||||
unsupported,
|
||||
parse_errors,
|
||||
rtk_disabled_count,
|
||||
rtk_disabled_examples,
|
||||
};
|
||||
|
||||
match format {
|
||||
|
||||
+175
-13
@@ -76,6 +76,26 @@ pub fn classify_command(cmd: &str) -> Classification {
|
||||
return Classification::Ignored;
|
||||
}
|
||||
|
||||
// Exclude cat/head/tail with redirect operators — these are writes, not reads (#315)
|
||||
if cmd_clean.starts_with("cat ")
|
||||
|| cmd_clean.starts_with("head ")
|
||||
|| cmd_clean.starts_with("tail ")
|
||||
{
|
||||
let has_redirect = cmd_clean
|
||||
.split_whitespace()
|
||||
.skip(1)
|
||||
.any(|t| t.starts_with('>') || t == "<" || t.starts_with(">>"));
|
||||
if has_redirect {
|
||||
return Classification::Unsupported {
|
||||
base_command: cmd_clean
|
||||
.split_whitespace()
|
||||
.next()
|
||||
.unwrap_or("cat")
|
||||
.to_string(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Fast check with RegexSet — take the last (most specific) match
|
||||
let matches: Vec<usize> = REGEX_SET.matches(cmd_clean).into_iter().collect();
|
||||
if let Some(&idx) = matches.last() {
|
||||
@@ -242,6 +262,25 @@ pub fn split_command_chain(cmd: &str) -> Vec<&str> {
|
||||
results
|
||||
}
|
||||
|
||||
/// Check if a command has RTK_DISABLED= prefix in its env prefix portion.
|
||||
pub fn has_rtk_disabled_prefix(cmd: &str) -> bool {
|
||||
let trimmed = cmd.trim();
|
||||
let stripped = ENV_PREFIX.replace(trimmed, "");
|
||||
let prefix_len = trimmed.len() - stripped.len();
|
||||
let prefix_part = &trimmed[..prefix_len];
|
||||
prefix_part.contains("RTK_DISABLED=")
|
||||
}
|
||||
|
||||
/// Strip RTK_DISABLED=X and other env prefixes, return the actual command.
|
||||
pub fn strip_disabled_prefix(cmd: &str) -> &str {
|
||||
let trimmed = cmd.trim();
|
||||
let stripped = ENV_PREFIX.replace(trimmed, "");
|
||||
// stripped is a Cow<str> that borrows from trimmed when no replacement happens.
|
||||
// We need to return a &str into the original, so compute the offset.
|
||||
let prefix_len = trimmed.len() - stripped.len();
|
||||
trimmed[prefix_len..].trim_start()
|
||||
}
|
||||
|
||||
/// Rewrite a raw command to its RTK equivalent.
|
||||
///
|
||||
/// Returns `Some(rewritten)` if the command has an RTK equivalent or is already RTK.
|
||||
@@ -431,6 +470,36 @@ fn rewrite_head_numeric(cmd: &str) -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Rewrite `tail` numeric line forms to `rtk read ... --tail-lines N`.
|
||||
/// Returns `None` when the pattern is unsupported (caller falls through / skips rewrite).
|
||||
fn rewrite_tail_lines(cmd: &str) -> Option<String> {
|
||||
lazy_static! {
|
||||
static ref TAIL_N: Regex = Regex::new(r"^tail\s+-(\d+)\s+(.+)$").expect("valid regex");
|
||||
static ref TAIL_N_SPACE: Regex =
|
||||
Regex::new(r"^tail\s+-n\s+(\d+)\s+(.+)$").expect("valid regex");
|
||||
static ref TAIL_LINES_EQ: Regex =
|
||||
Regex::new(r"^tail\s+--lines=(\d+)\s+(.+)$").expect("valid regex");
|
||||
static ref TAIL_LINES_SPACE: Regex =
|
||||
Regex::new(r"^tail\s+--lines\s+(\d+)\s+(.+)$").expect("valid regex");
|
||||
}
|
||||
|
||||
for re in [
|
||||
&*TAIL_N,
|
||||
&*TAIL_N_SPACE,
|
||||
&*TAIL_LINES_EQ,
|
||||
&*TAIL_LINES_SPACE,
|
||||
] {
|
||||
if let Some(caps) = re.captures(cmd) {
|
||||
let n = caps.get(1)?.as_str();
|
||||
let file = caps.get(2)?.as_str();
|
||||
return Some(format!("rtk read {} --tail-lines {}", file, n));
|
||||
}
|
||||
}
|
||||
|
||||
// Unknown tail form: skip rewrite to preserve native behavior.
|
||||
None
|
||||
}
|
||||
|
||||
/// Rewrite a single (non-compound) command segment.
|
||||
/// Returns `Some(rewritten)` if matched (including already-RTK pass-through).
|
||||
/// Returns `None` if no match (caller uses original segment).
|
||||
@@ -453,6 +522,12 @@ fn rewrite_segment(seg: &str, excluded: &[String]) -> Option<String> {
|
||||
return rewrite_head_numeric(trimmed);
|
||||
}
|
||||
|
||||
// tail has several forms that are not compatible with generic prefix replacement.
|
||||
// Only rewrite recognized numeric line forms; otherwise skip rewrite.
|
||||
if trimmed.starts_with("tail ") {
|
||||
return rewrite_tail_lines(trimmed);
|
||||
}
|
||||
|
||||
// Use classify_command for correct ignore/prefix handling
|
||||
let rtk_equivalent = match classify_command(trimmed) {
|
||||
Classification::Supported { rtk_equivalent, .. } => {
|
||||
@@ -476,7 +551,7 @@ fn rewrite_segment(seg: &str, excluded: &[String]) -> Option<String> {
|
||||
let cmd_clean = stripped_cow.trim();
|
||||
|
||||
// #345: RTK_DISABLED=1 in env prefix → skip rewrite entirely
|
||||
if env_prefix.contains("RTK_DISABLED=") {
|
||||
if has_rtk_disabled_prefix(trimmed) {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -592,6 +667,27 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_cat_redirect_not_supported() {
|
||||
// cat > file and cat >> file are writes, not reads — should not be classified as supported
|
||||
let write_commands = [
|
||||
"cat > /tmp/output.txt",
|
||||
"cat >> /tmp/output.txt",
|
||||
"cat file.txt > output.txt",
|
||||
"cat -n file.txt >> log.txt",
|
||||
"head -10 README.md > output.txt",
|
||||
"tail -f app.log > /dev/null",
|
||||
];
|
||||
for cmd in &write_commands {
|
||||
match classify_command(cmd) {
|
||||
Classification::Supported { .. } => {
|
||||
panic!("{} should NOT be classified as Supported", cmd)
|
||||
}
|
||||
_ => {} // Unsupported or Ignored is fine
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_cd_ignored() {
|
||||
assert_eq!(classify_command("cd /tmp"), Classification::Ignored);
|
||||
@@ -611,10 +707,10 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_terraform_unsupported() {
|
||||
match classify_command("terraform plan -var-file=prod.tfvars") {
|
||||
fn test_classify_htop_unsupported() {
|
||||
match classify_command("htop -d 10") {
|
||||
Classification::Unsupported { base_command } => {
|
||||
assert_eq!(base_command, "terraform plan");
|
||||
assert_eq!(base_command, "htop");
|
||||
}
|
||||
other => panic!("expected Unsupported, got {:?}", other),
|
||||
}
|
||||
@@ -886,8 +982,8 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_background_unsupported_right() {
|
||||
assert_eq!(
|
||||
rewrite_command("cargo test & terraform plan", &[]),
|
||||
Some("rtk cargo test & terraform plan".into())
|
||||
rewrite_command("cargo test & htop", &[]),
|
||||
Some("rtk cargo test & htop".into())
|
||||
);
|
||||
}
|
||||
|
||||
@@ -902,7 +998,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_unsupported_returns_none() {
|
||||
assert_eq!(rewrite_command("terraform plan", &[]), None);
|
||||
assert_eq!(rewrite_command("htop", &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1112,6 +1208,48 @@ mod tests {
|
||||
assert_eq!(rewrite_command("head -c 100 src/main.rs", &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_tail_numeric_flag() {
|
||||
assert_eq!(
|
||||
rewrite_command("tail -20 src/main.rs", &[]),
|
||||
Some("rtk read src/main.rs --tail-lines 20".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_tail_n_space_flag() {
|
||||
assert_eq!(
|
||||
rewrite_command("tail -n 12 src/lib.rs", &[]),
|
||||
Some("rtk read src/lib.rs --tail-lines 12".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_tail_lines_long_flag() {
|
||||
assert_eq!(
|
||||
rewrite_command("tail --lines=7 src/lib.rs", &[]),
|
||||
Some("rtk read src/lib.rs --tail-lines 7".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_tail_lines_space_flag() {
|
||||
assert_eq!(
|
||||
rewrite_command("tail --lines 7 src/lib.rs", &[]),
|
||||
Some("rtk read src/lib.rs --tail-lines 7".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_tail_other_flag_skipped() {
|
||||
assert_eq!(rewrite_command("tail -c 100 src/main.rs", &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_tail_plain_file_skipped() {
|
||||
assert_eq!(rewrite_command("tail src/main.rs", &[]), None);
|
||||
}
|
||||
|
||||
// --- New registry entries ---
|
||||
|
||||
#[test]
|
||||
@@ -1695,18 +1833,15 @@ mod tests {
|
||||
fn test_rewrite_compound_mixed_supported_unsupported() {
|
||||
// unsupported segments stay raw
|
||||
assert_eq!(
|
||||
rewrite_command("cargo test && terraform plan", &[]),
|
||||
Some("rtk cargo test && terraform plan".into())
|
||||
rewrite_command("cargo test && htop", &[]),
|
||||
Some("rtk cargo test && htop".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_compound_all_unsupported_returns_none() {
|
||||
// No rewrite at all: returns None
|
||||
assert_eq!(
|
||||
rewrite_command("terraform plan && terraform apply", &[]),
|
||||
None
|
||||
);
|
||||
assert_eq!(rewrite_command("htop && top", &[]), None);
|
||||
}
|
||||
|
||||
// --- sudo / env prefix + rewrite ---
|
||||
@@ -1857,4 +1992,31 @@ mod tests {
|
||||
Some("rtk gh pr list".into())
|
||||
);
|
||||
}
|
||||
|
||||
// --- #508: RTK_DISABLED detection helpers ---
|
||||
|
||||
#[test]
|
||||
fn test_has_rtk_disabled_prefix() {
|
||||
assert!(has_rtk_disabled_prefix("RTK_DISABLED=1 git status"));
|
||||
assert!(has_rtk_disabled_prefix("FOO=1 RTK_DISABLED=1 cargo test"));
|
||||
assert!(has_rtk_disabled_prefix(
|
||||
"RTK_DISABLED=true git log --oneline"
|
||||
));
|
||||
assert!(!has_rtk_disabled_prefix("git status"));
|
||||
assert!(!has_rtk_disabled_prefix("rtk git status"));
|
||||
assert!(!has_rtk_disabled_prefix("SOME_VAR=1 git status"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_disabled_prefix() {
|
||||
assert_eq!(
|
||||
strip_disabled_prefix("RTK_DISABLED=1 git status"),
|
||||
"git status"
|
||||
);
|
||||
assert_eq!(
|
||||
strip_disabled_prefix("FOO=1 RTK_DISABLED=1 cargo test"),
|
||||
"cargo test"
|
||||
);
|
||||
assert_eq!(strip_disabled_prefix("git status"), "git status");
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,8 @@ pub struct DiscoverReport {
|
||||
pub supported: Vec<SupportedEntry>,
|
||||
pub unsupported: Vec<UnsupportedEntry>,
|
||||
pub parse_errors: usize,
|
||||
pub rtk_disabled_count: usize,
|
||||
pub rtk_disabled_examples: Vec<String>,
|
||||
}
|
||||
|
||||
impl DiscoverReport {
|
||||
@@ -146,6 +148,21 @@ pub fn format_text(report: &DiscoverReport, limit: usize, verbose: bool) -> Stri
|
||||
out.push_str("-> github.com/rtk-ai/rtk/issues\n");
|
||||
}
|
||||
|
||||
// RTK_DISABLED bypass warning
|
||||
if report.rtk_disabled_count > 0 {
|
||||
out.push_str(&format!(
|
||||
"\nRTK_DISABLED BYPASS -- {} commands ran without filtering\n",
|
||||
report.rtk_disabled_count
|
||||
));
|
||||
out.push_str(&"-".repeat(72));
|
||||
out.push('\n');
|
||||
out.push_str("These commands used RTK_DISABLED=1 unnecessarily:\n");
|
||||
if !report.rtk_disabled_examples.is_empty() {
|
||||
out.push_str(&format!(" {}\n", report.rtk_disabled_examples.join(", ")));
|
||||
}
|
||||
out.push_str("-> Remove RTK_DISABLED=1 to recover token savings\n");
|
||||
}
|
||||
|
||||
out.push_str("\n~estimated from tool_result output sizes\n");
|
||||
|
||||
if verbose && report.parse_errors > 0 {
|
||||
|
||||
@@ -48,6 +48,39 @@ pub const PATTERNS: &[&str] = &[
|
||||
r"^aws\s+",
|
||||
// PostgreSQL
|
||||
r"^psql(\s|$)",
|
||||
// TOML-filtered commands
|
||||
r"^ansible-playbook\b",
|
||||
r"^brew\s+(install|upgrade)\b",
|
||||
r"^composer\s+(install|update|require)\b",
|
||||
r"^df(\s|$)",
|
||||
r"^dotnet\s+build\b",
|
||||
r"^du\b",
|
||||
r"^fail2ban-client\b",
|
||||
r"^gcloud\b",
|
||||
r"^hadolint\b",
|
||||
r"^helm\b",
|
||||
r"^iptables\b",
|
||||
r"^make\b",
|
||||
r"^markdownlint\b",
|
||||
r"^mix\s+(compile|format)(\s|$)",
|
||||
r"^mvn\s+(compile|package|clean|install)\b",
|
||||
r"^ping\b",
|
||||
r"^pio\s+run",
|
||||
r"^poetry\s+(install|lock|update)\b",
|
||||
r"^pre-commit\b",
|
||||
r"^ps(\s|$)",
|
||||
r"^quarto\s+render",
|
||||
r"^rsync\b",
|
||||
r"^shellcheck\b",
|
||||
r"^shopify\s+theme\s+(push|pull)",
|
||||
r"^sops\b",
|
||||
r"^swift\s+build\b",
|
||||
r"^systemctl\s+status\b",
|
||||
r"^terraform\s+plan",
|
||||
r"^tofu\s+(fmt|init|plan|validate)(\s|$)",
|
||||
r"^trunk\s+build",
|
||||
r"^uv\s+(sync|pip\s+install)\b",
|
||||
r"^yamllint\b",
|
||||
];
|
||||
|
||||
pub const RULES: &[RtkRule] = &[
|
||||
@@ -317,6 +350,263 @@ pub const RULES: &[RtkRule] = &[
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
// TOML-filtered commands
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk ansible-playbook",
|
||||
rewrite_prefixes: &["ansible-playbook"],
|
||||
category: "Infra",
|
||||
savings_pct: 70.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk brew",
|
||||
rewrite_prefixes: &["brew"],
|
||||
category: "PackageManager",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk composer",
|
||||
rewrite_prefixes: &["composer"],
|
||||
category: "PackageManager",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk df",
|
||||
rewrite_prefixes: &["df"],
|
||||
category: "System",
|
||||
savings_pct: 60.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk dotnet",
|
||||
rewrite_prefixes: &["dotnet"],
|
||||
category: "Build",
|
||||
savings_pct: 70.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk du",
|
||||
rewrite_prefixes: &["du"],
|
||||
category: "System",
|
||||
savings_pct: 60.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk fail2ban-client",
|
||||
rewrite_prefixes: &["fail2ban-client"],
|
||||
category: "Infra",
|
||||
savings_pct: 60.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk gcloud",
|
||||
rewrite_prefixes: &["gcloud"],
|
||||
category: "Infra",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk hadolint",
|
||||
rewrite_prefixes: &["hadolint"],
|
||||
category: "Build",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk helm",
|
||||
rewrite_prefixes: &["helm"],
|
||||
category: "Infra",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk iptables",
|
||||
rewrite_prefixes: &["iptables"],
|
||||
category: "Infra",
|
||||
savings_pct: 60.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk make",
|
||||
rewrite_prefixes: &["make"],
|
||||
category: "Build",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk markdownlint",
|
||||
rewrite_prefixes: &["markdownlint"],
|
||||
category: "Build",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk mix",
|
||||
rewrite_prefixes: &["mix"],
|
||||
category: "Build",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk mvn",
|
||||
rewrite_prefixes: &["mvn"],
|
||||
category: "Build",
|
||||
savings_pct: 70.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk ping",
|
||||
rewrite_prefixes: &["ping"],
|
||||
category: "Network",
|
||||
savings_pct: 60.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk pio",
|
||||
rewrite_prefixes: &["pio"],
|
||||
category: "Build",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk poetry",
|
||||
rewrite_prefixes: &["poetry"],
|
||||
category: "Python",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk pre-commit",
|
||||
rewrite_prefixes: &["pre-commit"],
|
||||
category: "Build",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk ps",
|
||||
rewrite_prefixes: &["ps"],
|
||||
category: "System",
|
||||
savings_pct: 60.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk quarto",
|
||||
rewrite_prefixes: &["quarto"],
|
||||
category: "Build",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk rsync",
|
||||
rewrite_prefixes: &["rsync"],
|
||||
category: "Network",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk shellcheck",
|
||||
rewrite_prefixes: &["shellcheck"],
|
||||
category: "Build",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk shopify",
|
||||
rewrite_prefixes: &["shopify"],
|
||||
category: "Build",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk sops",
|
||||
rewrite_prefixes: &["sops"],
|
||||
category: "Infra",
|
||||
savings_pct: 60.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk swift",
|
||||
rewrite_prefixes: &["swift"],
|
||||
category: "Build",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk systemctl",
|
||||
rewrite_prefixes: &["systemctl"],
|
||||
category: "System",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk terraform",
|
||||
rewrite_prefixes: &["terraform"],
|
||||
category: "Infra",
|
||||
savings_pct: 70.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk tofu",
|
||||
rewrite_prefixes: &["tofu"],
|
||||
category: "Infra",
|
||||
savings_pct: 70.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk trunk",
|
||||
rewrite_prefixes: &["trunk"],
|
||||
category: "Build",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk uv",
|
||||
rewrite_prefixes: &["uv"],
|
||||
category: "Python",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk yamllint",
|
||||
rewrite_prefixes: &["yamllint"],
|
||||
category: "Build",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
];
|
||||
|
||||
/// Commands to ignore (shell builtins, trivial, already rtk).
|
||||
|
||||
+1771
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,133 @@
|
||||
use anyhow::{Context, Result};
|
||||
use serde::Deserialize;
|
||||
use std::fs::File;
|
||||
use std::io::BufReader;
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
struct FormatReportEntry {
|
||||
file_path: String,
|
||||
#[serde(default)]
|
||||
file_changes: Vec<FileChange>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
struct FileChange {
|
||||
line_number: u32,
|
||||
char_number: u32,
|
||||
diagnostic_id: String,
|
||||
format_description: String,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ChangeDetail {
|
||||
pub line_number: u32,
|
||||
pub char_number: u32,
|
||||
pub diagnostic_id: String,
|
||||
pub format_description: String,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct FileWithChanges {
|
||||
pub path: String,
|
||||
pub changes: Vec<ChangeDetail>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct FormatSummary {
|
||||
pub files_with_changes: Vec<FileWithChanges>,
|
||||
pub files_unchanged: usize,
|
||||
pub total_files: usize,
|
||||
}
|
||||
|
||||
pub fn parse_format_report(path: &Path) -> Result<FormatSummary> {
|
||||
let file = File::open(path)
|
||||
.with_context(|| format!("Failed to read dotnet format report at {}", path.display()))?;
|
||||
let reader = BufReader::new(file);
|
||||
|
||||
let entries: Vec<FormatReportEntry> = serde_json::from_reader(reader).with_context(|| {
|
||||
format!(
|
||||
"Failed to parse dotnet format report JSON at {}",
|
||||
path.display()
|
||||
)
|
||||
})?;
|
||||
|
||||
let total_files = entries.len();
|
||||
let files_with_changes: Vec<FileWithChanges> = entries
|
||||
.into_iter()
|
||||
.filter_map(|entry| {
|
||||
if entry.file_changes.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let changes = entry
|
||||
.file_changes
|
||||
.into_iter()
|
||||
.map(|change| ChangeDetail {
|
||||
line_number: change.line_number,
|
||||
char_number: change.char_number,
|
||||
diagnostic_id: change.diagnostic_id,
|
||||
format_description: change.format_description,
|
||||
})
|
||||
.collect();
|
||||
|
||||
Some(FileWithChanges {
|
||||
path: entry.file_path,
|
||||
changes,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let files_unchanged = total_files.saturating_sub(files_with_changes.len());
|
||||
|
||||
Ok(FormatSummary {
|
||||
files_with_changes,
|
||||
files_unchanged,
|
||||
total_files,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn fixture(name: &str) -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("tests")
|
||||
.join("fixtures")
|
||||
.join("dotnet")
|
||||
.join(name)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_format_report_all_formatted() {
|
||||
let summary = parse_format_report(&fixture("format_success.json")).expect("parse report");
|
||||
|
||||
assert_eq!(summary.total_files, 2);
|
||||
assert_eq!(summary.files_unchanged, 2);
|
||||
assert!(summary.files_with_changes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_format_report_with_changes() {
|
||||
let summary = parse_format_report(&fixture("format_changes.json")).expect("parse report");
|
||||
|
||||
assert_eq!(summary.total_files, 3);
|
||||
assert_eq!(summary.files_unchanged, 1);
|
||||
assert_eq!(summary.files_with_changes.len(), 2);
|
||||
assert!(summary.files_with_changes[0].path.contains("Program.cs"));
|
||||
assert_eq!(summary.files_with_changes[0].changes[0].line_number, 42);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_format_report_empty() {
|
||||
let summary = parse_format_report(&fixture("format_empty.json")).expect("parse report");
|
||||
|
||||
assert_eq!(summary.total_files, 0);
|
||||
assert_eq!(summary.files_unchanged, 0);
|
||||
assert!(summary.files_with_changes.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,593 @@
|
||||
use crate::binlog::{FailedTest, TestSummary};
|
||||
use chrono::{DateTime, FixedOffset};
|
||||
use quick_xml::events::{BytesStart, Event};
|
||||
use quick_xml::Reader;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
|
||||
fn local_name(name: &[u8]) -> &[u8] {
|
||||
name.rsplit(|b| *b == b':').next().unwrap_or(name)
|
||||
}
|
||||
|
||||
fn extract_attr_value(
|
||||
reader: &Reader<&[u8]>,
|
||||
start: &BytesStart<'_>,
|
||||
key: &[u8],
|
||||
) -> Option<String> {
|
||||
for attr in start.attributes().flatten() {
|
||||
if local_name(attr.key.as_ref()) != key {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Ok(value) = attr.decode_and_unescape_value(reader.decoder()) {
|
||||
return Some(value.into_owned());
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn parse_usize_attr(reader: &Reader<&[u8]>, start: &BytesStart<'_>, key: &[u8]) -> usize {
|
||||
extract_attr_value(reader, start, key)
|
||||
.and_then(|v| v.parse::<usize>().ok())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
fn parse_trx_duration(start: &str, finish: &str) -> Option<String> {
|
||||
let start_dt = DateTime::parse_from_rfc3339(start).ok()?;
|
||||
let finish_dt = DateTime::parse_from_rfc3339(finish).ok()?;
|
||||
format_duration_between(start_dt, finish_dt)
|
||||
}
|
||||
|
||||
fn format_duration_between(
|
||||
start_dt: DateTime<FixedOffset>,
|
||||
finish_dt: DateTime<FixedOffset>,
|
||||
) -> Option<String> {
|
||||
let diff = finish_dt.signed_duration_since(start_dt);
|
||||
let millis = diff.num_milliseconds();
|
||||
if millis <= 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
if millis >= 1_000 {
|
||||
let seconds = millis as f64 / 1_000.0;
|
||||
return Some(format!("{seconds:.1} s"));
|
||||
}
|
||||
|
||||
Some(format!("{millis} ms"))
|
||||
}
|
||||
|
||||
fn parse_trx_time_bounds(content: &str) -> Option<(DateTime<FixedOffset>, DateTime<FixedOffset>)> {
|
||||
let mut reader = Reader::from_str(content);
|
||||
reader.config_mut().trim_text(true);
|
||||
let mut buf = Vec::new();
|
||||
|
||||
loop {
|
||||
match reader.read_event_into(&mut buf) {
|
||||
Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
|
||||
if local_name(e.name().as_ref()) != b"Times" {
|
||||
buf.clear();
|
||||
continue;
|
||||
}
|
||||
|
||||
let start = extract_attr_value(&reader, &e, b"start")?;
|
||||
let finish = extract_attr_value(&reader, &e, b"finish")?;
|
||||
let start_dt = DateTime::parse_from_rfc3339(&start).ok()?;
|
||||
let finish_dt = DateTime::parse_from_rfc3339(&finish).ok()?;
|
||||
return Some((start_dt, finish_dt));
|
||||
}
|
||||
Ok(Event::Eof) => break,
|
||||
Err(_) => return None,
|
||||
_ => {}
|
||||
}
|
||||
|
||||
buf.clear();
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// Parse TRX (Visual Studio Test Results) file to extract test summary.
|
||||
/// Returns None if the file doesn't exist or isn't a valid TRX file.
|
||||
pub fn parse_trx_file(path: &Path) -> Option<TestSummary> {
|
||||
let content = std::fs::read_to_string(path).ok()?;
|
||||
parse_trx_content(&content)
|
||||
}
|
||||
|
||||
pub fn parse_trx_file_since(path: &Path, since: SystemTime) -> Option<TestSummary> {
|
||||
let modified = std::fs::metadata(path).ok()?.modified().ok()?;
|
||||
if modified < since {
|
||||
return None;
|
||||
}
|
||||
|
||||
parse_trx_file(path)
|
||||
}
|
||||
|
||||
pub fn parse_trx_files_in_dir(dir: &Path) -> Option<TestSummary> {
|
||||
parse_trx_files_in_dir_since(dir, None)
|
||||
}
|
||||
|
||||
pub fn parse_trx_files_in_dir_since(dir: &Path, since: Option<SystemTime>) -> Option<TestSummary> {
|
||||
if !dir.exists() || !dir.is_dir() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut summaries = Vec::new();
|
||||
let mut min_start: Option<DateTime<FixedOffset>> = None;
|
||||
let mut max_finish: Option<DateTime<FixedOffset>> = None;
|
||||
let entries = std::fs::read_dir(dir).ok()?;
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path
|
||||
.extension()
|
||||
.is_none_or(|e| !e.eq_ignore_ascii_case("trx"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(since) = since {
|
||||
let modified = match entry.metadata().ok().and_then(|m| m.modified().ok()) {
|
||||
Some(modified) => modified,
|
||||
None => continue,
|
||||
};
|
||||
if modified < since {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
let content = match std::fs::read_to_string(&path) {
|
||||
Ok(content) => content,
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
if let Some((start, finish)) = parse_trx_time_bounds(&content) {
|
||||
min_start = Some(min_start.map_or(start, |prev| prev.min(start)));
|
||||
max_finish = Some(max_finish.map_or(finish, |prev| prev.max(finish)));
|
||||
}
|
||||
|
||||
if let Some(summary) = parse_trx_content(&content) {
|
||||
summaries.push(summary);
|
||||
}
|
||||
}
|
||||
|
||||
if summaries.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut merged = TestSummary::default();
|
||||
for summary in summaries {
|
||||
merged.passed += summary.passed;
|
||||
merged.failed += summary.failed;
|
||||
merged.skipped += summary.skipped;
|
||||
merged.total += summary.total;
|
||||
merged.failed_tests.extend(summary.failed_tests);
|
||||
merged.project_count += summary.project_count.max(1);
|
||||
if merged.duration_text.is_none() {
|
||||
merged.duration_text = summary.duration_text;
|
||||
}
|
||||
}
|
||||
|
||||
if let (Some(start), Some(finish)) = (min_start, max_finish) {
|
||||
merged.duration_text = format_duration_between(start, finish);
|
||||
}
|
||||
|
||||
Some(merged)
|
||||
}
|
||||
|
||||
pub fn find_recent_trx_in_testresults() -> Option<PathBuf> {
|
||||
find_recent_trx_in_dir(Path::new("./TestResults"))
|
||||
}
|
||||
|
||||
fn find_recent_trx_in_dir(dir: &Path) -> Option<PathBuf> {
|
||||
if !dir.exists() {
|
||||
return None;
|
||||
}
|
||||
|
||||
std::fs::read_dir(dir)
|
||||
.ok()?
|
||||
.filter_map(|entry| entry.ok())
|
||||
.filter_map(|entry| {
|
||||
let path = entry.path();
|
||||
let is_trx = path
|
||||
.extension()
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("trx"));
|
||||
if !is_trx {
|
||||
return None;
|
||||
}
|
||||
|
||||
let modified = entry.metadata().ok()?.modified().ok()?;
|
||||
Some((modified, path))
|
||||
})
|
||||
.max_by_key(|(modified, _)| *modified)
|
||||
.map(|(_, path)| path)
|
||||
}
|
||||
|
||||
fn parse_trx_content(content: &str) -> Option<TestSummary> {
|
||||
#[derive(Clone, Copy)]
|
||||
enum CaptureField {
|
||||
Message,
|
||||
StackTrace,
|
||||
}
|
||||
|
||||
let mut reader = Reader::from_str(content);
|
||||
reader.config_mut().trim_text(true);
|
||||
let mut buf = Vec::new();
|
||||
let mut summary = TestSummary::default();
|
||||
let mut saw_test_run = false;
|
||||
let mut in_failed_result = false;
|
||||
let mut in_error_info = false;
|
||||
let mut failed_test_name = String::new();
|
||||
let mut message_buf = String::new();
|
||||
let mut stack_buf = String::new();
|
||||
let mut capture_field: Option<CaptureField> = None;
|
||||
|
||||
loop {
|
||||
match reader.read_event_into(&mut buf) {
|
||||
Ok(Event::Start(e)) => match local_name(e.name().as_ref()) {
|
||||
b"TestRun" => saw_test_run = true,
|
||||
b"Times" => {
|
||||
let start = extract_attr_value(&reader, &e, b"start");
|
||||
let finish = extract_attr_value(&reader, &e, b"finish");
|
||||
if let (Some(start), Some(finish)) = (start, finish) {
|
||||
summary.duration_text = parse_trx_duration(&start, &finish);
|
||||
}
|
||||
}
|
||||
b"Counters" => {
|
||||
summary.total = parse_usize_attr(&reader, &e, b"total");
|
||||
summary.passed = parse_usize_attr(&reader, &e, b"passed");
|
||||
summary.failed = parse_usize_attr(&reader, &e, b"failed");
|
||||
}
|
||||
b"UnitTestResult" => {
|
||||
let outcome = extract_attr_value(&reader, &e, b"outcome")
|
||||
.unwrap_or_else(|| "Unknown".to_string());
|
||||
|
||||
if outcome == "Failed" {
|
||||
in_failed_result = true;
|
||||
in_error_info = false;
|
||||
capture_field = None;
|
||||
message_buf.clear();
|
||||
stack_buf.clear();
|
||||
failed_test_name = extract_attr_value(&reader, &e, b"testName")
|
||||
.unwrap_or_else(|| "unknown".to_string());
|
||||
}
|
||||
}
|
||||
b"ErrorInfo" => {
|
||||
if in_failed_result {
|
||||
in_error_info = true;
|
||||
}
|
||||
}
|
||||
b"Message" => {
|
||||
if in_failed_result && in_error_info {
|
||||
capture_field = Some(CaptureField::Message);
|
||||
message_buf.clear();
|
||||
}
|
||||
}
|
||||
b"StackTrace" => {
|
||||
if in_failed_result && in_error_info {
|
||||
capture_field = Some(CaptureField::StackTrace);
|
||||
stack_buf.clear();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Ok(Event::Empty(e)) => match local_name(e.name().as_ref()) {
|
||||
b"Times" => {
|
||||
let start = extract_attr_value(&reader, &e, b"start");
|
||||
let finish = extract_attr_value(&reader, &e, b"finish");
|
||||
if let (Some(start), Some(finish)) = (start, finish) {
|
||||
summary.duration_text = parse_trx_duration(&start, &finish);
|
||||
}
|
||||
}
|
||||
b"Counters" => {
|
||||
summary.total = parse_usize_attr(&reader, &e, b"total");
|
||||
summary.passed = parse_usize_attr(&reader, &e, b"passed");
|
||||
summary.failed = parse_usize_attr(&reader, &e, b"failed");
|
||||
}
|
||||
b"UnitTestResult" => {
|
||||
let outcome = extract_attr_value(&reader, &e, b"outcome")
|
||||
.unwrap_or_else(|| "Unknown".to_string());
|
||||
if outcome == "Failed" {
|
||||
let name = extract_attr_value(&reader, &e, b"testName")
|
||||
.unwrap_or_else(|| "unknown".to_string());
|
||||
summary.failed_tests.push(FailedTest {
|
||||
name,
|
||||
details: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Ok(Event::Text(e)) => {
|
||||
if !in_failed_result {
|
||||
buf.clear();
|
||||
continue;
|
||||
}
|
||||
|
||||
let text = String::from_utf8_lossy(e.as_ref());
|
||||
match capture_field {
|
||||
Some(CaptureField::Message) => message_buf.push_str(&text),
|
||||
Some(CaptureField::StackTrace) => stack_buf.push_str(&text),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
Ok(Event::CData(e)) => {
|
||||
if !in_failed_result {
|
||||
buf.clear();
|
||||
continue;
|
||||
}
|
||||
|
||||
let text = String::from_utf8_lossy(e.as_ref());
|
||||
match capture_field {
|
||||
Some(CaptureField::Message) => message_buf.push_str(&text),
|
||||
Some(CaptureField::StackTrace) => stack_buf.push_str(&text),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
Ok(Event::End(e)) => match local_name(e.name().as_ref()) {
|
||||
b"Message" | b"StackTrace" => {
|
||||
capture_field = None;
|
||||
}
|
||||
b"ErrorInfo" => {
|
||||
in_error_info = false;
|
||||
}
|
||||
b"UnitTestResult" => {
|
||||
if in_failed_result {
|
||||
let mut details = Vec::new();
|
||||
|
||||
let message = message_buf.trim();
|
||||
if !message.is_empty() {
|
||||
details.push(message.to_string());
|
||||
}
|
||||
|
||||
let stack = stack_buf.trim();
|
||||
if !stack.is_empty() {
|
||||
let stack_lines: Vec<&str> = stack.lines().take(3).collect();
|
||||
if !stack_lines.is_empty() {
|
||||
details.push(stack_lines.join("\n"));
|
||||
}
|
||||
}
|
||||
|
||||
summary.failed_tests.push(FailedTest {
|
||||
name: failed_test_name.clone(),
|
||||
details,
|
||||
});
|
||||
|
||||
in_failed_result = false;
|
||||
in_error_info = false;
|
||||
capture_field = None;
|
||||
message_buf.clear();
|
||||
stack_buf.clear();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Ok(Event::Eof) => break,
|
||||
Err(_) => return None,
|
||||
_ => {}
|
||||
}
|
||||
|
||||
buf.clear();
|
||||
}
|
||||
|
||||
if !saw_test_run {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Calculate skipped from counters if available
|
||||
if summary.total > 0 {
|
||||
summary.skipped = summary
|
||||
.total
|
||||
.saturating_sub(summary.passed + summary.failed);
|
||||
}
|
||||
|
||||
// Set project count to at least 1 if there were any tests
|
||||
if summary.total > 0 {
|
||||
summary.project_count = 1;
|
||||
}
|
||||
|
||||
Some(summary)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
fn test_parse_trx_content_extracts_passed_counts() {
|
||||
let trx = r#"<?xml version="1.0" encoding="utf-8"?>
|
||||
<TestRun xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010">
|
||||
<Times creation="2026-02-21T12:57:28.3323710+01:00" queuing="2026-02-21T12:57:28.3323710+01:00" start="2026-02-21T12:57:27.7149650+01:00" finish="2026-02-21T12:57:30.2214710+01:00" />
|
||||
<ResultSummary outcome="Completed">
|
||||
<Counters total="42" executed="42" passed="40" failed="2" error="0" timeout="0" aborted="0" inconclusive="0" />
|
||||
</ResultSummary>
|
||||
</TestRun>"#;
|
||||
|
||||
let summary = parse_trx_content(trx).expect("valid TRX");
|
||||
assert_eq!(summary.total, 42);
|
||||
assert_eq!(summary.passed, 40);
|
||||
assert_eq!(summary.failed, 2);
|
||||
assert_eq!(summary.skipped, 0);
|
||||
assert_eq!(summary.duration_text.as_deref(), Some("2.5 s"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_trx_content_extracts_failed_tests_with_details() {
|
||||
let trx = r#"<?xml version="1.0" encoding="utf-8"?>
|
||||
<TestRun>
|
||||
<Results>
|
||||
<UnitTestResult testName="MyTests.Calculator.Add_ShouldFail" outcome="Failed">
|
||||
<Output>
|
||||
<ErrorInfo>
|
||||
<Message>Expected: 5, Actual: 4</Message>
|
||||
<StackTrace>at MyTests.Calculator.Add_ShouldFail()\nat line 42</StackTrace>
|
||||
</ErrorInfo>
|
||||
</Output>
|
||||
</UnitTestResult>
|
||||
</Results>
|
||||
<ResultSummary><Counters total="1" executed="1" passed="0" failed="1" /></ResultSummary>
|
||||
</TestRun>"#;
|
||||
|
||||
let summary = parse_trx_content(trx).expect("valid TRX");
|
||||
assert_eq!(summary.failed_tests.len(), 1);
|
||||
assert_eq!(
|
||||
summary.failed_tests[0].name,
|
||||
"MyTests.Calculator.Add_ShouldFail"
|
||||
);
|
||||
assert!(summary.failed_tests[0].details[0].contains("Expected: 5, Actual: 4"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_trx_content_extracts_counters_when_attribute_order_varies() {
|
||||
let trx = r#"<?xml version="1.0" encoding="utf-8"?>
|
||||
<TestRun>
|
||||
<ResultSummary outcome="Completed">
|
||||
<Counters failed="3" passed="7" executed="10" total="10" />
|
||||
</ResultSummary>
|
||||
</TestRun>"#;
|
||||
|
||||
let summary = parse_trx_content(trx).expect("valid TRX");
|
||||
assert_eq!(summary.total, 10);
|
||||
assert_eq!(summary.passed, 7);
|
||||
assert_eq!(summary.failed, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_trx_content_extracts_failed_tests_when_attribute_order_varies() {
|
||||
let trx = r#"<?xml version="1.0" encoding="utf-8"?>
|
||||
<TestRun>
|
||||
<Results>
|
||||
<UnitTestResult outcome="Failed" testName="MyTests.Ordering.ShouldStillParse">
|
||||
<Output>
|
||||
<ErrorInfo>
|
||||
<Message>Boom</Message>
|
||||
<StackTrace>at MyTests.Ordering.ShouldStillParse()</StackTrace>
|
||||
</ErrorInfo>
|
||||
</Output>
|
||||
</UnitTestResult>
|
||||
</Results>
|
||||
<ResultSummary><Counters failed="1" passed="0" executed="1" total="1" /></ResultSummary>
|
||||
</TestRun>"#;
|
||||
|
||||
let summary = parse_trx_content(trx).expect("valid TRX");
|
||||
assert_eq!(summary.failed, 1);
|
||||
assert_eq!(summary.failed_tests.len(), 1);
|
||||
assert_eq!(
|
||||
summary.failed_tests[0].name,
|
||||
"MyTests.Ordering.ShouldStillParse"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_trx_content_returns_none_for_invalid_xml() {
|
||||
let not_trx = "This is not a TRX file";
|
||||
assert!(parse_trx_content(not_trx).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_find_recent_trx_in_dir_returns_none_when_missing() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let missing_dir = temp_dir.path().join("TestResults");
|
||||
|
||||
let found = find_recent_trx_in_dir(&missing_dir);
|
||||
assert!(found.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_find_recent_trx_in_dir_picks_newest_trx() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let testresults_dir = temp_dir.path().join("TestResults");
|
||||
std::fs::create_dir_all(&testresults_dir).expect("create TestResults");
|
||||
|
||||
let old_trx = testresults_dir.join("old.trx");
|
||||
let new_trx = testresults_dir.join("new.trx");
|
||||
std::fs::write(&old_trx, "old").expect("write old");
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
std::fs::write(&new_trx, "new").expect("write new");
|
||||
|
||||
let found = find_recent_trx_in_dir(&testresults_dir).expect("should find newest trx");
|
||||
assert_eq!(found, new_trx);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_find_recent_trx_in_dir_ignores_non_trx_files() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let testresults_dir = temp_dir.path().join("TestResults");
|
||||
std::fs::create_dir_all(&testresults_dir).expect("create TestResults");
|
||||
|
||||
let txt = testresults_dir.join("notes.txt");
|
||||
std::fs::write(&txt, "noop").expect("write txt");
|
||||
|
||||
let found = find_recent_trx_in_dir(&testresults_dir);
|
||||
assert!(found.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_trx_files_in_dir_aggregates_counts_and_wall_clock_duration() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let trx_dir = temp_dir.path().join("TestResults");
|
||||
std::fs::create_dir_all(&trx_dir).expect("create TestResults");
|
||||
|
||||
let trx_one = r#"<?xml version="1.0" encoding="utf-8"?>
|
||||
<TestRun>
|
||||
<Times start="2026-02-21T12:57:27.0000000+01:00" finish="2026-02-21T12:57:30.0000000+01:00" />
|
||||
<ResultSummary outcome="Completed">
|
||||
<Counters total="10" executed="10" passed="9" failed="1" />
|
||||
</ResultSummary>
|
||||
</TestRun>"#;
|
||||
|
||||
let trx_two = r#"<?xml version="1.0" encoding="utf-8"?>
|
||||
<TestRun>
|
||||
<Times start="2026-02-21T12:57:28.0000000+01:00" finish="2026-02-21T12:57:29.0000000+01:00" />
|
||||
<ResultSummary outcome="Completed">
|
||||
<Counters total="20" executed="20" passed="20" failed="0" />
|
||||
</ResultSummary>
|
||||
</TestRun>"#;
|
||||
|
||||
std::fs::write(trx_dir.join("a.trx"), trx_one).expect("write first trx");
|
||||
std::fs::write(trx_dir.join("b.trx"), trx_two).expect("write second trx");
|
||||
|
||||
let summary = parse_trx_files_in_dir(&trx_dir).expect("merged summary");
|
||||
assert_eq!(summary.total, 30);
|
||||
assert_eq!(summary.passed, 29);
|
||||
assert_eq!(summary.failed, 1);
|
||||
assert_eq!(summary.duration_text.as_deref(), Some("3.0 s"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_trx_files_in_dir_since_ignores_older_files() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let trx_dir = temp_dir.path().join("TestResults");
|
||||
std::fs::create_dir_all(&trx_dir).expect("create TestResults");
|
||||
|
||||
let trx_old = r#"<?xml version="1.0" encoding="utf-8"?>
|
||||
<TestRun><ResultSummary><Counters total="2" executed="2" passed="2" failed="0" /></ResultSummary></TestRun>"#;
|
||||
std::fs::write(trx_dir.join("old.trx"), trx_old).expect("write old trx");
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
let since = SystemTime::now();
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
|
||||
let trx_new = r#"<?xml version="1.0" encoding="utf-8"?>
|
||||
<TestRun><ResultSummary><Counters total="3" executed="3" passed="2" failed="1" /></ResultSummary></TestRun>"#;
|
||||
std::fs::write(trx_dir.join("new.trx"), trx_new).expect("write new trx");
|
||||
|
||||
let summary = parse_trx_files_in_dir_since(&trx_dir, Some(since)).expect("merged summary");
|
||||
assert_eq!(summary.total, 3);
|
||||
assert_eq!(summary.failed, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_trx_files_in_dir_since_handles_uppercase_extension() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let trx_dir = temp_dir.path().join("TestResults");
|
||||
std::fs::create_dir_all(&trx_dir).expect("create TestResults");
|
||||
|
||||
let trx = r#"<?xml version="1.0" encoding="utf-8"?>
|
||||
<TestRun><ResultSummary><Counters total="3" executed="3" passed="2" failed="1" /></ResultSummary></TestRun>"#;
|
||||
std::fs::write(trx_dir.join("UPPER.TRX"), trx).expect("write trx");
|
||||
|
||||
let summary = parse_trx_files_in_dir_since(&trx_dir, None).expect("summary");
|
||||
assert_eq!(summary.total, 3);
|
||||
assert_eq!(summary.failed, 1);
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,7 @@ pub enum Language {
|
||||
Java,
|
||||
Ruby,
|
||||
Shell,
|
||||
Data,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
@@ -66,6 +67,9 @@ impl Language {
|
||||
"java" => Language::Java,
|
||||
"rb" => Language::Ruby,
|
||||
"sh" | "bash" | "zsh" => Language::Shell,
|
||||
"json" | "jsonc" | "json5" | "yaml" | "yml" | "toml" | "xml" | "html" | "htm"
|
||||
| "css" | "scss" | "svg" | "md" | "markdown" | "txt" | "csv" | "tsv" | "env"
|
||||
| "ini" | "cfg" | "conf" | "lock" => Language::Data,
|
||||
_ => Language::Unknown,
|
||||
}
|
||||
}
|
||||
@@ -112,6 +116,13 @@ impl Language {
|
||||
doc_line: None,
|
||||
doc_block_start: None,
|
||||
},
|
||||
Language::Data => CommentPatterns {
|
||||
line: None,
|
||||
block_start: None,
|
||||
block_end: None,
|
||||
doc_line: None,
|
||||
doc_block_start: None,
|
||||
},
|
||||
Language::Unknown => CommentPatterns {
|
||||
line: Some("//"),
|
||||
block_start: Some("/*"),
|
||||
@@ -389,6 +400,52 @@ mod tests {
|
||||
assert_eq!(Language::from_extension("js"), Language::JavaScript);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_language_detection_data_formats() {
|
||||
assert_eq!(Language::from_extension("json"), Language::Data);
|
||||
assert_eq!(Language::from_extension("yaml"), Language::Data);
|
||||
assert_eq!(Language::from_extension("yml"), Language::Data);
|
||||
assert_eq!(Language::from_extension("toml"), Language::Data);
|
||||
assert_eq!(Language::from_extension("xml"), Language::Data);
|
||||
assert_eq!(Language::from_extension("md"), Language::Data);
|
||||
assert_eq!(Language::from_extension("csv"), Language::Data);
|
||||
assert_eq!(Language::from_extension("lock"), Language::Data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_data_files_no_comment_stripping() {
|
||||
// Regression test for #464: package.json with `/*` in strings
|
||||
let json = r#"{
|
||||
"workspaces": {
|
||||
"packages": [
|
||||
"packages/*"
|
||||
]
|
||||
},
|
||||
"scripts": {
|
||||
"build": "bun run --workspaces build"
|
||||
},
|
||||
"lint-staged": {
|
||||
"**/package.json": [
|
||||
"sort-package-json"
|
||||
]
|
||||
}
|
||||
}"#;
|
||||
let filter = MinimalFilter;
|
||||
let result = filter.filter(json, &Language::Data);
|
||||
assert!(
|
||||
result.contains("scripts"),
|
||||
"scripts section must be preserved"
|
||||
);
|
||||
assert!(
|
||||
result.contains("packages/*"),
|
||||
"glob pattern must be preserved"
|
||||
);
|
||||
assert!(
|
||||
result.contains("**/package.json"),
|
||||
"glob pattern must be preserved"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_minimal_filter_removes_comments() {
|
||||
let code = r#"
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
[filters.basedpyright]
|
||||
description = "Compact basedpyright type checker output — strip blank lines, keep errors"
|
||||
match_command = "^basedpyright\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^Searching for source files",
|
||||
"^Found \\d+ source file",
|
||||
"^Pyright \\d+\\.\\d+",
|
||||
"^basedpyright \\d+\\.\\d+",
|
||||
]
|
||||
max_lines = 50
|
||||
on_empty = "basedpyright: ok"
|
||||
|
||||
[[tests.basedpyright]]
|
||||
name = "strips noise, keeps errors and summary"
|
||||
input = """
|
||||
basedpyright 1.22.0
|
||||
Searching for source files
|
||||
Found 42 source files
|
||||
|
||||
/home/user/app/main.py
|
||||
/home/user/app/main.py:10:5 - error: "foo" is not defined (reportUndefinedVariable)
|
||||
/home/user/app/main.py:25:1 - error: Type "str" is not assignable to type "int" (reportAssignmentType)
|
||||
|
||||
/home/user/app/utils.py
|
||||
/home/user/app/utils.py:8:9 - warning: Variable "x" is not accessed (reportUnusedVariable)
|
||||
|
||||
3 errors, 1 warning, 0 informations
|
||||
"""
|
||||
expected = "/home/user/app/main.py\n /home/user/app/main.py:10:5 - error: \"foo\" is not defined (reportUndefinedVariable)\n /home/user/app/main.py:25:1 - error: Type \"str\" is not assignable to type \"int\" (reportAssignmentType)\n/home/user/app/utils.py\n /home/user/app/utils.py:8:9 - warning: Variable \"x\" is not accessed (reportUnusedVariable)\n3 errors, 1 warning, 0 informations"
|
||||
|
||||
[[tests.basedpyright]]
|
||||
name = "clean output"
|
||||
input = """
|
||||
basedpyright 1.22.0
|
||||
Searching for source files
|
||||
Found 10 source files
|
||||
|
||||
0 errors, 0 warnings, 0 informations
|
||||
"""
|
||||
expected = "0 errors, 0 warnings, 0 informations"
|
||||
|
||||
[[tests.basedpyright]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -0,0 +1,45 @@
|
||||
[filters.biome]
|
||||
description = "Compact Biome lint/format output — strip blank lines, keep diagnostics"
|
||||
match_command = "^biome\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^Checked \\d+ file",
|
||||
"^Fixed \\d+ file",
|
||||
"^The following command",
|
||||
"^Run it with",
|
||||
]
|
||||
max_lines = 50
|
||||
on_empty = "biome: ok"
|
||||
|
||||
[[tests.biome]]
|
||||
name = "lint strips noise, keeps diagnostics"
|
||||
input = """
|
||||
Checked 42 files in 0.5s
|
||||
|
||||
src/app.tsx:5:3 lint/suspicious/noExplicitAny ━━━━━━━━━━━━━━━━━━━━
|
||||
× Unexpected any. Specify a different type.
|
||||
3 │ interface Props {
|
||||
4 │ data: any;
|
||||
5 │ ^^^
|
||||
|
||||
src/utils.ts:12:1 lint/complexity/noForEach ━━━━━━━━━━━━━━━━━━━━
|
||||
× Prefer for...of instead of forEach.
|
||||
12 │ items.forEach(item => process(item));
|
||||
│ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Found 2 errors.
|
||||
"""
|
||||
expected = "src/app.tsx:5:3 lint/suspicious/noExplicitAny ━━━━━━━━━━━━━━━━━━━━\n × Unexpected any. Specify a different type.\n 3 │ interface Props {\n 4 │ data: any;\n 5 │ ^^^\nsrc/utils.ts:12:1 lint/complexity/noForEach ━━━━━━━━━━━━━━━━━━━━\n × Prefer for...of instead of forEach.\n 12 │ items.forEach(item => process(item));\n │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nFound 2 errors."
|
||||
|
||||
[[tests.biome]]
|
||||
name = "clean check"
|
||||
input = """
|
||||
Checked 42 files in 0.3s
|
||||
"""
|
||||
expected = "biome: ok"
|
||||
|
||||
[[tests.biome]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -0,0 +1,49 @@
|
||||
[filters.gcc]
|
||||
description = "Compact gcc/g++ compiler output — strip notes, keep errors and warnings"
|
||||
match_command = "^g(cc|\\+\\+)\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^\\s+\\|\\s*$",
|
||||
"^In file included from",
|
||||
"^\\s+from\\s",
|
||||
"^\\d+ warnings? generated",
|
||||
"^\\d+ errors? generated",
|
||||
]
|
||||
max_lines = 50
|
||||
on_empty = "gcc: ok"
|
||||
|
||||
[[tests.gcc]]
|
||||
name = "strips include chain, keeps errors and warnings"
|
||||
input = """
|
||||
In file included from /usr/include/stdio.h:42:
|
||||
from main.c:1:
|
||||
main.c:10:5: error: use of undeclared identifier 'foo'
|
||||
foo();
|
||||
^
|
||||
main.c:15:12: warning: unused variable 'x' [-Wunused-variable]
|
||||
int x = 42;
|
||||
^
|
||||
2 warnings generated.
|
||||
1 error generated.
|
||||
"""
|
||||
expected = "main.c:10:5: error: use of undeclared identifier 'foo'\n foo();\n ^\nmain.c:15:12: warning: unused variable 'x' [-Wunused-variable]\n int x = 42;\n ^"
|
||||
|
||||
[[tests.gcc]]
|
||||
name = "clean compilation"
|
||||
input = """
|
||||
"""
|
||||
expected = "gcc: ok"
|
||||
|
||||
[[tests.gcc]]
|
||||
name = "linker error kept"
|
||||
input = """
|
||||
/usr/bin/ld: /tmp/main.o: undefined reference to 'missing_func'
|
||||
collect2: error: ld returned 1 exit status
|
||||
"""
|
||||
expected = "/usr/bin/ld: /tmp/main.o: undefined reference to 'missing_func'\ncollect2: error: ld returned 1 exit status"
|
||||
|
||||
[[tests.gcc]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -0,0 +1,28 @@
|
||||
[filters.jj]
|
||||
description = "Compact Jujutsu (jj) output — strip blank lines, truncate"
|
||||
match_command = "^jj\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^Hint:",
|
||||
"^Working copy now at:",
|
||||
]
|
||||
max_lines = 30
|
||||
truncate_lines_at = 120
|
||||
|
||||
[[tests.jj]]
|
||||
name = "log output stripped of hints"
|
||||
input = """
|
||||
@ qpvuntsm patrick@example.com 2026-03-10 12:00 abc123
|
||||
│ feat: add new feature
|
||||
◉ zzzzzzzz root()
|
||||
|
||||
Working copy now at: qpvuntsm abc123 feat: add new feature
|
||||
Hint: use `jj log` to see the full history
|
||||
"""
|
||||
expected = "@ qpvuntsm patrick@example.com 2026-03-10 12:00 abc123\n│ feat: add new feature\n◉ zzzzzzzz root()"
|
||||
|
||||
[[tests.jj]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -0,0 +1,24 @@
|
||||
[filters.jq]
|
||||
description = "Compact jq output — truncate large JSON results"
|
||||
match_command = "^jq\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
]
|
||||
max_lines = 40
|
||||
truncate_lines_at = 120
|
||||
|
||||
[[tests.jq]]
|
||||
name = "short output passes through"
|
||||
input = """
|
||||
{
|
||||
"name": "test",
|
||||
"version": "1.0"
|
||||
}
|
||||
"""
|
||||
expected = "{\n \"name\": \"test\",\n \"version\": \"1.0\"\n}"
|
||||
|
||||
[[tests.jq]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -0,0 +1,43 @@
|
||||
[filters.oxlint]
|
||||
description = "Compact oxlint output — strip blank lines, keep diagnostics"
|
||||
match_command = "^oxlint\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^Finished in \\d+",
|
||||
"^Found \\d+ warning",
|
||||
]
|
||||
max_lines = 50
|
||||
on_empty = "oxlint: ok"
|
||||
|
||||
[[tests.oxlint]]
|
||||
name = "strips noise, keeps diagnostics"
|
||||
input = """
|
||||
× eslint(no-console): Unexpected console statement.
|
||||
╭─[src/app.ts:5:3]
|
||||
5 │ console.log("debug");
|
||||
│ ^^^^^^^^^^^
|
||||
╰────
|
||||
|
||||
× eslint(no-unused-vars): 'x' is defined but never used.
|
||||
╭─[src/utils.ts:2:7]
|
||||
2 │ let x = 42;
|
||||
│ ^
|
||||
╰────
|
||||
|
||||
Found 2 warnings on 2 files.
|
||||
Finished in 12ms on 100 files.
|
||||
"""
|
||||
expected = " × eslint(no-console): Unexpected console statement.\n ╭─[src/app.ts:5:3]\n 5 │ console.log(\"debug\");\n │ ^^^^^^^^^^^\n ╰────\n × eslint(no-unused-vars): 'x' is defined but never used.\n ╭─[src/utils.ts:2:7]\n 2 │ let x = 42;\n │ ^\n ╰────"
|
||||
|
||||
[[tests.oxlint]]
|
||||
name = "clean output"
|
||||
input = """
|
||||
Finished in 5ms on 100 files.
|
||||
"""
|
||||
expected = "oxlint: ok"
|
||||
|
||||
[[tests.oxlint]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -0,0 +1,45 @@
|
||||
[filters.skopeo]
|
||||
description = "Compact skopeo output — truncate large manifests, strip verbosity"
|
||||
match_command = "^skopeo\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^Getting image source signatures",
|
||||
"^Copying blob",
|
||||
"^Copying config",
|
||||
"^Writing manifest",
|
||||
"^Storing signatures",
|
||||
]
|
||||
max_lines = 30
|
||||
truncate_lines_at = 120
|
||||
on_empty = "skopeo: ok"
|
||||
|
||||
[[tests.skopeo]]
|
||||
name = "copy strips progress, keeps result"
|
||||
input = """
|
||||
Getting image source signatures
|
||||
Copying blob sha256:abc123 done
|
||||
Copying blob sha256:def456 done
|
||||
Copying config sha256:789ghi done
|
||||
Writing manifest to image destination
|
||||
Storing signatures
|
||||
"""
|
||||
expected = "skopeo: ok"
|
||||
|
||||
[[tests.skopeo]]
|
||||
name = "inspect keeps output"
|
||||
input = """
|
||||
{
|
||||
"Name": "docker.io/library/nginx",
|
||||
"Tag": "latest",
|
||||
"Digest": "sha256:abc123",
|
||||
"RepoTags": ["latest", "1.25"],
|
||||
"Created": "2026-01-01T00:00:00Z"
|
||||
}
|
||||
"""
|
||||
expected = "{\n \"Name\": \"docker.io/library/nginx\",\n \"Tag\": \"latest\",\n \"Digest\": \"sha256:abc123\",\n \"RepoTags\": [\"latest\", \"1.25\"],\n \"Created\": \"2026-01-01T00:00:00Z\"\n}"
|
||||
|
||||
[[tests.skopeo]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -0,0 +1,44 @@
|
||||
[filters.ssh]
|
||||
description = "Compact ssh output — strip connection banners, keep command output"
|
||||
match_command = "^ssh\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^Warning: Permanently added",
|
||||
"^Connection to .+ closed",
|
||||
"^Authenticated to",
|
||||
"^debug1:",
|
||||
"^OpenSSH_",
|
||||
"^Pseudo-terminal",
|
||||
]
|
||||
max_lines = 200
|
||||
truncate_lines_at = 120
|
||||
|
||||
[[tests.ssh]]
|
||||
name = "strips connection banners, keeps command output"
|
||||
input = """
|
||||
Warning: Permanently added '192.168.1.10' (ED25519) to the list of known hosts.
|
||||
|
||||
total 32
|
||||
drwxr-xr-x 4 user user 4096 Mar 10 12:00 app
|
||||
-rw-r--r-- 1 user user 1234 Mar 10 11:00 config.yaml
|
||||
|
||||
Connection to 192.168.1.10 closed.
|
||||
"""
|
||||
expected = "total 32\ndrwxr-xr-x 4 user user 4096 Mar 10 12:00 app\n-rw-r--r-- 1 user user 1234 Mar 10 11:00 config.yaml"
|
||||
|
||||
[[tests.ssh]]
|
||||
name = "verbose debug lines stripped"
|
||||
input = """
|
||||
debug1: Connecting to host.example.com port 22.
|
||||
debug1: Connection established.
|
||||
Authenticated to host.example.com ([1.2.3.4]:22).
|
||||
uptime: 12:00:00 up 42 days, load average: 0.10, 0.15, 0.12
|
||||
Connection to host.example.com closed.
|
||||
"""
|
||||
expected = "uptime: 12:00:00 up 42 days, load average: 0.10, 0.15, 0.12"
|
||||
|
||||
[[tests.ssh]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -0,0 +1,34 @@
|
||||
[filters.stat]
|
||||
description = "Compact stat output — strip blank lines"
|
||||
match_command = "^stat\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
]
|
||||
max_lines = 30
|
||||
|
||||
[[tests.stat]]
|
||||
name = "macOS stat output kept"
|
||||
input = """
|
||||
16777234 8690244974 -rw-r--r-- 1 patrick staff 0 12345 "Mar 10 12:00:00 2026" "Mar 10 11:00:00 2026" "Mar 10 11:00:00 2026" "Mar 9 10:00:00 2026" 4096 24 0 file.txt
|
||||
"""
|
||||
expected = "16777234 8690244974 -rw-r--r-- 1 patrick staff 0 12345 \"Mar 10 12:00:00 2026\" \"Mar 10 11:00:00 2026\" \"Mar 10 11:00:00 2026\" \"Mar 9 10:00:00 2026\" 4096 24 0 file.txt"
|
||||
|
||||
[[tests.stat]]
|
||||
name = "linux stat output kept"
|
||||
input = """
|
||||
File: main.rs
|
||||
Size: 12345 Blocks: 24 IO Block: 4096 regular file
|
||||
Device: 801h/2049d Inode: 1234567 Links: 1
|
||||
Access: (0644/-rw-r--r--) Uid: ( 1000/ patrick) Gid: ( 1000/ patrick)
|
||||
Access: 2026-03-10 12:00:00.000000000 +0100
|
||||
Modify: 2026-03-10 11:00:00.000000000 +0100
|
||||
Change: 2026-03-10 11:00:00.000000000 +0100
|
||||
Birth: 2026-03-09 10:00:00.000000000 +0100
|
||||
"""
|
||||
expected = " File: main.rs\n Size: 12345 Blocks: 24 IO Block: 4096 regular file\nDevice: 801h/2049d Inode: 1234567 Links: 1\nAccess: (0644/-rw-r--r--) Uid: ( 1000/ patrick) Gid: ( 1000/ patrick)\nAccess: 2026-03-10 12:00:00.000000000 +0100\nModify: 2026-03-10 11:00:00.000000000 +0100\nChange: 2026-03-10 11:00:00.000000000 +0100\n Birth: 2026-03-09 10:00:00.000000000 +0100"
|
||||
|
||||
[[tests.stat]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -0,0 +1,50 @@
|
||||
[filters.ty]
|
||||
description = "Compact ty type checker output — strip blank lines, keep errors"
|
||||
match_command = "^ty\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^Checking \\d+ file",
|
||||
"^ty \\d+\\.\\d+",
|
||||
]
|
||||
max_lines = 50
|
||||
on_empty = "ty: ok"
|
||||
|
||||
[[tests.ty]]
|
||||
name = "strips noise, keeps diagnostics"
|
||||
input = """
|
||||
ty 0.1.0
|
||||
Checking 15 files
|
||||
|
||||
error[unresolved-reference]: Name `foo` used when not defined
|
||||
--> app/main.py:10:5
|
||||
|
|
||||
10 | foo()
|
||||
| ^^^
|
||||
|
|
||||
|
||||
warning[unused-variable]: Variable `x` is not used
|
||||
--> app/utils.py:8:9
|
||||
|
|
||||
8 | x = 42
|
||||
| ^
|
||||
|
|
||||
|
||||
Found 1 error, 1 warning
|
||||
"""
|
||||
expected = "error[unresolved-reference]: Name `foo` used when not defined\n --> app/main.py:10:5\n |\n10 | foo()\n | ^^^\n |\nwarning[unused-variable]: Variable `x` is not used\n --> app/utils.py:8:9\n |\n 8 | x = 42\n | ^\n |\nFound 1 error, 1 warning"
|
||||
|
||||
[[tests.ty]]
|
||||
name = "clean output"
|
||||
input = """
|
||||
ty 0.1.0
|
||||
Checking 10 files
|
||||
|
||||
All checks passed!
|
||||
"""
|
||||
expected = "All checks passed!"
|
||||
|
||||
[[tests.ty]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -0,0 +1,99 @@
|
||||
[filters.xcodebuild]
|
||||
description = "Compact xcodebuild output — strip build phases, keep errors/warnings/summary"
|
||||
match_command = "^xcodebuild\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^CompileC\\s",
|
||||
"^CompileSwift\\s",
|
||||
"^Ld\\s",
|
||||
"^CreateBuildDirectory\\s",
|
||||
"^MkDir\\s",
|
||||
"^ProcessInfoPlistFile\\s",
|
||||
"^CopySwiftLibs\\s",
|
||||
"^CodeSign\\s",
|
||||
"^Signing Identity:",
|
||||
"^RegisterWithLaunchServices",
|
||||
"^Validate\\s",
|
||||
"^ProcessProductPackaging",
|
||||
"^Touch\\s",
|
||||
"^LinkStoryboards",
|
||||
"^CompileStoryboard",
|
||||
"^CompileAssetCatalog",
|
||||
"^GenerateDSYMFile",
|
||||
"^PhaseScriptExecution",
|
||||
"^PBXCp\\s",
|
||||
"^SetMode\\s",
|
||||
"^SetOwnerAndGroup\\s",
|
||||
"^Ditto\\s",
|
||||
"^CpResource\\s",
|
||||
"^CpHeader\\s",
|
||||
"^\\s+cd\\s+/",
|
||||
"^\\s+export\\s",
|
||||
"^\\s+/Applications/Xcode",
|
||||
"^\\s+/usr/bin/",
|
||||
"^\\s+builtin-",
|
||||
"^note: Using new build system",
|
||||
]
|
||||
max_lines = 60
|
||||
on_empty = "xcodebuild: ok"
|
||||
|
||||
[[tests.xcodebuild]]
|
||||
name = "strips build phases, keeps errors and summary"
|
||||
input = """
|
||||
note: Using new build system
|
||||
CompileSwift normal arm64 /Users/dev/App/ViewController.swift
|
||||
cd /Users/dev/App
|
||||
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift-frontend -c
|
||||
CompileSwift normal arm64 /Users/dev/App/AppDelegate.swift
|
||||
cd /Users/dev/App
|
||||
export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
|
||||
Ld /Users/dev/Build/Products/Debug/App normal arm64
|
||||
cd /Users/dev/App
|
||||
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang
|
||||
CodeSign /Users/dev/Build/Products/Debug/App.app
|
||||
cd /Users/dev/App
|
||||
builtin-codesign --force --sign
|
||||
|
||||
/Users/dev/App/ViewController.swift:42:9: error: use of unresolved identifier 'foo'
|
||||
/Users/dev/App/Model.swift:18:5: warning: variable 'x' was never used
|
||||
|
||||
** BUILD FAILED **
|
||||
"""
|
||||
expected = "/Users/dev/App/ViewController.swift:42:9: error: use of unresolved identifier 'foo'\n/Users/dev/App/Model.swift:18:5: warning: variable 'x' was never used\n** BUILD FAILED **"
|
||||
|
||||
[[tests.xcodebuild]]
|
||||
name = "clean build success"
|
||||
input = """
|
||||
note: Using new build system
|
||||
CompileSwift normal arm64 /Users/dev/App/Main.swift
|
||||
cd /Users/dev/App
|
||||
Ld /Users/dev/Build/Products/Debug/App normal arm64
|
||||
cd /Users/dev/App
|
||||
CodeSign /Users/dev/Build/Products/Debug/App.app
|
||||
cd /Users/dev/App
|
||||
builtin-codesign --force --sign
|
||||
|
||||
** BUILD SUCCEEDED **
|
||||
"""
|
||||
expected = "** BUILD SUCCEEDED **"
|
||||
|
||||
[[tests.xcodebuild]]
|
||||
name = "test output keeps test results"
|
||||
input = """
|
||||
note: Using new build system
|
||||
CompileSwift normal arm64 /Users/dev/AppTests/Tests.swift
|
||||
cd /Users/dev/App
|
||||
Test Suite 'All tests' started at 2026-03-10 12:00:00
|
||||
Test Suite 'AppTests' started at 2026-03-10 12:00:00
|
||||
Test Case '-[AppTests testExample]' passed (0.001 seconds).
|
||||
Test Case '-[AppTests testFailing]' failed (0.002 seconds).
|
||||
Test Suite 'AppTests' passed at 2026-03-10 12:00:01
|
||||
Executed 2 tests, with 1 failure in 0.003 seconds
|
||||
"""
|
||||
expected = "Test Suite 'All tests' started at 2026-03-10 12:00:00\nTest Suite 'AppTests' started at 2026-03-10 12:00:00\nTest Case '-[AppTests testExample]' passed (0.001 seconds).\nTest Case '-[AppTests testFailing]' failed (0.002 seconds).\nTest Suite 'AppTests' passed at 2026-03-10 12:00:01\nExecuted 2 tests, with 1 failure in 0.003 seconds"
|
||||
|
||||
[[tests.xcodebuild]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
+80
-4
@@ -1,11 +1,12 @@
|
||||
use crate::display_helpers::{format_duration, print_period_table};
|
||||
use crate::hook_check;
|
||||
use crate::tracking::{DayStats, MonthStats, Tracker, WeekStats};
|
||||
use crate::utils::format_tokens;
|
||||
use anyhow::{Context, Result};
|
||||
use colored::Colorize; // added: terminal colors
|
||||
use colored::Colorize;
|
||||
use serde::Serialize;
|
||||
use std::io::IsTerminal; // added: TTY detection for graceful degradation
|
||||
use std::path::PathBuf; // added: for project path resolution
|
||||
use std::io::IsTerminal;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub fn run(
|
||||
project: bool, // added: per-project scope flag
|
||||
@@ -99,9 +100,35 @@ pub fn run(
|
||||
format_duration(summary.avg_time_ms)
|
||||
),
|
||||
);
|
||||
print_efficiency_meter(summary.avg_savings_pct); // added: visual meter
|
||||
print_efficiency_meter(summary.avg_savings_pct);
|
||||
println!();
|
||||
|
||||
// Warn about hook issues that silently kill savings (stderr, not stdout)
|
||||
match hook_check::status() {
|
||||
hook_check::HookStatus::Missing => {
|
||||
eprintln!(
|
||||
"{}",
|
||||
"⚠️ No hook installed — run `rtk init -g` for automatic token savings"
|
||||
.yellow()
|
||||
);
|
||||
eprintln!();
|
||||
}
|
||||
hook_check::HookStatus::Outdated => {
|
||||
eprintln!(
|
||||
"{}",
|
||||
"⚠️ Hook outdated — run `rtk init -g` to update".yellow()
|
||||
);
|
||||
eprintln!();
|
||||
}
|
||||
hook_check::HookStatus::Ok => {}
|
||||
}
|
||||
|
||||
// Lightweight RTK_DISABLED bypass check (best-effort, silent on failure)
|
||||
if let Some(warning) = check_rtk_disabled_bypass() {
|
||||
eprintln!("{}", warning.yellow());
|
||||
eprintln!();
|
||||
}
|
||||
|
||||
if !summary.by_command.is_empty() {
|
||||
// added: styled section header
|
||||
println!("{}", styled("By Command", true));
|
||||
@@ -590,6 +617,55 @@ fn export_csv(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Lightweight scan of recent Claude Code sessions for RTK_DISABLED= overuse.
|
||||
/// Returns a warning string if bypass rate exceeds 10%, None otherwise.
|
||||
/// Silently returns None on any error (missing dirs, permission issues, etc.).
|
||||
fn check_rtk_disabled_bypass() -> Option<String> {
|
||||
use crate::discover::provider::{ClaudeProvider, SessionProvider};
|
||||
use crate::discover::registry::has_rtk_disabled_prefix;
|
||||
|
||||
let provider = ClaudeProvider;
|
||||
|
||||
// Quick scan: last 7 days only
|
||||
let sessions = provider.discover_sessions(None, Some(7)).ok()?;
|
||||
|
||||
// Early bail if no sessions or too many (avoid slow scan)
|
||||
if sessions.is_empty() || sessions.len() > 200 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut total_bash: usize = 0;
|
||||
let mut bypassed: usize = 0;
|
||||
|
||||
for session_path in &sessions {
|
||||
let extracted = match provider.extract_commands(session_path) {
|
||||
Ok(cmds) => cmds,
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
for ext_cmd in &extracted {
|
||||
total_bash += 1;
|
||||
if has_rtk_disabled_prefix(&ext_cmd.command) {
|
||||
bypassed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if total_bash == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let pct = (bypassed as f64 / total_bash as f64) * 100.0;
|
||||
if pct > 10.0 {
|
||||
Some(format!(
|
||||
"⚠️ {} commands ({:.0}%) used RTK_DISABLED=1 unnecessarily — run `rtk discover` for details",
|
||||
bypassed, pct
|
||||
))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn show_failures(tracker: &Tracker) -> Result<()> {
|
||||
let summary = tracker
|
||||
.get_parse_failure_summary()
|
||||
|
||||
+51
-1
@@ -121,7 +121,16 @@ fn extract_identifier_and_extra_args(args: &[String]) -> Option<(String, Vec<Str
|
||||
}
|
||||
|
||||
// Known gh flags that take a value — skip these and their values
|
||||
let flags_with_value = ["-R", "--repo", "-q", "--jq", "-t", "--template"];
|
||||
let flags_with_value = [
|
||||
"-R",
|
||||
"--repo",
|
||||
"-q",
|
||||
"--jq",
|
||||
"-t",
|
||||
"--template",
|
||||
"--job",
|
||||
"--attempt",
|
||||
];
|
||||
let mut identifier = None;
|
||||
let mut extra = Vec::new();
|
||||
let mut skip_next = false;
|
||||
@@ -1418,6 +1427,47 @@ mod tests {
|
||||
assert!(!should_passthrough_run_view(&["--web".into()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_identifier_with_job_flag_after() {
|
||||
// gh run view 12345 --job 67890
|
||||
let args: Vec<String> = vec!["12345".into(), "--job".into(), "67890".into()];
|
||||
let (id, extra) = extract_identifier_and_extra_args(&args).unwrap();
|
||||
assert_eq!(id, "12345");
|
||||
assert_eq!(extra, vec!["--job", "67890"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_identifier_with_job_flag_before() {
|
||||
// gh run view --job 67890 12345
|
||||
let args: Vec<String> = vec!["--job".into(), "67890".into(), "12345".into()];
|
||||
let (id, extra) = extract_identifier_and_extra_args(&args).unwrap();
|
||||
assert_eq!(id, "12345");
|
||||
assert_eq!(extra, vec!["--job", "67890"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_identifier_with_job_and_log_failed() {
|
||||
// gh run view --log-failed --job 67890 12345
|
||||
let args: Vec<String> = vec![
|
||||
"--log-failed".into(),
|
||||
"--job".into(),
|
||||
"67890".into(),
|
||||
"12345".into(),
|
||||
];
|
||||
let (id, extra) = extract_identifier_and_extra_args(&args).unwrap();
|
||||
assert_eq!(id, "12345");
|
||||
assert_eq!(extra, vec!["--log-failed", "--job", "67890"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_identifier_with_attempt_flag() {
|
||||
// gh run view 12345 --attempt 3
|
||||
let args: Vec<String> = vec!["12345".into(), "--attempt".into(), "3".into()];
|
||||
let (id, extra) = extract_identifier_and_extra_args(&args).unwrap();
|
||||
assert_eq!(id, "12345");
|
||||
assert_eq!(extra, vec!["--attempt", "3"]);
|
||||
}
|
||||
|
||||
// --- should_passthrough_pr_view tests ---
|
||||
|
||||
#[test]
|
||||
|
||||
+200
-41
@@ -352,9 +352,11 @@ fn run_log(
|
||||
arg.starts_with("--oneline") || arg.starts_with("--pretty") || arg.starts_with("--format")
|
||||
});
|
||||
|
||||
// Check if user provided limit flag
|
||||
// Check if user provided limit flag (-N, -n N, --max-count=N, --max-count N)
|
||||
let has_limit_flag = args.iter().any(|arg| {
|
||||
arg.starts_with('-') && arg.chars().nth(1).map_or(false, |c| c.is_ascii_digit())
|
||||
(arg.starts_with('-') && arg.chars().nth(1).map_or(false, |c| c.is_ascii_digit()))
|
||||
|| arg == "-n"
|
||||
|| arg.starts_with("--max-count")
|
||||
});
|
||||
|
||||
// Apply RTK defaults only if user didn't specify them
|
||||
@@ -362,17 +364,19 @@ fn run_log(
|
||||
cmd.args(["--pretty=format:%h %s (%ar) <%an>"]);
|
||||
}
|
||||
|
||||
let limit = if !has_limit_flag {
|
||||
cmd.arg("-10");
|
||||
10
|
||||
// Determine limit: respect user's explicit -N flag, use sensible defaults otherwise
|
||||
let (limit, user_set_limit) = if has_limit_flag {
|
||||
// User explicitly passed -N / -n N / --max-count=N → respect their choice
|
||||
let n = parse_user_limit(args).unwrap_or(10);
|
||||
(n, true)
|
||||
} else if has_format_flag {
|
||||
// --oneline / --pretty without -N: user wants compact output, allow more
|
||||
cmd.arg("-50");
|
||||
(50, false)
|
||||
} else {
|
||||
// Extract limit from args if provided
|
||||
args.iter()
|
||||
.find(|arg| {
|
||||
arg.starts_with('-') && arg.chars().nth(1).map_or(false, |c| c.is_ascii_digit())
|
||||
})
|
||||
.and_then(|arg| arg[1..].parse::<usize>().ok())
|
||||
.unwrap_or(10)
|
||||
// No flags at all: default to 10
|
||||
cmd.arg("-10");
|
||||
(10, false)
|
||||
};
|
||||
|
||||
// Only add --no-merges if user didn't explicitly request merge commits
|
||||
@@ -403,8 +407,8 @@ fn run_log(
|
||||
eprintln!("Git log output:");
|
||||
}
|
||||
|
||||
// Post-process: truncate long messages, cap lines
|
||||
let filtered = filter_log_output(&stdout, limit);
|
||||
// Post-process: truncate long messages, cap lines only if RTK set the default
|
||||
let filtered = filter_log_output(&stdout, limit, user_set_limit);
|
||||
println!("{}", filtered);
|
||||
|
||||
timer.track(
|
||||
@@ -418,24 +422,80 @@ fn run_log(
|
||||
}
|
||||
|
||||
/// Filter git log output: truncate long messages, cap lines
|
||||
fn filter_log_output(output: &str, limit: usize) -> String {
|
||||
let lines: Vec<&str> = output.lines().collect();
|
||||
let capped: Vec<String> = lines
|
||||
.iter()
|
||||
.take(limit)
|
||||
.map(|line| {
|
||||
if line.len() > 80 {
|
||||
let truncated: String = line.chars().take(77).collect();
|
||||
format!("{}...", truncated)
|
||||
} else {
|
||||
line.to_string()
|
||||
/// Parse the user-specified limit from git log args.
|
||||
/// Handles: -20, -n 20, --max-count=20, --max-count 20
|
||||
fn parse_user_limit(args: &[String]) -> Option<usize> {
|
||||
let mut iter = args.iter();
|
||||
while let Some(arg) = iter.next() {
|
||||
// -20 (combined digit form)
|
||||
if arg.starts_with('-')
|
||||
&& arg.len() > 1
|
||||
&& arg.chars().nth(1).map_or(false, |c| c.is_ascii_digit())
|
||||
{
|
||||
if let Ok(n) = arg[1..].parse::<usize>() {
|
||||
return Some(n);
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
// -n 20 (two-token form)
|
||||
if arg == "-n" {
|
||||
if let Some(next) = iter.next() {
|
||||
if let Ok(n) = next.parse::<usize>() {
|
||||
return Some(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
// --max-count=20
|
||||
if let Some(rest) = arg.strip_prefix("--max-count=") {
|
||||
if let Ok(n) = rest.parse::<usize>() {
|
||||
return Some(n);
|
||||
}
|
||||
}
|
||||
// --max-count 20 (two-token form)
|
||||
if arg == "--max-count" {
|
||||
if let Some(next) = iter.next() {
|
||||
if let Ok(n) = next.parse::<usize>() {
|
||||
return Some(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// When `user_set_limit` is true, the user explicitly passed `-N` to git log,
|
||||
/// so we skip line capping (git already returns exactly N commits) and use a
|
||||
/// wider truncation threshold (120 chars) to preserve commit context that LLMs
|
||||
/// need for rebase/squash operations.
|
||||
fn filter_log_output(output: &str, limit: usize, user_set_limit: bool) -> String {
|
||||
let lines: Vec<&str> = output.lines().collect();
|
||||
|
||||
let truncate_width = if user_set_limit { 120 } else { 80 };
|
||||
|
||||
let iter = lines.iter();
|
||||
let capped: Vec<String> = if user_set_limit {
|
||||
// User chose the limit → git already returned the right number of commits
|
||||
iter.map(|line| truncate_line(line, truncate_width))
|
||||
.collect()
|
||||
} else {
|
||||
// RTK default → cap output lines
|
||||
iter.take(limit)
|
||||
.map(|line| truncate_line(line, truncate_width))
|
||||
.collect()
|
||||
};
|
||||
|
||||
capped.join("\n").trim().to_string()
|
||||
}
|
||||
|
||||
/// Truncate a single line to `width` characters, appending "..." if needed
|
||||
fn truncate_line(line: &str, width: usize) -> String {
|
||||
if line.chars().count() > width {
|
||||
let truncated: String = line.chars().take(width - 3).collect();
|
||||
format!("{}...", truncated)
|
||||
} else {
|
||||
line.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Format porcelain output into compact RTK status display
|
||||
fn format_status_output(porcelain: &str) -> String {
|
||||
let lines: Vec<&str> = porcelain.lines().collect();
|
||||
@@ -1616,7 +1676,7 @@ M file7.rs
|
||||
#[test]
|
||||
fn test_filter_log_output() {
|
||||
let output = "abc1234 This is a commit message (2 days ago) <author>\ndef5678 Another commit (1 week ago) <other>\n";
|
||||
let result = filter_log_output(output, 10);
|
||||
let result = filter_log_output(output, 10, false);
|
||||
assert!(result.contains("abc1234"));
|
||||
assert!(result.contains("def5678"));
|
||||
assert_eq!(result.lines().count(), 2);
|
||||
@@ -1625,10 +1685,10 @@ M file7.rs
|
||||
#[test]
|
||||
fn test_filter_log_output_truncate_long() {
|
||||
let long_line = "abc1234 ".to_string() + &"x".repeat(100) + " (2 days ago) <author>";
|
||||
let result = filter_log_output(&long_line, 10);
|
||||
assert!(result.len() < long_line.len());
|
||||
let result = filter_log_output(&long_line, 10, false);
|
||||
assert!(result.chars().count() < long_line.chars().count());
|
||||
assert!(result.contains("..."));
|
||||
assert!(result.len() <= 80);
|
||||
assert!(result.chars().count() <= 80);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1637,10 +1697,101 @@ M file7.rs
|
||||
.map(|i| format!("hash{} message {} (1 day ago) <author>", i, i))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let result = filter_log_output(&output, 5);
|
||||
let result = filter_log_output(&output, 5, false);
|
||||
assert_eq!(result.lines().count(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_log_output_user_limit_no_cap() {
|
||||
// When user explicitly passes -N, all N lines should be returned (no re-truncation)
|
||||
let output = (0..20)
|
||||
.map(|i| format!("hash{} message {} (1 day ago) <author>", i, i))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let result = filter_log_output(&output, 20, true);
|
||||
assert_eq!(
|
||||
result.lines().count(),
|
||||
20,
|
||||
"User's -20 should return all 20 lines"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_log_output_user_limit_wider_truncation() {
|
||||
// When user explicitly passes -N, lines up to 120 chars should NOT be truncated
|
||||
let line_90_chars = format!("abc1234 {} (2 days ago) <author>", "x".repeat(60));
|
||||
assert!(line_90_chars.chars().count() > 80);
|
||||
assert!(line_90_chars.chars().count() < 120);
|
||||
|
||||
let result_default = filter_log_output(&line_90_chars, 10, false);
|
||||
let result_user = filter_log_output(&line_90_chars, 10, true);
|
||||
|
||||
// Default truncates at 80 chars
|
||||
assert!(
|
||||
result_default.contains("..."),
|
||||
"Default should truncate at 80 chars"
|
||||
);
|
||||
// User-set limit uses wider threshold (120 chars)
|
||||
assert!(
|
||||
!result_user.contains("..."),
|
||||
"User limit should not truncate 90-char line"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_user_limit_combined() {
|
||||
let args: Vec<String> = vec!["-20".into()];
|
||||
assert_eq!(parse_user_limit(&args), Some(20));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_user_limit_n_space() {
|
||||
let args: Vec<String> = vec!["-n".into(), "15".into()];
|
||||
assert_eq!(parse_user_limit(&args), Some(15));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_user_limit_max_count_eq() {
|
||||
let args: Vec<String> = vec!["--max-count=30".into()];
|
||||
assert_eq!(parse_user_limit(&args), Some(30));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_user_limit_max_count_space() {
|
||||
let args: Vec<String> = vec!["--max-count".into(), "25".into()];
|
||||
assert_eq!(parse_user_limit(&args), Some(25));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_user_limit_none() {
|
||||
let args: Vec<String> = vec!["--oneline".into()];
|
||||
assert_eq!(parse_user_limit(&args), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_log_output_token_savings() {
|
||||
fn count_tokens(text: &str) -> usize {
|
||||
text.split_whitespace().count()
|
||||
}
|
||||
// Simulate verbose git log output (default format with full metadata)
|
||||
let input = (0..20)
|
||||
.map(|i| {
|
||||
format!(
|
||||
"commit abc123{:02x}\nAuthor: User Name <user@example.com>\nDate: Mon Mar 10 10:00:00 2026 +0000\n\n fix: commit message number {}\n\n Extended body with details about the change.\n",
|
||||
i, i
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let output = filter_log_output(&input, 10, false);
|
||||
let savings = 100.0 - (count_tokens(&output) as f64 / count_tokens(&input) as f64 * 100.0);
|
||||
assert!(
|
||||
savings >= 60.0,
|
||||
"Expected ≥60% token savings, got {:.1}%",
|
||||
savings
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_status_with_args() {
|
||||
let output = r#"On branch main
|
||||
@@ -1674,20 +1825,22 @@ no changes added to commit (use "git add" and/or "git commit -a")
|
||||
fn test_filter_log_output_multibyte() {
|
||||
// Thai characters: each is 3 bytes. A line with >80 bytes but few chars
|
||||
let thai_msg = format!("abc1234 {} (2 days ago) <author>", "ก".repeat(30));
|
||||
let result = filter_log_output(&thai_msg, 10);
|
||||
let result = filter_log_output(&thai_msg, 10, false);
|
||||
// Should not panic
|
||||
assert!(result.contains("abc1234"));
|
||||
// The line has 30 Thai chars (90 bytes) + other text, so > 80 bytes
|
||||
// It should be truncated with "..."
|
||||
assert!(result.contains("..."));
|
||||
// The line has 30 Thai chars + other text, so > 80 chars total
|
||||
// truncate_line now counts chars, not bytes
|
||||
// 30 Thai + ~33 other = 63 chars < 80 threshold, so no truncation
|
||||
assert!(result.contains("abc1234"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_log_output_emoji() {
|
||||
let emoji_msg = "abc1234 🎉🎊🎈🎁🎂🎄🎃🎆🎇✨🎉🎊🎈🎁🎂🎄🎃🎆🎇✨ (1 day ago) <user>";
|
||||
let result = filter_log_output(emoji_msg, 10);
|
||||
// Should not panic, should have "..."
|
||||
assert!(result.contains("..."));
|
||||
let result = filter_log_output(emoji_msg, 10, false);
|
||||
// Should not panic
|
||||
// 20 emoji + ~30 other chars = ~50 chars < 80, no truncation needed
|
||||
assert!(result.contains("abc1234"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1815,6 +1968,7 @@ no changes added to commit (use "git add" and/or "git commit -a")
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore] // Requires `cargo build` first — run with `cargo test --ignored`
|
||||
fn test_git_status_not_a_repo_exits_nonzero() {
|
||||
// Run rtk git status in a directory that is not a git repo
|
||||
let tmp = std::env::temp_dir().join("rtk_test_not_a_repo");
|
||||
@@ -1825,6 +1979,11 @@ no changes added to commit (use "git add" and/or "git commit -a")
|
||||
.join("target")
|
||||
.join("debug")
|
||||
.join("rtk");
|
||||
assert!(
|
||||
bin_path.exists(),
|
||||
"Debug binary not found at {:?} — run `cargo build` first",
|
||||
bin_path
|
||||
);
|
||||
let output = std::process::Command::new(&bin_path)
|
||||
.args(["git", "status"])
|
||||
.current_dir(&tmp)
|
||||
@@ -1842,8 +2001,8 @@ no changes added to commit (use "git add" and/or "git commit -a")
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(
|
||||
stderr.contains("Not a git repository"),
|
||||
"Expected 'Not a git repository' on stderr, got stderr={:?}, stdout={:?}",
|
||||
stderr.to_lowercase().contains("not a git repository"),
|
||||
"Expected 'not a git repository' on stderr, got stderr={:?}, stdout={:?}",
|
||||
stderr,
|
||||
stdout
|
||||
);
|
||||
|
||||
+97
-14
@@ -3,42 +3,79 @@ use std::path::PathBuf;
|
||||
const CURRENT_HOOK_VERSION: u8 = 2;
|
||||
const WARN_INTERVAL_SECS: u64 = 24 * 3600;
|
||||
|
||||
/// Check if the installed hook is outdated, warn once per day.
|
||||
/// Hook status for diagnostics and `rtk gain`.
|
||||
#[derive(Debug, PartialEq, Clone)]
|
||||
pub enum HookStatus {
|
||||
/// Hook is installed and up to date.
|
||||
Ok,
|
||||
/// Hook exists but is outdated or unreadable.
|
||||
Outdated,
|
||||
/// No hook file found (but Claude Code is installed).
|
||||
Missing,
|
||||
}
|
||||
|
||||
/// Return the current hook status without printing anything.
|
||||
/// Returns `Ok` if no Claude Code is detected (not applicable).
|
||||
pub fn status() -> HookStatus {
|
||||
// Don't warn users who don't have Claude Code installed
|
||||
let home = match dirs::home_dir() {
|
||||
Some(h) => h,
|
||||
None => return HookStatus::Ok,
|
||||
};
|
||||
if !home.join(".claude").exists() {
|
||||
return HookStatus::Ok;
|
||||
}
|
||||
|
||||
let Some(hook_path) = hook_installed_path() else {
|
||||
return HookStatus::Missing;
|
||||
};
|
||||
let Ok(content) = std::fs::read_to_string(&hook_path) else {
|
||||
return HookStatus::Outdated; // exists but unreadable — treat as needs-update
|
||||
};
|
||||
if parse_hook_version(&content) >= CURRENT_HOOK_VERSION {
|
||||
HookStatus::Ok
|
||||
} else {
|
||||
HookStatus::Outdated
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if the installed hook is missing or outdated, warn once per day.
|
||||
pub fn maybe_warn() {
|
||||
// Don't block startup — fail silently on any error
|
||||
let _ = check_and_warn();
|
||||
}
|
||||
|
||||
/// Single source of truth: delegates to `status()` then rate-limits the warning.
|
||||
fn check_and_warn() -> Option<()> {
|
||||
let hook_path = hook_installed_path()?;
|
||||
let content = std::fs::read_to_string(&hook_path).ok()?;
|
||||
|
||||
let installed_version = parse_hook_version(&content);
|
||||
|
||||
if installed_version >= CURRENT_HOOK_VERSION {
|
||||
return Some(());
|
||||
}
|
||||
let warning = match status() {
|
||||
HookStatus::Ok => return Some(()),
|
||||
HookStatus::Missing => {
|
||||
"[rtk] /!\\ No hook installed — run `rtk init -g` for automatic token savings"
|
||||
}
|
||||
HookStatus::Outdated => "[rtk] /!\\ Hook outdated — run `rtk init -g` to update",
|
||||
};
|
||||
|
||||
// Rate limit: warn once per day
|
||||
let marker = warn_marker_path()?;
|
||||
if let Ok(meta) = std::fs::metadata(&marker) {
|
||||
if let Ok(elapsed) = meta.modified().ok()?.elapsed() {
|
||||
if elapsed.as_secs() < WARN_INTERVAL_SECS {
|
||||
if let Ok(modified) = meta.modified() {
|
||||
if modified.elapsed().map(|e| e.as_secs()).unwrap_or(u64::MAX) < WARN_INTERVAL_SECS {
|
||||
return Some(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Touch marker
|
||||
eprintln!("{}", warning);
|
||||
|
||||
// Touch marker after warning is printed
|
||||
let _ = std::fs::create_dir_all(marker.parent()?);
|
||||
let _ = std::fs::write(&marker, b"");
|
||||
|
||||
eprintln!("[rtk] Hook outdated — run `rtk init -g` to update");
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
pub fn parse_hook_version(content: &str) -> u8 {
|
||||
// Version tag must be in the first 5 lines (shebang + header convention)
|
||||
for line in content.lines().take(5) {
|
||||
if let Some(rest) = line.strip_prefix("# rtk-hook-version:") {
|
||||
if let Ok(v) = rest.trim().parse::<u8>() {
|
||||
@@ -85,4 +122,50 @@ mod tests {
|
||||
let content = "#!/usr/bin/env bash\n# rtk-hook-version: 5\n";
|
||||
assert_eq!(parse_hook_version(content), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_hook_version_no_tag() {
|
||||
assert_eq!(parse_hook_version("no version here"), 0);
|
||||
assert_eq!(parse_hook_version(""), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hook_status_enum() {
|
||||
assert_ne!(HookStatus::Ok, HookStatus::Missing);
|
||||
assert_ne!(HookStatus::Outdated, HookStatus::Missing);
|
||||
assert_eq!(HookStatus::Ok, HookStatus::Ok);
|
||||
// Clone works
|
||||
let s = HookStatus::Missing;
|
||||
assert_eq!(s.clone(), HookStatus::Missing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_status_returns_valid_variant() {
|
||||
// Skip on machines without Claude Code or without hook
|
||||
let home = match dirs::home_dir() {
|
||||
Some(h) => h,
|
||||
None => return,
|
||||
};
|
||||
if !home
|
||||
.join(".claude")
|
||||
.join("hooks")
|
||||
.join("rtk-rewrite.sh")
|
||||
.exists()
|
||||
{
|
||||
// No hook — status should be Missing (if .claude exists) or Ok (if not)
|
||||
let s = status();
|
||||
if home.join(".claude").exists() {
|
||||
assert_eq!(s, HookStatus::Missing);
|
||||
} else {
|
||||
assert_eq!(s, HookStatus::Ok);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let s = status();
|
||||
assert!(
|
||||
s == HookStatus::Ok || s == HookStatus::Outdated,
|
||||
"Expected Ok or Outdated when hook exists, got {:?}",
|
||||
s
|
||||
);
|
||||
}
|
||||
}
|
||||
+221
-22
@@ -9,6 +9,9 @@ use crate::integrity;
|
||||
// Embedded hook script (guards before set -euo pipefail)
|
||||
const REWRITE_HOOK: &str = include_str!("../hooks/rtk-rewrite.sh");
|
||||
|
||||
// Embedded OpenCode plugin (auto-rewrite)
|
||||
const OPENCODE_PLUGIN: &str = include_str!("../hooks/opencode-rtk.ts");
|
||||
|
||||
// Embedded slim RTK awareness instructions
|
||||
const RTK_SLIM: &str = include_str!("../hooks/rtk-awareness.md");
|
||||
|
||||
@@ -199,16 +202,26 @@ Overall average: **60-90% token reduction** on common development operations.
|
||||
/// Main entry point for `rtk init`
|
||||
pub fn run(
|
||||
global: bool,
|
||||
install_claude: bool,
|
||||
install_opencode: bool,
|
||||
claude_md: bool,
|
||||
hook_only: bool,
|
||||
patch_mode: PatchMode,
|
||||
verbose: u8,
|
||||
) -> Result<()> {
|
||||
if install_opencode && !global {
|
||||
anyhow::bail!("OpenCode plugin is global-only. Use: rtk init -g --opencode");
|
||||
}
|
||||
|
||||
// Mode selection
|
||||
match (claude_md, hook_only) {
|
||||
(true, _) => run_claude_md_mode(global, verbose),
|
||||
(false, true) => run_hook_only_mode(global, patch_mode, verbose),
|
||||
(false, false) => run_default_mode(global, patch_mode, verbose),
|
||||
match (install_claude, install_opencode, claude_md, hook_only) {
|
||||
(false, true, _, _) => run_opencode_only_mode(verbose),
|
||||
(true, opencode, true, _) => run_claude_md_mode(global, verbose, opencode),
|
||||
(true, opencode, false, true) => run_hook_only_mode(global, patch_mode, verbose, opencode),
|
||||
(true, opencode, false, false) => run_default_mode(global, patch_mode, verbose, opencode),
|
||||
(false, false, _, _) => {
|
||||
anyhow::bail!("at least one of install_claude or install_opencode must be true")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -353,7 +366,7 @@ fn prompt_user_consent(settings_path: &Path) -> Result<bool> {
|
||||
}
|
||||
|
||||
/// Print manual instructions for settings.json patching
|
||||
fn print_manual_instructions(hook_path: &Path) {
|
||||
fn print_manual_instructions(hook_path: &Path, include_opencode: bool) {
|
||||
println!("\n MANUAL STEP: Add this to ~/.claude/settings.json:");
|
||||
println!(" {{");
|
||||
println!(" \"hooks\": {{ \"PreToolUse\": [{{");
|
||||
@@ -363,7 +376,11 @@ fn print_manual_instructions(hook_path: &Path) {
|
||||
println!(" }}]");
|
||||
println!(" }}]}}");
|
||||
println!(" }}");
|
||||
println!("\n Then restart Claude Code. Test with: git status\n");
|
||||
if include_opencode {
|
||||
println!("\n Then restart Claude Code and OpenCode. Test with: git status\n");
|
||||
} else {
|
||||
println!("\n Then restart Claude Code. Test with: git status\n");
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove RTK hook entry from settings.json
|
||||
@@ -499,6 +516,12 @@ pub fn uninstall(global: bool, verbose: u8) -> Result<()> {
|
||||
removed.push("settings.json: removed RTK hook entry".to_string());
|
||||
}
|
||||
|
||||
// 5. Remove OpenCode plugin
|
||||
let opencode_removed = remove_opencode_plugin(verbose)?;
|
||||
for path in opencode_removed {
|
||||
removed.push(format!("OpenCode plugin: {}", path.display()));
|
||||
}
|
||||
|
||||
// Report results
|
||||
if removed.is_empty() {
|
||||
println!("RTK was not installed (nothing to remove)");
|
||||
@@ -507,7 +530,7 @@ pub fn uninstall(global: bool, verbose: u8) -> Result<()> {
|
||||
for item in removed {
|
||||
println!(" - {}", item);
|
||||
}
|
||||
println!("\nRestart Claude Code to apply changes.");
|
||||
println!("\nRestart Claude Code and OpenCode (if used) to apply changes.");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -515,7 +538,12 @@ pub fn uninstall(global: bool, verbose: u8) -> Result<()> {
|
||||
|
||||
/// Orchestrator: patch settings.json with RTK hook
|
||||
/// Handles reading, checking, prompting, merging, backing up, and atomic writing
|
||||
fn patch_settings_json(hook_path: &Path, mode: PatchMode, verbose: u8) -> Result<PatchResult> {
|
||||
fn patch_settings_json(
|
||||
hook_path: &Path,
|
||||
mode: PatchMode,
|
||||
verbose: u8,
|
||||
include_opencode: bool,
|
||||
) -> Result<PatchResult> {
|
||||
let claude_dir = resolve_claude_dir()?;
|
||||
let settings_path = claude_dir.join("settings.json");
|
||||
let hook_command = hook_path
|
||||
@@ -548,12 +576,12 @@ fn patch_settings_json(hook_path: &Path, mode: PatchMode, verbose: u8) -> Result
|
||||
// Handle mode
|
||||
match mode {
|
||||
PatchMode::Skip => {
|
||||
print_manual_instructions(hook_path);
|
||||
print_manual_instructions(hook_path, include_opencode);
|
||||
return Ok(PatchResult::Skipped);
|
||||
}
|
||||
PatchMode::Ask => {
|
||||
if !prompt_user_consent(&settings_path)? {
|
||||
print_manual_instructions(hook_path);
|
||||
print_manual_instructions(hook_path, include_opencode);
|
||||
return Ok(PatchResult::Declined);
|
||||
}
|
||||
}
|
||||
@@ -587,7 +615,11 @@ fn patch_settings_json(hook_path: &Path, mode: PatchMode, verbose: u8) -> Result
|
||||
settings_path.with_extension("json.bak").display()
|
||||
);
|
||||
}
|
||||
println!(" Restart Claude Code. Test with: git status");
|
||||
if include_opencode {
|
||||
println!(" Restart Claude Code and OpenCode. Test with: git status");
|
||||
} else {
|
||||
println!(" Restart Claude Code. Test with: git status");
|
||||
}
|
||||
|
||||
Ok(PatchResult::Patched)
|
||||
}
|
||||
@@ -687,18 +719,28 @@ fn hook_already_present(root: &serde_json::Value, hook_command: &str) -> bool {
|
||||
|
||||
/// Default mode: hook + slim RTK.md + @RTK.md reference
|
||||
#[cfg(not(unix))]
|
||||
fn run_default_mode(_global: bool, _patch_mode: PatchMode, _verbose: u8) -> Result<()> {
|
||||
fn run_default_mode(
|
||||
_global: bool,
|
||||
_patch_mode: PatchMode,
|
||||
_verbose: u8,
|
||||
_install_opencode: bool,
|
||||
) -> Result<()> {
|
||||
eprintln!("⚠️ Hook-based mode requires Unix (macOS/Linux).");
|
||||
eprintln!(" Windows: use --claude-md mode for full injection.");
|
||||
eprintln!(" Falling back to --claude-md mode.");
|
||||
run_claude_md_mode(_global, _verbose)
|
||||
run_claude_md_mode(_global, _verbose, _install_opencode)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn run_default_mode(global: bool, patch_mode: PatchMode, verbose: u8) -> Result<()> {
|
||||
fn run_default_mode(
|
||||
global: bool,
|
||||
patch_mode: PatchMode,
|
||||
verbose: u8,
|
||||
install_opencode: bool,
|
||||
) -> Result<()> {
|
||||
if !global {
|
||||
// Local init: inject CLAUDE.md + generate project-local filters template
|
||||
run_claude_md_mode(false, verbose)?;
|
||||
run_claude_md_mode(false, verbose, install_opencode)?;
|
||||
generate_project_filters_template(verbose)?;
|
||||
return Ok(());
|
||||
}
|
||||
@@ -714,6 +756,14 @@ fn run_default_mode(global: bool, patch_mode: PatchMode, verbose: u8) -> Result<
|
||||
// 2. Write RTK.md
|
||||
write_if_changed(&rtk_md_path, RTK_SLIM, "RTK.md", verbose)?;
|
||||
|
||||
let opencode_plugin_path = if install_opencode {
|
||||
let path = prepare_opencode_plugin_path()?;
|
||||
ensure_opencode_plugin_installed(&path, verbose)?;
|
||||
Some(path)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// 3. Patch CLAUDE.md (add @RTK.md, migrate if needed)
|
||||
let migrated = patch_claude_md(&claude_md_path, verbose)?;
|
||||
|
||||
@@ -726,6 +776,9 @@ fn run_default_mode(global: bool, patch_mode: PatchMode, verbose: u8) -> Result<
|
||||
println!("\nRTK hook {} (global).\n", hook_status);
|
||||
println!(" Hook: {}", hook_path.display());
|
||||
println!(" RTK.md: {} (10 lines)", rtk_md_path.display());
|
||||
if let Some(path) = &opencode_plugin_path {
|
||||
println!(" OpenCode: {}", path.display());
|
||||
}
|
||||
println!(" CLAUDE.md: @RTK.md reference added");
|
||||
|
||||
if migrated {
|
||||
@@ -734,7 +787,7 @@ fn run_default_mode(global: bool, patch_mode: PatchMode, verbose: u8) -> Result<
|
||||
}
|
||||
|
||||
// 5. Patch settings.json
|
||||
let patch_result = patch_settings_json(&hook_path, patch_mode, verbose)?;
|
||||
let patch_result = patch_settings_json(&hook_path, patch_mode, verbose, install_opencode)?;
|
||||
|
||||
// Report result
|
||||
match patch_result {
|
||||
@@ -743,7 +796,11 @@ fn run_default_mode(global: bool, patch_mode: PatchMode, verbose: u8) -> Result<
|
||||
}
|
||||
PatchResult::AlreadyPresent => {
|
||||
println!("\n settings.json: hook already present");
|
||||
println!(" Restart Claude Code. Test with: git status");
|
||||
if install_opencode {
|
||||
println!(" Restart Claude Code and OpenCode. Test with: git status");
|
||||
} else {
|
||||
println!(" Restart Claude Code. Test with: git status");
|
||||
}
|
||||
}
|
||||
PatchResult::Declined | PatchResult::Skipped => {
|
||||
// Manual instructions already printed by patch_settings_json
|
||||
@@ -809,12 +866,22 @@ fn generate_global_filters_template(verbose: u8) -> Result<()> {
|
||||
|
||||
/// Hook-only mode: just the hook, no RTK.md
|
||||
#[cfg(not(unix))]
|
||||
fn run_hook_only_mode(_global: bool, _patch_mode: PatchMode, _verbose: u8) -> Result<()> {
|
||||
fn run_hook_only_mode(
|
||||
_global: bool,
|
||||
_patch_mode: PatchMode,
|
||||
_verbose: u8,
|
||||
_install_opencode: bool,
|
||||
) -> Result<()> {
|
||||
anyhow::bail!("Hook install requires Unix (macOS/Linux). Use WSL or --claude-md mode.")
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn run_hook_only_mode(global: bool, patch_mode: PatchMode, verbose: u8) -> Result<()> {
|
||||
fn run_hook_only_mode(
|
||||
global: bool,
|
||||
patch_mode: PatchMode,
|
||||
verbose: u8,
|
||||
install_opencode: bool,
|
||||
) -> Result<()> {
|
||||
if !global {
|
||||
eprintln!("⚠️ Warning: --hook-only only makes sense with --global");
|
||||
eprintln!(" For local projects, use default mode or --claude-md");
|
||||
@@ -825,6 +892,14 @@ fn run_hook_only_mode(global: bool, patch_mode: PatchMode, verbose: u8) -> Resul
|
||||
let (_hook_dir, hook_path) = prepare_hook_paths()?;
|
||||
let hook_changed = ensure_hook_installed(&hook_path, verbose)?;
|
||||
|
||||
let opencode_plugin_path = if install_opencode {
|
||||
let path = prepare_opencode_plugin_path()?;
|
||||
ensure_opencode_plugin_installed(&path, verbose)?;
|
||||
Some(path)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let hook_status = if hook_changed {
|
||||
"installed/updated"
|
||||
} else {
|
||||
@@ -832,12 +907,15 @@ fn run_hook_only_mode(global: bool, patch_mode: PatchMode, verbose: u8) -> Resul
|
||||
};
|
||||
println!("\nRTK hook {} (hook-only mode).\n", hook_status);
|
||||
println!(" Hook: {}", hook_path.display());
|
||||
if let Some(path) = &opencode_plugin_path {
|
||||
println!(" OpenCode: {}", path.display());
|
||||
}
|
||||
println!(
|
||||
" Note: No RTK.md created. Claude won't know about meta commands (gain, discover, proxy)."
|
||||
);
|
||||
|
||||
// Patch settings.json
|
||||
let patch_result = patch_settings_json(&hook_path, patch_mode, verbose)?;
|
||||
let patch_result = patch_settings_json(&hook_path, patch_mode, verbose, install_opencode)?;
|
||||
|
||||
// Report result
|
||||
match patch_result {
|
||||
@@ -846,7 +924,11 @@ fn run_hook_only_mode(global: bool, patch_mode: PatchMode, verbose: u8) -> Resul
|
||||
}
|
||||
PatchResult::AlreadyPresent => {
|
||||
println!("\n settings.json: hook already present");
|
||||
println!(" Restart Claude Code. Test with: git status");
|
||||
if install_opencode {
|
||||
println!(" Restart Claude Code and OpenCode. Test with: git status");
|
||||
} else {
|
||||
println!(" Restart Claude Code. Test with: git status");
|
||||
}
|
||||
}
|
||||
PatchResult::Declined | PatchResult::Skipped => {
|
||||
// Manual instructions already printed by patch_settings_json
|
||||
@@ -859,7 +941,7 @@ fn run_hook_only_mode(global: bool, patch_mode: PatchMode, verbose: u8) -> Resul
|
||||
}
|
||||
|
||||
/// Legacy mode: full 137-line injection into CLAUDE.md
|
||||
fn run_claude_md_mode(global: bool, verbose: u8) -> Result<()> {
|
||||
fn run_claude_md_mode(global: bool, verbose: u8, install_opencode: bool) -> Result<()> {
|
||||
let path = if global {
|
||||
resolve_claude_dir()?.join("CLAUDE.md")
|
||||
} else {
|
||||
@@ -926,6 +1008,14 @@ fn run_claude_md_mode(global: bool, verbose: u8) -> Result<()> {
|
||||
}
|
||||
|
||||
if global {
|
||||
if install_opencode {
|
||||
let opencode_plugin_path = prepare_opencode_plugin_path()?;
|
||||
ensure_opencode_plugin_installed(&opencode_plugin_path, verbose)?;
|
||||
println!(
|
||||
"✅ OpenCode plugin installed: {}",
|
||||
opencode_plugin_path.display()
|
||||
);
|
||||
}
|
||||
println!(" Claude Code will now use rtk in all sessions");
|
||||
} else {
|
||||
println!(" Claude Code will use rtk in this project");
|
||||
@@ -1091,6 +1181,58 @@ fn resolve_claude_dir() -> Result<PathBuf> {
|
||||
.context("Cannot determine home directory. Is $HOME set?")
|
||||
}
|
||||
|
||||
/// Resolve OpenCode config directory (~/.config/opencode)
|
||||
/// OpenCode uses ~/.config/opencode on all platforms (XDG convention),
|
||||
/// NOT the macOS-native ~/Library/Application Support/.
|
||||
fn resolve_opencode_dir() -> Result<PathBuf> {
|
||||
dirs::home_dir()
|
||||
.map(|h| h.join(".config").join("opencode"))
|
||||
.context("Cannot determine home directory. Is $HOME set?")
|
||||
}
|
||||
|
||||
/// Return OpenCode plugin path: ~/.config/opencode/plugins/rtk.ts
|
||||
fn opencode_plugin_path(opencode_dir: &Path) -> PathBuf {
|
||||
opencode_dir.join("plugins").join("rtk.ts")
|
||||
}
|
||||
|
||||
/// Prepare OpenCode plugin directory and return install path
|
||||
fn prepare_opencode_plugin_path() -> Result<PathBuf> {
|
||||
let opencode_dir = resolve_opencode_dir()?;
|
||||
let path = opencode_plugin_path(&opencode_dir);
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent).with_context(|| {
|
||||
format!(
|
||||
"Failed to create OpenCode plugin directory: {}",
|
||||
parent.display()
|
||||
)
|
||||
})?;
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// Write OpenCode plugin file if missing or outdated
|
||||
fn ensure_opencode_plugin_installed(path: &Path, verbose: u8) -> Result<bool> {
|
||||
write_if_changed(path, OPENCODE_PLUGIN, "OpenCode plugin", verbose)
|
||||
}
|
||||
|
||||
/// Remove OpenCode plugin file
|
||||
fn remove_opencode_plugin(verbose: u8) -> Result<Vec<PathBuf>> {
|
||||
let opencode_dir = resolve_opencode_dir()?;
|
||||
let path = opencode_plugin_path(&opencode_dir);
|
||||
let mut removed = Vec::new();
|
||||
|
||||
if path.exists() {
|
||||
fs::remove_file(&path)
|
||||
.with_context(|| format!("Failed to remove OpenCode plugin: {}", path.display()))?;
|
||||
if verbose > 0 {
|
||||
eprintln!("Removed OpenCode plugin: {}", path.display());
|
||||
}
|
||||
removed.push(path);
|
||||
}
|
||||
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
/// Show current rtk configuration
|
||||
pub fn show_config() -> Result<()> {
|
||||
let claude_dir = resolve_claude_dir()?;
|
||||
@@ -1226,6 +1368,18 @@ pub fn show_config() -> Result<()> {
|
||||
println!("⚪ settings.json: not found");
|
||||
}
|
||||
|
||||
// Check OpenCode plugin
|
||||
if let Ok(opencode_dir) = resolve_opencode_dir() {
|
||||
let plugin = opencode_plugin_path(&opencode_dir);
|
||||
if plugin.exists() {
|
||||
println!("✅ OpenCode: plugin installed ({})", plugin.display());
|
||||
} else {
|
||||
println!("⚪ OpenCode: plugin not found");
|
||||
}
|
||||
} else {
|
||||
println!("⚪ OpenCode: config dir not found");
|
||||
}
|
||||
|
||||
println!("\nUsage:");
|
||||
println!(" rtk init # Full injection into local CLAUDE.md");
|
||||
println!(" rtk init -g # Hook + RTK.md + @RTK.md + settings.json (recommended)");
|
||||
@@ -1234,13 +1388,24 @@ pub fn show_config() -> Result<()> {
|
||||
println!(" rtk init -g --uninstall # Remove all RTK artifacts");
|
||||
println!(" rtk init -g --claude-md # Legacy: full injection into ~/.claude/CLAUDE.md");
|
||||
println!(" rtk init -g --hook-only # Hook only, no RTK.md");
|
||||
println!(" rtk init -g --opencode # OpenCode plugin only");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_opencode_only_mode(verbose: u8) -> Result<()> {
|
||||
let opencode_plugin_path = prepare_opencode_plugin_path()?;
|
||||
ensure_opencode_plugin_installed(&opencode_plugin_path, verbose)?;
|
||||
println!("\nOpenCode plugin installed (global).\n");
|
||||
println!(" OpenCode: {}", opencode_plugin_path.display());
|
||||
println!(" Restart OpenCode. Test with: git status\n");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::Path;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
@@ -1308,6 +1473,40 @@ More content"#;
|
||||
assert!(result.contains("More content"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_opencode_plugin_install_and_update() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let opencode_dir = temp.path().join("opencode");
|
||||
let plugin_path = opencode_plugin_path(&opencode_dir);
|
||||
|
||||
fs::create_dir_all(plugin_path.parent().unwrap()).unwrap();
|
||||
assert!(!plugin_path.exists());
|
||||
|
||||
let changed = ensure_opencode_plugin_installed(&plugin_path, 0).unwrap();
|
||||
assert!(changed);
|
||||
let content = fs::read_to_string(&plugin_path).unwrap();
|
||||
assert_eq!(content, OPENCODE_PLUGIN);
|
||||
|
||||
fs::write(&plugin_path, "// old").unwrap();
|
||||
let changed_again = ensure_opencode_plugin_installed(&plugin_path, 0).unwrap();
|
||||
assert!(changed_again);
|
||||
let content_updated = fs::read_to_string(&plugin_path).unwrap();
|
||||
assert_eq!(content_updated, OPENCODE_PLUGIN);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_opencode_plugin_remove() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let opencode_dir = temp.path().join("opencode");
|
||||
let plugin_path = opencode_plugin_path(&opencode_dir);
|
||||
fs::create_dir_all(plugin_path.parent().unwrap()).unwrap();
|
||||
fs::write(&plugin_path, OPENCODE_PLUGIN).unwrap();
|
||||
|
||||
assert!(plugin_path.exists());
|
||||
fs::remove_file(&plugin_path).unwrap();
|
||||
assert!(!plugin_path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_migration_warns_on_missing_end_marker() {
|
||||
let input = "<!-- rtk-instructions v2 -->\nOLD STUFF\nNo end marker";
|
||||
|
||||
@@ -121,6 +121,7 @@ fn lang_display_name(lang: &Language) -> &'static str {
|
||||
Language::Java => "Java",
|
||||
Language::Ruby => "Ruby",
|
||||
Language::Shell => "Shell",
|
||||
Language::Data => "Data",
|
||||
Language::Unknown => "Code",
|
||||
}
|
||||
}
|
||||
|
||||
+228
-15
@@ -1,4 +1,5 @@
|
||||
mod aws_cmd;
|
||||
mod binlog;
|
||||
mod cargo_cmd;
|
||||
mod cc_economics;
|
||||
mod ccusage;
|
||||
@@ -9,6 +10,9 @@ mod deps;
|
||||
mod diff_cmd;
|
||||
mod discover;
|
||||
mod display_helpers;
|
||||
mod dotnet_cmd;
|
||||
mod dotnet_format_report;
|
||||
mod dotnet_trx;
|
||||
mod env_cmd;
|
||||
mod filter;
|
||||
mod find_cmd;
|
||||
@@ -112,8 +116,11 @@ enum Commands {
|
||||
#[arg(short, long, default_value = "minimal")]
|
||||
level: filter::FilterLevel,
|
||||
/// Max lines
|
||||
#[arg(short, long)]
|
||||
#[arg(short, long, conflicts_with = "tail_lines")]
|
||||
max_lines: Option<usize>,
|
||||
/// Keep only last N lines
|
||||
#[arg(long, conflicts_with = "max_lines")]
|
||||
tail_lines: Option<usize>,
|
||||
/// Show line numbers
|
||||
#[arg(short = 'n', long)]
|
||||
line_numbers: bool,
|
||||
@@ -261,6 +268,12 @@ enum Commands {
|
||||
file: Option<PathBuf>,
|
||||
},
|
||||
|
||||
/// .NET commands with compact output (build/test/restore/format)
|
||||
Dotnet {
|
||||
#[command(subcommand)]
|
||||
command: DotnetCommands,
|
||||
},
|
||||
|
||||
/// Docker commands with compact output
|
||||
Docker {
|
||||
#[command(subcommand)]
|
||||
@@ -313,6 +326,10 @@ enum Commands {
|
||||
#[arg(short, long)]
|
||||
global: bool,
|
||||
|
||||
/// Install OpenCode plugin (in addition to Claude Code)
|
||||
#[arg(long)]
|
||||
opencode: bool,
|
||||
|
||||
/// Show current configuration
|
||||
#[arg(long)]
|
||||
show: bool,
|
||||
@@ -627,7 +644,9 @@ enum Commands {
|
||||
/// REWRITTEN=$(rtk rewrite "$CMD") || exit 0
|
||||
Rewrite {
|
||||
/// Raw command to rewrite (e.g. "git status", "cargo test && git push")
|
||||
cmd: String,
|
||||
/// Accepts multiple args: `rtk rewrite ls -al` is equivalent to `rtk rewrite "ls -al"`
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -919,6 +938,33 @@ enum CargoCommands {
|
||||
Other(Vec<OsString>),
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum DotnetCommands {
|
||||
/// Build with compact output
|
||||
Build {
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
},
|
||||
/// Test with compact output
|
||||
Test {
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
},
|
||||
/// Restore with compact output
|
||||
Restore {
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
},
|
||||
/// Format with compact output
|
||||
Format {
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
},
|
||||
/// Passthrough: runs any unsupported dotnet subcommand directly
|
||||
#[command(external_subcommand)]
|
||||
Other(Vec<OsString>),
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum GoCommands {
|
||||
/// Run tests with compact output (90% token reduction via JSON streaming)
|
||||
@@ -1109,13 +1155,37 @@ enum GtCommands {
|
||||
Other(Vec<OsString>),
|
||||
}
|
||||
|
||||
/// Split a string into shell-like tokens, respecting single and double quotes.
|
||||
/// e.g. `git log --format="%H %s"` → ["git", "log", "--format=%H %s"]
|
||||
fn shell_split(input: &str) -> Vec<String> {
|
||||
let mut tokens = Vec::new();
|
||||
let mut current = String::new();
|
||||
let mut chars = input.chars().peekable();
|
||||
let mut in_single = false;
|
||||
let mut in_double = false;
|
||||
|
||||
while let Some(c) = chars.next() {
|
||||
match c {
|
||||
'\'' if !in_double => in_single = !in_single,
|
||||
'"' if !in_single => in_double = !in_double,
|
||||
' ' | '\t' if !in_single && !in_double => {
|
||||
if !current.is_empty() {
|
||||
tokens.push(std::mem::take(&mut current));
|
||||
}
|
||||
}
|
||||
_ => current.push(c),
|
||||
}
|
||||
}
|
||||
if !current.is_empty() {
|
||||
tokens.push(current);
|
||||
}
|
||||
tokens
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
// Fire-and-forget telemetry ping (1/day, non-blocking)
|
||||
telemetry::maybe_ping();
|
||||
|
||||
// Warn if installed hook is outdated (1/day, non-blocking)
|
||||
hook_check::maybe_warn();
|
||||
|
||||
let cli = match Cli::try_parse() {
|
||||
Ok(cli) => cli,
|
||||
Err(e) => {
|
||||
@@ -1126,6 +1196,12 @@ fn main() -> Result<()> {
|
||||
}
|
||||
};
|
||||
|
||||
// Warn if installed hook is outdated/missing (1/day, non-blocking).
|
||||
// Skip for Gain — it shows its own inline hook warning.
|
||||
if !matches!(cli.command, Commands::Gain { .. }) {
|
||||
hook_check::maybe_warn();
|
||||
}
|
||||
|
||||
// Runtime integrity check for operational commands.
|
||||
// Meta commands (init, gain, verify, config, etc.) skip the check
|
||||
// because they don't go through the hook pipeline.
|
||||
@@ -1146,12 +1222,20 @@ fn main() -> Result<()> {
|
||||
file,
|
||||
level,
|
||||
max_lines,
|
||||
tail_lines,
|
||||
line_numbers,
|
||||
} => {
|
||||
if file == Path::new("-") {
|
||||
read::run_stdin(level, max_lines, line_numbers, cli.verbose)?;
|
||||
read::run_stdin(level, max_lines, tail_lines, line_numbers, cli.verbose)?;
|
||||
} else {
|
||||
read::run(&file, level, max_lines, line_numbers, cli.verbose)?;
|
||||
read::run(
|
||||
&file,
|
||||
level,
|
||||
max_lines,
|
||||
tail_lines,
|
||||
line_numbers,
|
||||
cli.verbose,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1394,6 +1478,24 @@ fn main() -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
Commands::Dotnet { command } => match command {
|
||||
DotnetCommands::Build { args } => {
|
||||
dotnet_cmd::run_build(&args, cli.verbose)?;
|
||||
}
|
||||
DotnetCommands::Test { args } => {
|
||||
dotnet_cmd::run_test(&args, cli.verbose)?;
|
||||
}
|
||||
DotnetCommands::Restore { args } => {
|
||||
dotnet_cmd::run_restore(&args, cli.verbose)?;
|
||||
}
|
||||
DotnetCommands::Format { args } => {
|
||||
dotnet_cmd::run_format(&args, cli.verbose)?;
|
||||
}
|
||||
DotnetCommands::Other(args) => {
|
||||
dotnet_cmd::run_passthrough(&args, cli.verbose)?;
|
||||
}
|
||||
},
|
||||
|
||||
Commands::Docker { command } => match command {
|
||||
DockerCommands::Ps => {
|
||||
container::run(container::ContainerCmd::DockerPs, &[], cli.verbose)?;
|
||||
@@ -1486,6 +1588,7 @@ fn main() -> Result<()> {
|
||||
|
||||
Commands::Init {
|
||||
global,
|
||||
opencode,
|
||||
show,
|
||||
claude_md,
|
||||
hook_only,
|
||||
@@ -1498,6 +1601,9 @@ fn main() -> Result<()> {
|
||||
} else if uninstall {
|
||||
init::uninstall(global, cli.verbose)?;
|
||||
} else {
|
||||
let install_opencode = opencode;
|
||||
let install_claude = !opencode;
|
||||
|
||||
let patch_mode = if auto_patch {
|
||||
init::PatchMode::Auto
|
||||
} else if no_patch {
|
||||
@@ -1505,7 +1611,15 @@ fn main() -> Result<()> {
|
||||
} else {
|
||||
init::PatchMode::Ask
|
||||
};
|
||||
init::run(global, claude_md, hook_only, patch_mode, cli.verbose)?;
|
||||
init::run(
|
||||
global,
|
||||
install_claude,
|
||||
install_opencode,
|
||||
claude_md,
|
||||
hook_only,
|
||||
patch_mode,
|
||||
cli.verbose,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1840,7 +1954,8 @@ fn main() -> Result<()> {
|
||||
hook_audit_cmd::run(since, cli.verbose)?;
|
||||
}
|
||||
|
||||
Commands::Rewrite { cmd } => {
|
||||
Commands::Rewrite { args } => {
|
||||
let cmd = args.join(" ");
|
||||
rewrite_cmd::run(&cmd)?;
|
||||
}
|
||||
|
||||
@@ -1857,17 +1972,32 @@ fn main() -> Result<()> {
|
||||
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
let cmd_name = args[0].to_string_lossy();
|
||||
let cmd_args: Vec<String> = args[1..]
|
||||
.iter()
|
||||
.map(|s| s.to_string_lossy().into_owned())
|
||||
.collect();
|
||||
// If a single quoted arg contains spaces, split it respecting quotes (#388).
|
||||
// e.g. rtk proxy 'head -50 file.php' → cmd=head, args=["-50", "file.php"]
|
||||
// e.g. rtk proxy 'git log --format="%H %s"' → cmd=git, args=["log", "--format=%H %s"]
|
||||
let (cmd_name, cmd_args): (String, Vec<String>) = if args.len() == 1 {
|
||||
let full = args[0].to_string_lossy();
|
||||
let parts = shell_split(&full);
|
||||
if parts.len() > 1 {
|
||||
(parts[0].clone(), parts[1..].to_vec())
|
||||
} else {
|
||||
(full.into_owned(), vec![])
|
||||
}
|
||||
} else {
|
||||
(
|
||||
args[0].to_string_lossy().into_owned(),
|
||||
args[1..]
|
||||
.iter()
|
||||
.map(|s| s.to_string_lossy().into_owned())
|
||||
.collect(),
|
||||
)
|
||||
};
|
||||
|
||||
if cli.verbose > 0 {
|
||||
eprintln!("Proxy mode: {} {}", cmd_name, cmd_args.join(" "));
|
||||
}
|
||||
|
||||
let mut child = Command::new(cmd_name.as_ref())
|
||||
let mut child = Command::new(&cmd_name)
|
||||
.args(&cmd_args)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
@@ -1996,6 +2126,7 @@ fn is_operational_command(cmd: &Commands) -> bool {
|
||||
| Commands::Find { .. }
|
||||
| Commands::Diff { .. }
|
||||
| Commands::Log { .. }
|
||||
| Commands::Dotnet { .. }
|
||||
| Commands::Docker { .. }
|
||||
| Commands::Kubectl { .. }
|
||||
| Commands::Summary { .. }
|
||||
@@ -2266,4 +2397,86 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_shell_split_simple() {
|
||||
assert_eq!(
|
||||
shell_split("head -50 file.php"),
|
||||
vec!["head", "-50", "file.php"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_shell_split_double_quotes() {
|
||||
assert_eq!(
|
||||
shell_split(r#"git log --format="%H %s""#),
|
||||
vec!["git", "log", "--format=%H %s"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_shell_split_single_quotes() {
|
||||
assert_eq!(
|
||||
shell_split("grep -r 'hello world' ."),
|
||||
vec!["grep", "-r", "hello world", "."]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_shell_split_single_word() {
|
||||
assert_eq!(shell_split("ls"), vec!["ls"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_shell_split_empty() {
|
||||
let result: Vec<String> = shell_split("");
|
||||
assert!(result.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_clap_multi_args() {
|
||||
// This is the bug KuSh reported: `rtk rewrite ls -al` failed because
|
||||
// Clap rejected `-al` as an unknown flag. With trailing_var_arg + allow_hyphen_values,
|
||||
// multiple args are accepted and joined into a single command string.
|
||||
let cases = vec![
|
||||
vec!["rtk", "rewrite", "ls", "-al"],
|
||||
vec!["rtk", "rewrite", "git", "status"],
|
||||
vec!["rtk", "rewrite", "npm", "exec"],
|
||||
vec!["rtk", "rewrite", "cargo", "test"],
|
||||
vec!["rtk", "rewrite", "du", "-sh", "."],
|
||||
vec!["rtk", "rewrite", "head", "-50", "file.txt"],
|
||||
];
|
||||
for args in &cases {
|
||||
let result = Cli::try_parse_from(args.iter());
|
||||
assert!(
|
||||
result.is_ok(),
|
||||
"rtk rewrite {:?} should parse (was failing before trailing_var_arg fix)",
|
||||
&args[2..]
|
||||
);
|
||||
if let Ok(cli) = result {
|
||||
match cli.command {
|
||||
Commands::Rewrite { ref args } => {
|
||||
assert!(args.len() >= 2, "rewrite args should capture all tokens");
|
||||
}
|
||||
_ => panic!("expected Rewrite command"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_clap_quoted_single_arg() {
|
||||
// Quoted form: `rtk rewrite "git status"` — single arg containing spaces
|
||||
let result = Cli::try_parse_from(["rtk", "rewrite", "git status"]);
|
||||
assert!(result.is_ok());
|
||||
if let Ok(cli) = result {
|
||||
match cli.command {
|
||||
Commands::Rewrite { ref args } => {
|
||||
assert_eq!(args.len(), 1);
|
||||
assert_eq!(args[0], "git status");
|
||||
}
|
||||
_ => panic!("expected Rewrite command"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+122
-35
@@ -2,16 +2,98 @@ use crate::tracking;
|
||||
use anyhow::{Context, Result};
|
||||
use std::process::Command;
|
||||
|
||||
/// Known npm subcommands that should NOT get "run" injected.
|
||||
/// Shared between production code and tests to avoid drift.
|
||||
const NPM_SUBCOMMANDS: &[&str] = &[
|
||||
"install",
|
||||
"i",
|
||||
"ci",
|
||||
"uninstall",
|
||||
"remove",
|
||||
"rm",
|
||||
"update",
|
||||
"up",
|
||||
"list",
|
||||
"ls",
|
||||
"outdated",
|
||||
"init",
|
||||
"create",
|
||||
"publish",
|
||||
"pack",
|
||||
"link",
|
||||
"audit",
|
||||
"fund",
|
||||
"exec",
|
||||
"explain",
|
||||
"why",
|
||||
"search",
|
||||
"view",
|
||||
"info",
|
||||
"show",
|
||||
"config",
|
||||
"set",
|
||||
"get",
|
||||
"cache",
|
||||
"prune",
|
||||
"dedupe",
|
||||
"doctor",
|
||||
"help",
|
||||
"version",
|
||||
"prefix",
|
||||
"root",
|
||||
"bin",
|
||||
"bugs",
|
||||
"docs",
|
||||
"home",
|
||||
"repo",
|
||||
"ping",
|
||||
"whoami",
|
||||
"token",
|
||||
"profile",
|
||||
"team",
|
||||
"access",
|
||||
"owner",
|
||||
"deprecate",
|
||||
"dist-tag",
|
||||
"star",
|
||||
"stars",
|
||||
"login",
|
||||
"logout",
|
||||
"adduser",
|
||||
"unpublish",
|
||||
"pkg",
|
||||
"diff",
|
||||
"rebuild",
|
||||
"test",
|
||||
"t",
|
||||
"start",
|
||||
"stop",
|
||||
"restart",
|
||||
];
|
||||
|
||||
pub fn run(args: &[String], verbose: u8, skip_env: bool) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
let mut cmd = Command::new("npm");
|
||||
cmd.arg("run");
|
||||
|
||||
// Strip leading "run" to avoid doubling (rtk npm run build → npm run build, not npm run run build)
|
||||
let effective_args = if args.first().map(|s| s.as_str()) == Some("run") {
|
||||
// Determine if this is "npm run <script>" or another npm subcommand (install, list, etc.)
|
||||
// Only inject "run" when args look like a script name, not a known npm subcommand.
|
||||
let first_arg = args.first().map(|s| s.as_str());
|
||||
let is_run_explicit = first_arg == Some("run");
|
||||
let is_npm_subcommand = first_arg
|
||||
.map(|a| NPM_SUBCOMMANDS.contains(&a) || a.starts_with('-'))
|
||||
.unwrap_or(false);
|
||||
|
||||
let effective_args = if is_run_explicit {
|
||||
// "rtk npm run build" → "npm run build"
|
||||
cmd.arg("run");
|
||||
&args[1..]
|
||||
} else if is_npm_subcommand {
|
||||
// "rtk npm install express" → "npm install express"
|
||||
args
|
||||
} else {
|
||||
// "rtk npm build" → "npm run build" (assume script name)
|
||||
cmd.arg("run");
|
||||
args
|
||||
};
|
||||
|
||||
@@ -24,10 +106,10 @@ pub fn run(args: &[String], verbose: u8, skip_env: bool) -> Result<()> {
|
||||
}
|
||||
|
||||
if verbose > 0 {
|
||||
eprintln!("Running: npm run {}", effective_args.join(" "));
|
||||
eprintln!("Running: npm {}", args.join(" "));
|
||||
}
|
||||
|
||||
let output = cmd.output().context("Failed to run npm run")?;
|
||||
let output = cmd.output().context("Failed to run npm")?;
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let raw = format!("{}\n{}", stdout, stderr);
|
||||
@@ -36,8 +118,8 @@ pub fn run(args: &[String], verbose: u8, skip_env: bool) -> Result<()> {
|
||||
println!("{}", filtered);
|
||||
|
||||
timer.track(
|
||||
&format!("npm run {}", effective_args.join(" ")),
|
||||
&format!("rtk npm run {}", effective_args.join(" ")),
|
||||
&format!("npm {}", args.join(" ")),
|
||||
&format!("rtk npm {}", args.join(" ")),
|
||||
&raw,
|
||||
&filtered,
|
||||
);
|
||||
@@ -108,36 +190,41 @@ npm notice
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_leading_run_from_args() {
|
||||
// When user runs `rtk npm run build`, args = ["run", "build"]
|
||||
// The "run" should be stripped since cmd.arg("run") already adds it
|
||||
let args: Vec<String> = vec!["run".into(), "build".into()];
|
||||
let effective_args = if args.first().map(|s| s.as_str()) == Some("run") {
|
||||
&args[1..]
|
||||
} else {
|
||||
&args[..]
|
||||
};
|
||||
assert_eq!(effective_args, &["build"]);
|
||||
fn test_npm_subcommand_routing() {
|
||||
// Uses the shared NPM_SUBCOMMANDS constant — no drift between prod and test
|
||||
fn needs_run_injection(args: &[&str]) -> bool {
|
||||
let first = args.first().copied();
|
||||
let is_run_explicit = first == Some("run");
|
||||
let is_subcommand = first
|
||||
.map(|a| NPM_SUBCOMMANDS.contains(&a) || a.starts_with('-'))
|
||||
.unwrap_or(false);
|
||||
!is_run_explicit && !is_subcommand
|
||||
}
|
||||
|
||||
// When user runs `rtk npm build`, args = ["build"]
|
||||
// No stripping needed
|
||||
let args2: Vec<String> = vec!["build".into()];
|
||||
let effective_args2 = if args2.first().map(|s| s.as_str()) == Some("run") {
|
||||
&args2[1..]
|
||||
} else {
|
||||
&args2[..]
|
||||
};
|
||||
assert_eq!(effective_args2, &["build"]);
|
||||
// Known subcommands should NOT get "run" injected
|
||||
for subcmd in NPM_SUBCOMMANDS {
|
||||
assert!(
|
||||
!needs_run_injection(&[subcmd]),
|
||||
"'npm {}' should NOT inject 'run'",
|
||||
subcmd
|
||||
);
|
||||
}
|
||||
|
||||
// When user runs `rtk npm run`, args = ["run"]
|
||||
// Strip "run" → empty args (npm run with no script)
|
||||
let args3: Vec<String> = vec!["run".into()];
|
||||
let effective_args3 = if args3.first().map(|s| s.as_str()) == Some("run") {
|
||||
&args3[1..]
|
||||
} else {
|
||||
&args3[..]
|
||||
};
|
||||
assert!(effective_args3.is_empty());
|
||||
// Script names SHOULD get "run" injected
|
||||
for script in &["build", "dev", "lint", "typecheck", "deploy"] {
|
||||
assert!(
|
||||
needs_run_injection(&[script]),
|
||||
"'npm {}' SHOULD inject 'run'",
|
||||
script
|
||||
);
|
||||
}
|
||||
|
||||
// Flags should NOT get "run" injected
|
||||
assert!(!needs_run_injection(&["--version"]));
|
||||
assert!(!needs_run_injection(&["-h"]));
|
||||
|
||||
// Explicit "run" should NOT inject another "run"
|
||||
assert!(!needs_run_injection(&["run", "build"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+53
-9
@@ -8,6 +8,7 @@ pub fn run(
|
||||
file: &Path,
|
||||
level: FilterLevel,
|
||||
max_lines: Option<usize>,
|
||||
tail_lines: Option<usize>,
|
||||
line_numbers: bool,
|
||||
verbose: u8,
|
||||
) -> Result<()> {
|
||||
@@ -50,10 +51,7 @@ pub fn run(
|
||||
);
|
||||
}
|
||||
|
||||
// Apply smart truncation if max_lines is set
|
||||
if let Some(max) = max_lines {
|
||||
filtered = filter::smart_truncate(&filtered, max, &lang);
|
||||
}
|
||||
filtered = apply_line_window(&filtered, max_lines, tail_lines, &lang);
|
||||
|
||||
let rtk_output = if line_numbers {
|
||||
format_with_line_numbers(&filtered)
|
||||
@@ -73,6 +71,7 @@ pub fn run(
|
||||
pub fn run_stdin(
|
||||
level: FilterLevel,
|
||||
max_lines: Option<usize>,
|
||||
tail_lines: Option<usize>,
|
||||
line_numbers: bool,
|
||||
verbose: u8,
|
||||
) -> Result<()> {
|
||||
@@ -116,10 +115,7 @@ pub fn run_stdin(
|
||||
);
|
||||
}
|
||||
|
||||
// Apply smart truncation if max_lines is set
|
||||
if let Some(max) = max_lines {
|
||||
filtered = filter::smart_truncate(&filtered, max, &lang);
|
||||
}
|
||||
filtered = apply_line_window(&filtered, max_lines, tail_lines, &lang);
|
||||
|
||||
let rtk_output = if line_numbers {
|
||||
format_with_line_numbers(&filtered)
|
||||
@@ -142,6 +138,32 @@ fn format_with_line_numbers(content: &str) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
fn apply_line_window(
|
||||
content: &str,
|
||||
max_lines: Option<usize>,
|
||||
tail_lines: Option<usize>,
|
||||
lang: &Language,
|
||||
) -> String {
|
||||
if let Some(tail) = tail_lines {
|
||||
if tail == 0 {
|
||||
return String::new();
|
||||
}
|
||||
let lines: Vec<&str> = content.lines().collect();
|
||||
let start = lines.len().saturating_sub(tail);
|
||||
let mut result = lines[start..].join("\n");
|
||||
if content.ends_with('\n') {
|
||||
result.push('\n');
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
if let Some(max) = max_lines {
|
||||
return filter::smart_truncate(content, max, lang);
|
||||
}
|
||||
|
||||
content.to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -160,7 +182,7 @@ fn main() {{
|
||||
)?;
|
||||
|
||||
// Just verify it doesn't panic
|
||||
run(file.path(), FilterLevel::Minimal, None, false, 0)?;
|
||||
run(file.path(), FilterLevel::Minimal, None, None, false, 0)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -170,4 +192,26 @@ fn main() {{
|
||||
// We don't actually run it because it would hang waiting for stdin
|
||||
// Compile-time verification that the function exists with correct signature
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_apply_line_window_tail_lines() {
|
||||
let input = "a\nb\nc\nd\n";
|
||||
let output = apply_line_window(input, None, Some(2), &Language::Unknown);
|
||||
assert_eq!(output, "c\nd\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_apply_line_window_tail_lines_no_trailing_newline() {
|
||||
let input = "a\nb\nc\nd";
|
||||
let output = apply_line_window(input, None, Some(2), &Language::Unknown);
|
||||
assert_eq!(output, "c\nd");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_apply_line_window_max_lines_still_works() {
|
||||
let input = "a\nb\nc\nd\n";
|
||||
let output = apply_line_window(input, Some(2), None, &Language::Unknown);
|
||||
assert!(output.starts_with("a\n"));
|
||||
assert!(output.contains("more lines"));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -37,7 +37,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_run_unsupported_returns_none() {
|
||||
assert!(registry::rewrite_command("terraform plan", &[]).is_none());
|
||||
assert!(registry::rewrite_command("htop", &[]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+5
-5
@@ -1579,8 +1579,8 @@ match_command = "^make\\b"
|
||||
let filters = make_filters(BUILTIN_TOML);
|
||||
assert_eq!(
|
||||
filters.len(),
|
||||
36,
|
||||
"Expected exactly 36 built-in filters, got {}. \
|
||||
47,
|
||||
"Expected exactly 47 built-in filters, got {}. \
|
||||
Update this count when adding/removing filters in src/filters/.",
|
||||
filters.len()
|
||||
);
|
||||
@@ -1637,11 +1637,11 @@ expected = "output line 1\noutput line 2"
|
||||
let combined = format!("{}\n\n{}", BUILTIN_TOML, new_filter);
|
||||
let filters = make_filters(&combined);
|
||||
|
||||
// All 36 existing filters still present + 1 new = 37
|
||||
// All 47 existing filters still present + 1 new = 48
|
||||
assert_eq!(
|
||||
filters.len(),
|
||||
37,
|
||||
"Expected 37 filters after concat (36 built-in + 1 new)"
|
||||
48,
|
||||
"Expected 48 filters after concat (47 built-in + 1 new)"
|
||||
);
|
||||
|
||||
// New filter is discoverable
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
Determining projects to restore...
|
||||
All projects are up-to-date for restore.
|
||||
/private/tmp/RtkDotnetSmoke/Broken.cs(7,17): error CS1525: Invalid expression term ';' [/private/tmp/RtkDotnetSmoke/RtkDotnetSmoke.csproj]
|
||||
|
||||
Build FAILED.
|
||||
|
||||
/private/tmp/RtkDotnetSmoke/Broken.cs(7,17): error CS1525: Invalid expression term ';' [/private/tmp/RtkDotnetSmoke/RtkDotnetSmoke.csproj]
|
||||
0 Warning(s)
|
||||
1 Error(s)
|
||||
|
||||
Time Elapsed 00:00:00.76
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
[
|
||||
{
|
||||
"FileName": "Program.cs",
|
||||
"FilePath": "src/Program.cs",
|
||||
"FileChanges": [
|
||||
{
|
||||
"LineNumber": 42,
|
||||
"CharNumber": 17,
|
||||
"DiagnosticId": "WHITESPACE",
|
||||
"FormatDescription": "Fix whitespace"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"FileName": "Utils.cs",
|
||||
"FilePath": "src/Utils.cs",
|
||||
"FileChanges": [
|
||||
{
|
||||
"LineNumber": 15,
|
||||
"CharNumber": 8,
|
||||
"DiagnosticId": "IDE0055",
|
||||
"FormatDescription": "Fix formatting"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"FileName": "Tests.cs",
|
||||
"FilePath": "tests/Tests.cs",
|
||||
"FileChanges": []
|
||||
}
|
||||
]
|
||||
+1
@@ -0,0 +1 @@
|
||||
[]
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
[
|
||||
{
|
||||
"FileName": "Program.cs",
|
||||
"FilePath": "src/Program.cs",
|
||||
"FileChanges": []
|
||||
},
|
||||
{
|
||||
"FileName": "Utils.cs",
|
||||
"FilePath": "src/Utils.cs",
|
||||
"FileChanges": []
|
||||
}
|
||||
]
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
Determining projects to restore...
|
||||
All projects are up-to-date for restore.
|
||||
RtkDotnetSmoke -> /private/tmp/RtkDotnetSmoke/bin/Debug/net10.0/RtkDotnetSmoke.dll
|
||||
Test run for /private/tmp/RtkDotnetSmoke/bin/Debug/net10.0/RtkDotnetSmoke.dll (.NETCoreApp,Version=v10.0)
|
||||
VSTest version 18.0.1 (arm64)
|
||||
|
||||
Starting test execution, please wait...
|
||||
A total of 1 test files matched the specified pattern.
|
||||
[xUnit.net 00:00:00.11] RtkDotnetSmoke.UnitTest1.Test1 [FAIL]
|
||||
Failed RtkDotnetSmoke.UnitTest1.Test1 [4 ms]
|
||||
Error Message:
|
||||
Assert.Equal() Failure: Values differ
|
||||
Expected: 2
|
||||
Actual: 3
|
||||
Stack Trace:
|
||||
at RtkDotnetSmoke.UnitTest1.Test1() in /private/tmp/RtkDotnetSmoke/UnitTest1.cs:line 8
|
||||
|
||||
Failed! - Failed: 1, Passed: 0, Skipped: 0, Total: 1, Duration: 13 ms - RtkDotnetSmoke.dll (net10.0)
|
||||
Reference in new issue
Block a user