Compare commits
134
Commits
No files matched your search
@@ -85,15 +85,15 @@ elif echo "$FIRST_CMD" | grep -qE '^find\s+'; then
|
||||
elif echo "$FIRST_CMD" | grep -qE '^diff\s+'; then
|
||||
SUGGESTION=$(echo "$CMD" | sed 's/^diff /rtk diff /')
|
||||
elif echo "$FIRST_CMD" | grep -qE '^head\s+'; then
|
||||
# Suggest rtk read with --max-lines transformation
|
||||
# Suggest rtk read with --head-lines transformation
|
||||
if echo "$FIRST_CMD" | grep -qE '^head\s+-[0-9]+\s+'; then
|
||||
LINES=$(echo "$FIRST_CMD" | sed -E 's/^head +-([0-9]+) +.+$/\1/')
|
||||
FILE=$(echo "$FIRST_CMD" | sed -E 's/^head +-[0-9]+ +(.+)$/\1/')
|
||||
SUGGESTION="rtk read $FILE --max-lines $LINES"
|
||||
SUGGESTION="rtk read $FILE --head-lines $LINES"
|
||||
elif echo "$FIRST_CMD" | grep -qE '^head\s+--lines=[0-9]+\s+'; then
|
||||
LINES=$(echo "$FIRST_CMD" | sed -E 's/^head +--lines=([0-9]+) +.+$/\1/')
|
||||
FILE=$(echo "$FIRST_CMD" | sed -E 's/^head +--lines=[0-9]+ +(.+)$/\1/')
|
||||
SUGGESTION="rtk read $FILE --max-lines $LINES"
|
||||
SUGGESTION="rtk read $FILE --head-lines $LINES"
|
||||
fi
|
||||
|
||||
# --- JS/TS tooling ---
|
||||
|
||||
@@ -11,6 +11,10 @@ These override general Rust conventions:
|
||||
3. **Lazy regex** — Put fixed patterns reused across calls in `LazyLock<Regex>`; keep runtime-dependent patterns local.
|
||||
4. **Fallback pattern** — If filter fails, execute raw command unchanged. Never block the user.
|
||||
5. **Exit code propagation** — `std::process::exit(code)` if underlying command fails.
|
||||
6. **Parse args with `arg_tokenizer`** — every new command, flag, or arg-handling fix classifies
|
||||
arguments through `tokenize`/`tokenize_with_options`, never a `starts_with('-')` or
|
||||
`arg == "--flag"` scan. See [`src/core/README.md`](../../src/core/README.md#argument-tokenizer-arg_tokenizerrs)
|
||||
for the four rules that go with it.
|
||||
|
||||
## Error Handling
|
||||
|
||||
|
||||
@@ -45,6 +45,7 @@ RTK intercepts shell commands and compresses their output before your agent read
|
||||
| `ls` / `tree` | Tree format with file counts instead of one line per entry |
|
||||
| `cat` / `read` | Smart file reading: signatures and structure over full bodies |
|
||||
| `grep` / `rg` | Truncates long lines, groups matches by file |
|
||||
| `ast-grep` | Groups structural matches by file, caps overflow |
|
||||
| `git status` | Compact stat format, grouped by state |
|
||||
| `git diff` | Reduced context, headers stripped |
|
||||
| `git log` | Hash, author and subject only |
|
||||
@@ -421,7 +422,7 @@ RTK supports 17 AI coding tools. Each integration rewrites shell commands to `rt
|
||||
| **GitHub Copilot CLI** | `rtk init -g --copilot` | PreToolUse deny-with-suggestion (CLI limitation) |
|
||||
| **Cursor** | `rtk init -g --agent cursor` | preToolUse hook (hooks.json) |
|
||||
| **Gemini CLI** | `rtk init -g --gemini` | BeforeTool hook |
|
||||
| **Codex** | `rtk init -g --codex` | AGENTS.md + RTK.md instructions |
|
||||
| **Codex** | `rtk init -g --codex` | PreToolUse hook (`updatedInput`) + AGENTS.md |
|
||||
| **Windsurf** | `rtk init -g --agent windsurf` | .windsurfrules (project-scoped) |
|
||||
| **Cline / Roo Code** | `rtk init --agent cline` | .clinerules (project-scoped) |
|
||||
| **OpenCode** | `rtk init -g --opencode` | Plugin TS (tool.execute.before) |
|
||||
|
||||
+2
-2
@@ -62,8 +62,8 @@ This data directly drives our roadmap. For example, if telemetry shows that 40%
|
||||
|-------|---------|---------|
|
||||
| `passthrough_top` | `["git:15", "npm:8"]` | Top 5 commands with 0% savings — these need filters |
|
||||
| `parse_failures_24h` | `3` | Filter fragility — high count means filters are breaking |
|
||||
| `low_savings_commands` | `["rtk docker ps:25%"]` | Commands averaging <30% savings — filters to improve |
|
||||
| `avg_savings_per_command` | `68.5` | Unweighted average (vs global which is volume-biased) |
|
||||
| `low_savings_commands` | `["rtk docker ps:25%"]` | Commands with weighted savings rate <30%, net-negative ones included — filters to improve. Rate is `SUM(saved)/SUM(input)` over every call of the command, the same figure as the `rtk gain` By Command table, so high-volume calls are not diluted by passthrough calls. Exact 0% is left to `passthrough_top`. |
|
||||
| `avg_savings_per_command` | `68.5` | Unweighted average across distinct command names (each filter counts once regardless of invocation volume). Each command's individual rate is weighted by volume before the outer average; commands that never had any input are skipped. |
|
||||
| `recall_mode` | `sqlite` | Which recovery mode is active (`sqlite`/`tee`/`disabled`) |
|
||||
| `recall_stats` | `[{"filter":"grep","mode":"sqlite","elisions":142,"recalls":9}]` | Per-filter counters: how often elided output is retrieved — calibrates filter caps. Filter names come from a fixed allowlist of rtk filter families; anything else is folded into `other`. No hashes, no paths, no command arguments, no output content. |
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@
|
||||
|
||||
### Hook Architecture (v0.9.5+)
|
||||
|
||||
> For the hook interception diagram and agent-specific JSON formats, see [TECHNICAL.md](TECHNICAL.md#32-hook-interception-command-rewriting) and [hooks/README.md](hooks/README.md).
|
||||
> For the hook interception diagram and agent-specific JSON formats, see [TECHNICAL.md](TECHNICAL.md#32-hook-interception-command-rewriting) and [hooks/README.md](../../src/hooks/README.md).
|
||||
|
||||
Two hook strategies:
|
||||
|
||||
@@ -181,7 +181,7 @@ Savings by ecosystem:
|
||||
### Module Breakdown
|
||||
|
||||
- **Command Modules**: `src/cmds/` — organized by ecosystem (git, rust, js, python, go, dotnet, cloud, system, ruby). Each ecosystem README lists its files.
|
||||
- **Core Infrastructure**: `src/core/` — utils, filter, tracking, retriever (recall store), tee, tee_file, config, toml_filter, display_helpers, telemetry
|
||||
- **Core Infrastructure**: `src/core/` — utils, filter, tracking, retriever (recall store), tee, tee_file, config, toml_filter, display_helpers, telemetry, arg_tokenizer
|
||||
- **Hook System**: `src/hooks/` — init, rewrite, permissions, hook_cmd, hook_check, hook_audit, verify, trust, integrity
|
||||
- **Analytics**: `src/analytics/` — gain, cc_economics, ccusage, session_cmd
|
||||
|
||||
@@ -571,7 +571,13 @@ When adding Python/Go module support:
|
||||
|
||||
### Utilities Layer
|
||||
|
||||
> For the full utilities API (`truncate`, `strip_ansi`, `execute_command`, `ruby_exec`, etc.), see [src/core/README.md](src/core/README.md). Used by most command modules.
|
||||
> For the full utilities API (`truncate`, `strip_ansi`, `execute_command`, `ruby_exec`, etc.), see [src/core/README.md](../../src/core/README.md). Used by most command modules.
|
||||
|
||||
### Argument Handling
|
||||
|
||||
Every command that inspects its own arguments — which flags were passed, which tokens are paths, what to inject or strip — classifies them with `src/core/arg_tokenizer.rs`. String scans (`starts_with('-')`, `arg == "--flag"`) miss a flag's own value, attached values, short clusters and everything past `--`, which is where this module's whole bug class lives.
|
||||
|
||||
> For the predicate contract and the four rules that come with it (one grammar per subcommand, scope the lookup to the region the tool parses, inject before the boundary, detect and act with one rule), see [src/core/README.md](../../src/core/README.md#argument-tokenizer-arg_tokenizerrs).
|
||||
|
||||
### Package Manager Detection Pattern
|
||||
|
||||
@@ -872,7 +878,7 @@ Modules with Exit Code Preservation:
|
||||
|
||||
### Configuration
|
||||
|
||||
> For config file format, recall/tee settings, tracking database path, and TOML filter tiers, see [src/core/README.md](src/core/README.md).
|
||||
> For config file format, recall/tee settings, tracking database path, and TOML filter tiers, see [src/core/README.md](../../src/core/README.md).
|
||||
|
||||
Two tiers: **User settings** (`~/.config/rtk/config.toml`) and **LLM integration** (CLAUDE.md via `rtk init`).
|
||||
|
||||
@@ -997,7 +1003,7 @@ Overhead Sources:
|
||||
|
||||
## Extensibility Guide
|
||||
|
||||
> For the complete step-by-step process to add a new command (module file, enum variant, routing, tests, documentation), see [src/cmds/README.md — Adding a New Command Filter](src/cmds/README.md#adding-a-new-command-filter).
|
||||
> For the complete step-by-step process to add a new command (module file, enum variant, routing, tests, documentation), see [src/cmds/README.md — Adding a New Command Filter](../../src/cmds/README.md#adding-a-new-command-filter).
|
||||
|
||||
---
|
||||
|
||||
@@ -1035,7 +1041,7 @@ Overhead Sources:
|
||||
## Resources
|
||||
|
||||
- **[TECHNICAL.md](TECHNICAL.md)**: Guided tour of end-to-end flow
|
||||
- **[CONTRIBUTING.md](CONTRIBUTING.md)**: Design philosophy, contribution workflow, checklist
|
||||
- **[CONTRIBUTING.md](../../CONTRIBUTING.md)**: Design philosophy, contribution workflow, checklist
|
||||
- **CLAUDE.md**: Quick reference for AI agents (dev commands, build verification)
|
||||
- **README.md**: User guide, installation, examples
|
||||
- **Cargo.toml**: Dependencies, build profiles, package metadata
|
||||
|
||||
@@ -166,7 +166,7 @@ rewrite_segment(seg, excluded) [src/discover/registry.rs]
|
||||
| Step 4 — Already RTK → return as-is
|
||||
|
|
||||
| Step 5 — Special cases (short-circuit before classification)
|
||||
| head -N / --lines=N → rewrite_line_range() → "rtk read file --max-lines N"
|
||||
| head -N / -n N / --lines[= ]N / bare → rewrite_line_range() → "rtk read file --head-lines N"
|
||||
| tail -N / -n N / --lines N → rewrite_line_range() → "rtk read file --tail-lines N"
|
||||
| head/tail with unsupported flag (-c, -f) → None (skip rewrite)
|
||||
| cat with incompatible flag (-A, -v, -e) → None (skip rewrite)
|
||||
@@ -320,7 +320,7 @@ Start here, then drill down into each README for file-level details.
|
||||
| [`cursor/`](../hooks/cursor/README.md) | Cursor IDE | Shell hook, empty JSON response requirement |
|
||||
| [`cline/`](../hooks/cline/README.md) | Cline / Roo Code | Rules file (prompt-level, no programmatic hook) |
|
||||
| [`windsurf/`](../hooks/windsurf/README.md) | Windsurf / Cascade | Rules file (workspace-scoped) |
|
||||
| [`codex/`](../hooks/codex/README.md) | OpenAI Codex CLI | Awareness document, AGENTS.md integration |
|
||||
| [`codex/`](../hooks/codex/README.md) | OpenAI Codex CLI | Native `PreToolUse` processor, hooks.json registration, AGENTS.md awareness |
|
||||
| [`opencode/`](../hooks/opencode/README.md) | OpenCode | TypeScript plugin, zx library, in-place mutation |
|
||||
|
||||
---
|
||||
@@ -338,7 +338,7 @@ RTK supports the following LLM agents through hook integrations:
|
||||
| Gemini CLI | Rust binary | `rtk hook gemini` reads JSON | Yes (`hookSpecificOutput`) |
|
||||
| Cline/Roo Code | Rules file | Prompt-level guidance | N/A (prompt) |
|
||||
| Windsurf | Rules file | Prompt-level guidance | N/A (prompt) |
|
||||
| Codex CLI | Awareness doc | AGENTS.md integration | N/A (prompt) |
|
||||
| Codex CLI | Rust binary | `rtk hook codex` reads JSON | Yes (`updatedInput`) |
|
||||
| OpenCode | TS plugin | `tool.execute.before` event | Yes (in-place mutation) |
|
||||
|
||||
> **Details**: [`hooks/README.md`](../hooks/README.md) has the full JSON schemas for each agent. [`src/hooks/README.md`](../src/hooks/README.md) covers installation, integrity verification, and the rewrite command.
|
||||
|
||||
@@ -41,7 +41,7 @@ Agent runs "cargo test"
|
||||
| Factory Droid | Shell hook (`PreToolUse`, matcher `Execute`) | Yes |
|
||||
| Cline / Roo Code | Rules file (prompt-level) | N/A |
|
||||
| Windsurf | Rules file (prompt-level) | N/A |
|
||||
| Codex CLI | AGENTS.md instructions | N/A |
|
||||
| Codex CLI | Rust binary (`PreToolUse`) | Yes |
|
||||
| Kilo Code | Rules file (prompt-level) | N/A |
|
||||
| Google Antigravity | Rules file (prompt-level) | N/A |
|
||||
| Mistral Vibe | Rust binary (`pre_tool`) | Yes |
|
||||
@@ -210,10 +210,14 @@ rtk init --global --agent windsurf # creates .windsurfrules in current projec
|
||||
### Codex CLI
|
||||
|
||||
```bash
|
||||
rtk init --codex # project-scoped (AGENTS.md)
|
||||
rtk init --global --codex # user-global (~/.codex/AGENTS.md)
|
||||
rtk init --codex # project-scoped (.codex/hooks.json + AGENTS.md)
|
||||
rtk init --global --codex # user-global ($CODEX_HOME or ~/.codex/)
|
||||
rtk init --codex --uninstall # remove project-scoped integration
|
||||
rtk init --global --codex --uninstall # remove user-global integration
|
||||
```
|
||||
|
||||
Restart Codex after installation. Project-scoped hooks must be trusted when Codex prompts. The native `rtk hook codex` processor rewrites supported `Bash` commands through `PreToolUse.updatedInput`; Codex then applies its normal approval and sandbox checks to the rewritten command.
|
||||
|
||||
### Kilo Code
|
||||
|
||||
```bash
|
||||
@@ -261,7 +265,7 @@ Strips only RTK's `[[hooks]]` block and the `~/.vibe/prompts/rtk.md` file. Any o
|
||||
| **Plugin** | TypeScript, JavaScript, or Python in agent's plugin system | Transparent, in-place mutation when the agent allows it |
|
||||
| **Rules file** | Prompt-level instructions | Guidance only — agent is told to prefer `rtk <cmd>` |
|
||||
|
||||
Rules file integrations (Cline, Windsurf, Codex, Kilo Code, Antigravity) rely on the model following instructions. Full hook integrations (Claude Code, Cursor, Gemini) are guaranteed — the command is rewritten before the agent sees it. Plugin integrations (OpenCode, Pi) use in-place mutation via the agent's TypeScript extension API.
|
||||
Rules file integrations (Cline, Windsurf, Kilo Code, Antigravity) rely on the model following instructions. Full hook integrations (Claude Code, Cursor, Gemini, Codex) rewrite the command before execution. Plugin integrations (OpenCode, Pi) use in-place mutation via the agent's TypeScript extension API.
|
||||
|
||||
## Windows support
|
||||
|
||||
|
||||
@@ -67,8 +67,8 @@ This data directly drives our roadmap. For example, if telemetry shows that 40%
|
||||
|-------|---------|---------|
|
||||
| `passthrough_top` | `["git:15", "npm:8"]` | Top 5 commands with 0% bash output reduction — these need filters |
|
||||
| `parse_failures_24h` | `3` | Filter fragility — high count means filters are breaking |
|
||||
| `low_savings_commands` | `["rtk <cmd>:25%"]` | Commands averaging <30% bash output reduction — filters to improve. The example is a placeholder, not a measured value |
|
||||
| `avg_savings_per_command` | `68.5` | Unweighted average (vs global which is volume-biased) |
|
||||
| `low_savings_commands` | `["rtk <cmd>:25%"]` | Commands with a weighted bash output reduction <30%, net-negative ones included — filters to improve. The rate is `SUM(saved)/SUM(input)` over every call of the command, the same figure as the `rtk gain` By Command table, so high-volume calls are not diluted by passthrough calls. Exact 0% is left to `passthrough_top`. The example is a placeholder, not a measured value |
|
||||
| `avg_savings_per_command` | `68.5` | Unweighted average across distinct command names (each filter counts once regardless of invocation volume); each command's own rate is weighted by volume before the outer average, and commands that never had any input are skipped |
|
||||
|
||||
### Ecosystem distribution
|
||||
|
||||
|
||||
@@ -116,6 +116,7 @@ Every percentage below measures **bash output bytes removed** — the only thing
|
||||
| `ls` | 80% | Tree format with file counts |
|
||||
| `find` | 75% | Tree format |
|
||||
| `grep` | 70% | Truncated lines, grouped by file |
|
||||
| `ast-grep` | 85% | Grouped by file, capped overflow; `--json` passes through |
|
||||
| `diff` | 65% | Context reduced |
|
||||
| `wc` | 60% | Compact counts |
|
||||
| `cat` / `head` / `tail <file>` | 60-80% | Smart file reading via `rtk read` |
|
||||
|
||||
+20
-2
@@ -130,7 +130,9 @@ rtk read - [options] # Lecture depuis stdin
|
||||
| Option | Court | Defaut | Description |
|
||||
|--------|-------|--------|-------------|
|
||||
| `--level` | `-l` | `minimal` | Niveau de filtrage : `none`, `minimal`, `aggressive` |
|
||||
| `--max-lines` | `-m` | illimite | Nombre maximum de lignes |
|
||||
| `--max-lines` | `-m` | illimite | Apercu structurel plafonne a N lignes (signatures et imports, pas les N premieres) |
|
||||
| `--head-lines` | | illimite | Garde seulement les N premieres lignes, a l'octet pres |
|
||||
| `--tail-lines` | | illimite | Garde seulement les N dernieres lignes, a l'octet pres |
|
||||
| `--line-numbers` | `-n` | non | Afficher les numeros de ligne |
|
||||
|
||||
**Niveaux de filtrage :**
|
||||
@@ -238,6 +240,21 @@ src/ls.rs:25:fn run_tree(...) src/ls.rs
|
||||
|
||||
---
|
||||
|
||||
### `rtk ast-grep` -- Recherche structurelle (AST)
|
||||
|
||||
**Objectif :** Remplace `ast-grep` avec une sortie groupee par fichier, plafonnee.
|
||||
|
||||
**Syntaxe :**
|
||||
```bash
|
||||
rtk ast-grep run -p '<pattern>' [chemin] [options]
|
||||
```
|
||||
|
||||
Regroupe les correspondances par fichier, plafonnees a 5 par fichier et 50 au total ; le surplus est remplace par une note de comptage ("N more match line(s) in X" / "N more file(s) not shown"). ast-grep imprime une ligne par ligne source d'une correspondance, et une correspondance structurelle s'etend sur plusieurs lignes : le decompte porte donc sur les lignes, pas sur les correspondances. Les sorties que rtk ne sait pas decouper (`ast-grep scan`, `--heading`) passent telles quelles. Sur une recherche reelle dans ce depot, ~85% de reduction.
|
||||
|
||||
`--json` n'est pas filtre -- une demande explicite de sortie structuree passe telle quelle, sans compression.
|
||||
|
||||
---
|
||||
|
||||
### `rtk diff` -- Diff condense
|
||||
|
||||
**Objectif :** Diff ultra-condense entre deux fichiers (uniquement les lignes modifiees).
|
||||
@@ -1276,6 +1293,7 @@ rtk verify
|
||||
| `cargo test/build/clippy/check` | `rtk cargo ...` |
|
||||
| `cat/head/tail <fichier>` | `rtk read <fichier>` |
|
||||
| `rg/grep <pattern>` | `rtk grep <pattern>` |
|
||||
| `ast-grep run -p <pattern>` | `rtk ast-grep run -p <pattern>` |
|
||||
| `ls` | `rtk ls` |
|
||||
| `tree` | `rtk tree` |
|
||||
| `wc` | `rtk wc` |
|
||||
@@ -1448,7 +1466,7 @@ Octets de sortie bash supprimes (voir [A propos de la reduction de sortie bash](
|
||||
|
||||
| Categorie | Commandes | Reduction sortie bash |
|
||||
|-----------|-----------|-------------------|
|
||||
| **Fichiers** | ls, tree, read, find, grep, diff | 60-80% |
|
||||
| **Fichiers** | ls, tree, read, find, grep, ast-grep, diff | 60-85% |
|
||||
| **Git** | status, log, diff, show, add, commit, push, pull | 75-92% |
|
||||
| **GitHub** | pr, issue, run, api | 79-87% |
|
||||
| **Tests** | cargo test, vitest, playwright, pytest, go test | 90-99% |
|
||||
|
||||
+35
-7
@@ -2,7 +2,7 @@
|
||||
|
||||
## Scope
|
||||
|
||||
**Deployed hook artifacts** — the actual files installed on user machines by `rtk init`. These are shell scripts, TypeScript plugins, and rules files that run outside the Rust binary. They are **thin delegates**: parse agent-specific JSON, call `rtk rewrite` as a subprocess, format agent-specific response. Zero filtering logic lives here.
|
||||
**Deployed hook artifacts** — the files and agent-specific configuration installed on user machines by `rtk init`. External scripts and plugins are thin delegates to `rtk rewrite`; native processors such as Codex call the same Rust rewrite registry directly. Zero filtering logic is duplicated in this directory.
|
||||
|
||||
Owns: per-agent hook scripts and configuration files for 11 supported agents (Claude Code, Copilot, Cursor, Cline, Windsurf, Codex, OpenCode, Hermes, Pi, Oh My Pi, Mistral Vibe).
|
||||
|
||||
@@ -27,14 +27,14 @@ LLM agent integrations that intercept CLI commands and route them through RTK fo
|
||||
Agent runs command (e.g., "cargo test --nocapture")
|
||||
-> Hook intercepts (PreToolUse / plugin event)
|
||||
-> Reads JSON input, extracts command string
|
||||
-> Calls `rtk rewrite "cargo test --nocapture"`
|
||||
-> Uses the shared RTK rewrite registry
|
||||
-> Registry matches pattern, returns "rtk cargo test --nocapture"
|
||||
-> Hook sends response in agent-specific JSON format
|
||||
-> Agent executes "rtk cargo test --nocapture" instead
|
||||
-> Filtered output reaches LLM (up to 90% fewer bash output bytes)
|
||||
```
|
||||
|
||||
All rewrite logic lives in the Rust binary (`src/discover/registry.rs`). Hook scripts are **thin delegates** that handle agent-specific JSON formats and call `rtk rewrite` for the actual decision. This ensures a single source of truth for all 70+ rewrite patterns.
|
||||
All rewrite logic lives in the Rust binary (`src/discover/registry.rs`). External hook scripts call `rtk rewrite`; native Rust hook processors call the registry directly. This keeps one source of truth for all 70+ rewrite patterns.
|
||||
|
||||
## Directory Structure
|
||||
|
||||
@@ -45,7 +45,7 @@ Each agent subdirectory has its own README with hook-specific details:
|
||||
- **[`cursor/`](cursor/README.md)** — Shell hook, Cursor JSON format, empty `{}` response requirement
|
||||
- **[`cline/`](cline/README.md)** — Rules file (prompt-level), `.clinerules` project-local installation
|
||||
- **[`windsurf/`](windsurf/README.md)** — Rules file (prompt-level), `.windsurfrules` workspace-scoped
|
||||
- **[`codex/`](codex/README.md)** — Awareness document, `AGENTS.md` integration, `$CODEX_HOME` or `~/.codex/` location
|
||||
- **[`codex/`](codex/README.md)** — Rust binary hook (`rtk hook codex`), `PreToolUse.updatedInput`, `.codex/hooks.json` / `$CODEX_HOME/hooks.json`, plus `AGENTS.md` awareness
|
||||
- **[`opencode/`](opencode/README.md)** — TypeScript plugin, `zx` library, `tool.execute.before` event, in-place mutation
|
||||
- **[`pi/`](pi/README.md)** — TypeScript extension, `tool_call` event, local `isBashToolCallEvent` guard, in-place mutation, `~/.pi/agent/extensions/`; **shared with Oh My Pi (OMP)** — OMP installs the same file at `.omp/extensions/` via its `legacy-pi-compat` layer
|
||||
- **[`hermes/`](hermes/README.md)** — Python plugin, `pre_tool_call` hook, in-place terminal command mutation
|
||||
@@ -62,7 +62,7 @@ Each agent subdirectory has its own README with hook-specific details:
|
||||
| Gemini CLI | Rust binary (`rtk hook gemini`) | Transparent rewrite | Yes (`hookSpecificOutput`) |
|
||||
| Cline / Roo Code | Custom instructions (rules file) | Prompt-level guidance | N/A |
|
||||
| Windsurf | Custom instructions (rules file) | Prompt-level guidance | N/A |
|
||||
| Codex CLI | AGENTS.md / instructions | Prompt-level guidance | N/A |
|
||||
| Codex CLI | Rust binary (`rtk hook codex`) | Transparent rewrite | Yes (`updatedInput`) |
|
||||
| OpenCode | TypeScript plugin (`tool.execute.before`) | In-place mutation | Yes |
|
||||
| Pi | TypeScript extension (`tool_call` event) | In-place mutation | Yes |
|
||||
| Oh My Pi (OMP) | TypeScript extension (`tool_call` event, shared with Pi) | In-place mutation | Yes |
|
||||
@@ -110,6 +110,34 @@ Each agent subdirectory has its own README with hook-specific details:
|
||||
|
||||
Returns `{}` when no rewrite (Cursor requires JSON for all paths).
|
||||
|
||||
### Codex CLI (Rust Binary)
|
||||
|
||||
**Input** (stdin):
|
||||
|
||||
```json
|
||||
{
|
||||
"hook_event_name": "PreToolUse",
|
||||
"tool_name": "Bash",
|
||||
"permission_mode": "default",
|
||||
"tool_input": { "command": "git status" }
|
||||
}
|
||||
```
|
||||
|
||||
**Output** (stdout, when rewritten):
|
||||
|
||||
```json
|
||||
{
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "PreToolUse",
|
||||
"permissionDecision": "allow",
|
||||
"permissionDecisionReason": "RTK auto-rewrite",
|
||||
"updatedInput": { "command": "rtk git status" }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The `allow` value is required by Codex to accept `updatedInput`; Codex still runs its native approval and sandbox checks after applying the replacement. Those checks classify the rewritten command, and Codex does not currently unwrap the `rtk` binary for its safe/dangerous-command heuristics. Missing or unknown permission modes and other no-rewrite cases produce no stdout.
|
||||
|
||||
### Copilot CLI (Rust Binary)
|
||||
|
||||
**Input** (stdin, camelCase, `toolArgs` is JSON-stringified):
|
||||
@@ -277,9 +305,9 @@ New integrations must follow the [Exit Code Contract](#exit-code-contract) and [
|
||||
|
||||
| Tier | Mechanism | Maintenance | Examples |
|
||||
|------|-----------|-------------|----------|
|
||||
| **Full hook** | Shell script or Rust binary, intercepts commands via agent's hook API | High — must track agent API changes | Claude Code, Cursor, Copilot, Gemini |
|
||||
| **Full hook** | Shell script or Rust binary, intercepts commands via agent's hook API | High — must track agent API changes | Claude Code, Cursor, Copilot, Gemini, Codex |
|
||||
| **Plugin** | TypeScript/JS/Python plugin in agent's plugin system | Medium — agent manages loading | OpenCode, Hermes, Pi, Oh My Pi |
|
||||
| **Rules file** | Prompt-level instructions the agent reads | Low — no code to break | Cline, Windsurf, Codex |
|
||||
| **Rules file** | Prompt-level instructions the agent reads | Low — no code to break | Cline, Windsurf |
|
||||
|
||||
### Eligibility
|
||||
|
||||
|
||||
+34
-3
@@ -4,6 +4,37 @@
|
||||
|
||||
## Specifics
|
||||
|
||||
- Prompt-level guidance via awareness document -- no programmatic hook
|
||||
- `../rtk-awareness-full.md` is written to `RTK.md` and referenced from `AGENTS.md` via `@RTK.md`. No hook, so the `full` level is always used regardless of `awareness.level`
|
||||
- Installed to `$CODEX_HOME` when set, otherwise `~/.codex/`, by `rtk init --codex`
|
||||
- Native Rust `PreToolUse` processor: `rtk hook codex`
|
||||
- Transparently rewrites `tool_input.command` with Codex's `updatedInput` response
|
||||
- Registers a `Bash` matcher in `.codex/hooks.json` (project) or `$CODEX_HOME/hooks.json` (global)
|
||||
- Writes the shared awareness document selected by `awareness.level` to `RTK.md`, referenced from `AGENTS.md`
|
||||
- Installed by `rtk init --codex` (project) or `rtk init -g --codex` (global)
|
||||
- Uninstalled by adding `--uninstall` to the corresponding project or global command
|
||||
|
||||
Codex requires `permissionDecision: "allow"` in the hook response for `updatedInput` to take effect. Codex applies the replacement before its normal command approval and sandbox checks, so those native checks still run on the rewritten command. Codex's command safety classifier does not currently unwrap the `rtk` binary, so classification is based on the rewritten command. This can add prompts for known-safe commands or obscure signals for wrapped mutating commands such as `git push`.
|
||||
|
||||
RTK rewrites the documented Codex permission modes. Missing or unknown permission modes, no match, malformed JSON, unsupported commands, heredocs, substitutions, and file redirections fail open: the hook exits successfully without stdout and Codex executes the original command.
|
||||
|
||||
The Codex handler uses RTK's shared hook decision pipeline through `Host::Codex`.
|
||||
RTK does not parse Codex execution rules or reuse another agent's permission
|
||||
files: Codex's native execution layer remains responsible for those rules.
|
||||
An internal `AskRewrite` still emits the required protocol-level `allow` with
|
||||
`updatedInput`; it is not recorded internally as an explicit permission grant.
|
||||
This preserves transparent rewriting but does not remove the classifier
|
||||
limitation described above.
|
||||
|
||||
## History in workspace-write sandboxes
|
||||
|
||||
Command rewriting can work even when the sandbox prevents RTK from writing its
|
||||
SQLite history database. If recording reports `SQLITE_CANTOPEN`, run
|
||||
`rtk init --codex` outside the sandbox to see an optional Codex configuration
|
||||
snippet using the actual database parent directory. The path follows
|
||||
`RTK_DB_PATH`, then `tracking.database_path`, then the platform default.
|
||||
|
||||
To opt in, merge the printed `sandbox_workspace_write.writable_roots` entry into
|
||||
your Codex `config.toml`, preserving existing entries. SQLite needs directory
|
||||
access for journal/WAL files as well as the database itself. RTK only prints the
|
||||
snippet; it does not change sandbox settings. Review custom paths before granting
|
||||
access, and prefer a dedicated RTK data directory.
|
||||
|
||||
See the [Codex configuration reference](https://developers.openai.com/codex/config-reference/).
|
||||
@@ -220,7 +220,7 @@ pub fn run(
|
||||
println!("{}", "─".repeat(table_width));
|
||||
println!(
|
||||
"{:>3} {:<cmd_width$} {:>count_width$} {:>saved_width$} {:>6} {:>time_width$} {:<impact_width$}",
|
||||
"#", "Command", "Count", "Saved", "Avg%", "Time", "Impact",
|
||||
"#", "Command", "Count", "Saved", "Total%", "Time", "Impact",
|
||||
cmd_width = cmd_width, count_width = count_width,
|
||||
saved_width = saved_width, time_width = time_width,
|
||||
impact_width = impact_width
|
||||
|
||||
@@ -294,6 +294,7 @@ Adding a new filter or command requires changes in multiple places. For TOML-vs-
|
||||
- Add `.tee("label")` when the filter parses structured output (enables raw output recovery on failure)
|
||||
- **Exit codes**: handled automatically by `run_filtered()` — just return its result
|
||||
- **Truncation**: if the filter caps any list at N items, emit `force_tee_tail_hint` (flat lists) or `force_tee_hint` (multi-line blocks) so the agent can recover hidden items — see [Internal Truncation Recovery](#internal-truncation-recovery). Use a named constant for the cap; derive the offset from it (`MAX_XXX + 1`)
|
||||
- **Arguments**: if the filter inspects its args at all — which flags were passed, which are paths, what to inject or strip — classify them with [`arg_tokenizer`](../core/README.md#argument-tokenizer-arg_tokenizerrs), never a string scan. Write the `takes_value` predicate from the tool's own `--help` and check it against the real binary
|
||||
2. **Register module**:
|
||||
- Ecosystem `mod.rs` files use `automod::dir!()` — any `.rs` file in the directory becomes a public module automatically. No manual `pub mod` needed, but be aware: WIP or helper files will also be exposed. Only commit command-ready modules.
|
||||
- Add variant to `Commands` enum in `main.rs` with `#[arg(trailing_var_arg = true, allow_hyphen_values = true)]`
|
||||
|
||||
+774
-208
File diff suppressed because it is too large.
Load diff
@@ -5,6 +5,7 @@
|
||||
## Specifics
|
||||
|
||||
- **git.rs** uses `trailing_var_arg = true` + `allow_hyphen_values = true` so native git flags (`--oneline`, `--cached`, etc.) pass through correctly
|
||||
- Flag grammar (which flags take a value, what `-u`/`-p` mean) is per-subcommand, not shared wholesale between `log`/`diff`/`show`/`stash show` — see [`src/core/README.md`](../../core/README.md#argument-tokenizer-arg_tokenizerrs)
|
||||
- Default `git status` uses `--porcelain -b` so the compact output never exceeds raw `git status` (an untracked directory collapses to a single line, matching git's default); branch/short-only flags reuse the compact path, other explicit args still pass through unchanged
|
||||
- Global git options (`-C`, `--git-dir`, `--work-tree`, `--no-pager`) are prepended before the subcommand
|
||||
- Exit code propagation is critical for CI/CD pipelines
|
||||
|
||||
+141
-16
@@ -462,29 +462,54 @@ fn pr_checks(args: &[String], _verbose: u8, _ultra_compact: bool) -> Result<i32>
|
||||
"gh",
|
||||
&label,
|
||||
format_pr_checks,
|
||||
RunOptions::stdout_only()
|
||||
.early_exit_on_failure()
|
||||
.no_trailing_newline(),
|
||||
RunOptions::stdout_only().no_trailing_newline(),
|
||||
)
|
||||
}
|
||||
|
||||
fn format_pr_checks(stdout: &str) -> String {
|
||||
let mut passed = 0;
|
||||
let mut failed = 0;
|
||||
let mut pending = 0;
|
||||
let mut failed_checks = Vec::new();
|
||||
|
||||
// `gh pr checks --watch` appends each poll's table when stdout is not a TTY.
|
||||
// Keep the latest row for each check so status transitions are reflected
|
||||
// without inflating the summary.
|
||||
let mut checks: Vec<(String, String, PrCheckStatus, String)> = Vec::new();
|
||||
for line in stdout.lines() {
|
||||
if line.contains("[ok]") || line.contains("pass") {
|
||||
passed += 1;
|
||||
} else if line.contains("[x]") || line.contains("fail") {
|
||||
failed += 1;
|
||||
failed_checks.push(line.trim().to_string());
|
||||
} else if line.contains('*') || line.contains("pending") {
|
||||
pending += 1;
|
||||
let Some((name, link, status)) = parse_pr_check_line(line) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if let Some(check) = checks
|
||||
.iter_mut()
|
||||
.find(|check| check.0 == name && check.1 == link)
|
||||
{
|
||||
check.2 = status;
|
||||
check.3 = line.trim().to_string();
|
||||
} else {
|
||||
checks.push((
|
||||
name.to_string(),
|
||||
link.to_string(),
|
||||
status,
|
||||
line.trim().to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let passed = checks
|
||||
.iter()
|
||||
.filter(|check| check.2 == PrCheckStatus::Passed)
|
||||
.count();
|
||||
let failed = checks
|
||||
.iter()
|
||||
.filter(|check| check.2 == PrCheckStatus::Failed)
|
||||
.count();
|
||||
let pending = checks
|
||||
.iter()
|
||||
.filter(|check| check.2 == PrCheckStatus::Pending)
|
||||
.count();
|
||||
|
||||
let other = checks
|
||||
.iter()
|
||||
.filter(|check| check.2 == PrCheckStatus::Other)
|
||||
.count();
|
||||
|
||||
let mut out = String::new();
|
||||
out.push_str("CI Checks Summary:\n");
|
||||
out.push_str(&format!(" [ok] Passed: {}\n", passed));
|
||||
@@ -492,7 +517,14 @@ fn format_pr_checks(stdout: &str) -> String {
|
||||
if pending > 0 {
|
||||
out.push_str(&format!(" [pending] Pending: {}\n", pending));
|
||||
}
|
||||
if !failed_checks.is_empty() {
|
||||
if other > 0 {
|
||||
out.push_str(&format!(" [skip] Skipped/cancelled: {}\n", other));
|
||||
}
|
||||
let failed_checks = checks
|
||||
.iter()
|
||||
.filter(|check| check.2 == PrCheckStatus::Failed)
|
||||
.map(|check| check.3.as_str());
|
||||
if failed > 0 {
|
||||
out.push_str("\n Failed checks:\n");
|
||||
for check in failed_checks {
|
||||
out.push_str(&format!(" {}\n", check));
|
||||
@@ -501,6 +533,31 @@ fn format_pr_checks(stdout: &str) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum PrCheckStatus {
|
||||
Passed,
|
||||
Failed,
|
||||
Pending,
|
||||
Other,
|
||||
}
|
||||
|
||||
fn parse_pr_check_line(line: &str) -> Option<(&str, &str, PrCheckStatus)> {
|
||||
let mut fields = line.split('\t');
|
||||
let name = fields.next()?.trim();
|
||||
let status = match fields.next()?.trim() {
|
||||
"pass" => PrCheckStatus::Passed,
|
||||
"fail" => PrCheckStatus::Failed,
|
||||
"pending" | "*" => PrCheckStatus::Pending,
|
||||
// skipping, cancelled, and whatever a later gh adds. Counted rather than
|
||||
// dropped, so the totals add up to the checks gh listed and a cancelled
|
||||
// run cannot read as "nothing wrong".
|
||||
_ => PrCheckStatus::Other,
|
||||
};
|
||||
let link = fields.nth(1).unwrap_or("").trim();
|
||||
|
||||
(!name.is_empty()).then_some((name, link, status))
|
||||
}
|
||||
|
||||
fn pr_status(args: &[String], _verbose: u8, _ultra_compact: bool) -> Result<i32> {
|
||||
if should_passthrough_pr_status(args) {
|
||||
let mut passthrough_args = Vec::with_capacity(args.len() + 1);
|
||||
@@ -1121,6 +1178,74 @@ mod tests {
|
||||
assert!(extract_identifier_and_extra_args(&args).is_none());
|
||||
}
|
||||
|
||||
// --- format_pr_checks tests ---
|
||||
|
||||
#[test]
|
||||
fn test_format_pr_checks_counts_each_watch_snapshot_once() {
|
||||
let output = concat!(
|
||||
"Analyze (actions)\tpass\t42s\thttps://example.com/actions\n",
|
||||
"Analyze (rust)\tpass\t2m\thttps://example.com/rust\n",
|
||||
"Analyze (actions)\tpass\t42s\thttps://example.com/actions\n",
|
||||
"Analyze (rust)\tpass\t2m\thttps://example.com/rust\n",
|
||||
);
|
||||
|
||||
let result = format_pr_checks(output);
|
||||
|
||||
assert!(result.contains("Passed: 2"));
|
||||
assert!(!result.contains("Passed: 4"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_format_pr_checks_uses_final_status_for_each_check() {
|
||||
let output = concat!(
|
||||
"Lint\tpending\t0\thttps://example.com/lint\n",
|
||||
"Unit tests\tfail\t1m\thttps://example.com/unit\n",
|
||||
"Lint\tpass\t30s\thttps://example.com/lint\n",
|
||||
"Unit tests\tfail\t1m\thttps://example.com/unit\n",
|
||||
);
|
||||
|
||||
let result = format_pr_checks(output);
|
||||
|
||||
assert!(result.contains("Passed: 1"));
|
||||
assert!(result.contains("Failed: 1"));
|
||||
assert!(!result.contains("Pending:"));
|
||||
assert!(result.contains("Unit tests\tfail"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_format_pr_checks_keeps_same_name_checks_with_different_links() {
|
||||
let output = concat!(
|
||||
"build\tpass\t1m\thttps://example.com/workflow-a\n",
|
||||
"build\tfail\t1m\thttps://example.com/workflow-b\n",
|
||||
);
|
||||
|
||||
let result = format_pr_checks(output);
|
||||
|
||||
assert!(result.contains("Passed: 1"));
|
||||
assert!(result.contains("Failed: 1"));
|
||||
}
|
||||
|
||||
/// Rows exactly as `gh` prints them when stdout is a pipe: five tab-separated
|
||||
/// fields, the fifth (the description) usually empty. Captured from
|
||||
/// `gh pr checks --watch` against a run that was still going, so the pending
|
||||
/// rows here are the shape a real transition arrives in.
|
||||
#[test]
|
||||
fn test_format_pr_checks_handles_real_gh_row_shape() {
|
||||
let output = concat!(
|
||||
"test (macos-latest)\tpending\t0\thttps://example.com/job/1\t\n",
|
||||
"clippy\tpass\t28s\thttps://example.com/job/2\t\n",
|
||||
"license/cla\tpass\t0\thttps://cla.example.com/pr/1\tContributor License Agreement is signed.\n",
|
||||
"test (macos-latest)\tpass\t3m1s\thttps://example.com/job/1\t\n",
|
||||
"clippy\tpass\t28s\thttps://example.com/job/2\t\n",
|
||||
"license/cla\tpass\t0\thttps://cla.example.com/pr/1\tContributor License Agreement is signed.\n",
|
||||
);
|
||||
|
||||
let result = format_pr_checks(output);
|
||||
|
||||
assert!(result.contains("Passed: 3"), "got:\n{result}");
|
||||
assert!(!result.contains("Pending:"), "got:\n{result}");
|
||||
}
|
||||
|
||||
// --- parse_optional_identifier tests ---
|
||||
|
||||
#[test]
|
||||
|
||||
+1525
-441
File diff suppressed because it is too large.
Load diff
+270
-71
@@ -1,5 +1,7 @@
|
||||
//! Filters golangci-lint output, grouping issues by rule.
|
||||
|
||||
use crate::core::arg_tokenizer::{self, Dialect, TokenKind, ValueSpec};
|
||||
use crate::core::args_utils;
|
||||
use crate::core::config;
|
||||
use crate::core::runner;
|
||||
use crate::core::stream::exec_capture;
|
||||
@@ -10,28 +12,94 @@ use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::OsString;
|
||||
|
||||
const GOLANGCI_SUBCOMMANDS: &[&str] = &[
|
||||
"cache",
|
||||
"completion",
|
||||
"config",
|
||||
"custom",
|
||||
"fmt",
|
||||
"formatters",
|
||||
"help",
|
||||
"linters",
|
||||
"migrate",
|
||||
"run",
|
||||
"version",
|
||||
];
|
||||
fn is_subcommand(name: &str) -> bool {
|
||||
matches!(
|
||||
name,
|
||||
"cache"
|
||||
| "completion"
|
||||
| "config"
|
||||
| "custom"
|
||||
| "fmt"
|
||||
| "formatters"
|
||||
| "help"
|
||||
| "linters"
|
||||
| "migrate"
|
||||
| "run"
|
||||
| "version"
|
||||
)
|
||||
}
|
||||
|
||||
const GLOBAL_FLAGS_WITH_VALUE: &[&str] = &[
|
||||
"-c",
|
||||
"--color",
|
||||
"--config",
|
||||
"--cpu-profile-path",
|
||||
"--mem-profile-path",
|
||||
"--trace-path",
|
||||
];
|
||||
/// golangci-lint's *global* grammar: the value-taking flags accepted before a subcommand. `-c`
|
||||
/// is `--config`'s shorthand; this list is wider than `--help`'s "Global Flags" section, which
|
||||
/// omits several of these.
|
||||
///
|
||||
/// Solo-only, like every short flag here: Cobra does not let a value-taking shorthand sit
|
||||
/// inside a cluster (`golangci-lint -vc foo.yml run` is "unknown shorthand flag: 'c' in -c",
|
||||
/// verified against 2.13.1). Reading one as value-taking there swallowed the next token --
|
||||
/// `-Egosec run` lost `run`, and with it the subcommand detection this list exists for.
|
||||
fn global_takes_value(kind: TokenKind, name: &str) -> Option<ValueSpec> {
|
||||
match kind {
|
||||
TokenKind::Long => matches!(
|
||||
name,
|
||||
"color" | "config" | "cpu-profile-path" | "mem-profile-path" | "trace-path"
|
||||
)
|
||||
.then(ValueSpec::value),
|
||||
TokenKind::Short => (name == "c").then(ValueSpec::solo_only),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `run` subcommand's grammar -- a wider list than [`global_takes_value`], which is scoped
|
||||
/// to the flags valid before a subcommand. Missing an entry here risks a value like
|
||||
/// `--path-prefix --out-format` tokenizing as its own flag and being misdetected by
|
||||
/// [`has_output_flag`].
|
||||
fn run_takes_value(kind: TokenKind, name: &str) -> Option<ValueSpec> {
|
||||
// The one exception to one-grammar-per-command (`src/core/README.md`), earned by a strict
|
||||
// subset: every flag valid before `run` stays valid after it. Grammars that merely
|
||||
// intersect get a table each instead.
|
||||
if let Some(spec) = global_takes_value(kind, name) {
|
||||
return Some(spec);
|
||||
}
|
||||
if OUTPUT_PATH_FLAGS.contains(&name) && kind == TokenKind::Long {
|
||||
return Some(ValueSpec::value());
|
||||
}
|
||||
match kind {
|
||||
TokenKind::Long => matches!(
|
||||
name,
|
||||
"build-tags"
|
||||
| "concurrency"
|
||||
| "default"
|
||||
| "disable"
|
||||
| "enable"
|
||||
| "enable-only"
|
||||
| "issues-exit-code"
|
||||
| "max-issues-per-linter"
|
||||
| "max-same-issues"
|
||||
| "modules-download-mode"
|
||||
| "new-from-merge-base"
|
||||
| "new-from-patch"
|
||||
| "new-from-rev"
|
||||
// v1-only legacy flag (golangci-lint 2.x's --help no longer lists it, replaced
|
||||
// by output.json.path/etc.), kept for v1 installs since has_output_flag checks
|
||||
// for it explicitly.
|
||||
| "out-format"
|
||||
| "path-mode"
|
||||
| "path-prefix"
|
||||
// Deprecated in 2.x but still value-taking there ("flag needs an argument"),
|
||||
// and current in the 1.x installs run_filtered still supports.
|
||||
| "deadline"
|
||||
| "exclude"
|
||||
| "presets"
|
||||
| "skip-dirs"
|
||||
| "skip-files"
|
||||
| "timeout"
|
||||
)
|
||||
.then(ValueSpec::value),
|
||||
// `-e`/`-p` are 1.x's --exclude/--presets; 2.x rejects them outright either way.
|
||||
TokenKind::Short => matches!(name, "D" | "E" | "e" | "j" | "p").then(ValueSpec::solo_only),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct RunInvocation {
|
||||
@@ -123,6 +191,7 @@ pub(crate) fn detect_major_version() -> u32 {
|
||||
}
|
||||
|
||||
pub fn run(args: &[String], verbose: u8) -> Result<i32> {
|
||||
let args = &args_utils::restore_double_dash(args);
|
||||
match classify_invocation(args) {
|
||||
Invocation::FilteredRun(invocation) => run_filtered(args, &invocation, verbose),
|
||||
Invocation::Passthrough => run_passthrough(args, verbose),
|
||||
@@ -132,15 +201,16 @@ pub fn run(args: &[String], verbose: u8) -> Result<i32> {
|
||||
fn run_filtered(original_args: &[String], invocation: &RunInvocation, verbose: u8) -> Result<i32> {
|
||||
let version = detect_major_version();
|
||||
|
||||
let filtered_args = build_filtered_args(invocation, version);
|
||||
let mut cmd = resolved_command("golangci-lint");
|
||||
for arg in build_filtered_args(invocation, version) {
|
||||
for arg in &filtered_args {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
|
||||
if verbose > 0 {
|
||||
eprintln!(
|
||||
"Running: {}",
|
||||
format_command("golangci-lint", &build_filtered_args(invocation, version))
|
||||
format_command("golangci-lint", &filtered_args)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -180,58 +250,28 @@ fn classify_invocation(args: &[String]) -> Invocation {
|
||||
}
|
||||
}
|
||||
|
||||
/// Finds the index in `args` of the first non-flag token, stopping (and returning `None`)
|
||||
/// entirely at `--` or at a non-flag token that isn't a recognized subcommand — mirroring
|
||||
/// golangci-lint's own arg parsing just enough to locate `run`, not fully replicate it.
|
||||
fn find_subcommand_index(args: &[String]) -> Option<usize> {
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
let arg = args[i].as_str();
|
||||
let tokens = arg_tokenizer::tokenize_grammar(args, &global_takes_value, Dialect::Posix);
|
||||
|
||||
if arg == "--" {
|
||||
return None;
|
||||
}
|
||||
|
||||
if !arg.starts_with('-') {
|
||||
if GOLANGCI_SUBCOMMANDS.contains(&arg) {
|
||||
return Some(i);
|
||||
for token in &tokens {
|
||||
match token.kind {
|
||||
TokenKind::DashDash => return None,
|
||||
// A bare "-" (e.g. a stdin placeholder) is unrecognized-flag-like, not a stopping
|
||||
// condition -- keep scanning past it, same as any other unrecognized `-`-prefixed
|
||||
// token, instead of treating it as "no subcommand found."
|
||||
TokenKind::Positional if token.is_free_positional() && token.text != "-" => {
|
||||
return is_subcommand(token.text).then_some(token.source_index);
|
||||
}
|
||||
return None;
|
||||
_ => {}
|
||||
}
|
||||
|
||||
if let Some(flag) = split_flag_name(arg) {
|
||||
if golangci_flag_takes_separate_value(arg, flag) {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn split_flag_name(arg: &str) -> Option<&str> {
|
||||
if arg.starts_with("--") {
|
||||
return Some(arg.split_once('=').map(|(flag, _)| flag).unwrap_or(arg));
|
||||
}
|
||||
|
||||
if arg.starts_with('-') {
|
||||
return Some(arg);
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn golangci_flag_takes_separate_value(arg: &str, flag: &str) -> bool {
|
||||
if !GLOBAL_FLAGS_WITH_VALUE.contains(&flag) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if arg.starts_with("--") && arg.contains('=') {
|
||||
return false;
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
fn build_filtered_args(invocation: &RunInvocation, version: u32) -> Vec<String> {
|
||||
let mut args = invocation.global_args.clone();
|
||||
args.push("run".to_string());
|
||||
@@ -249,12 +289,41 @@ fn build_filtered_args(invocation: &RunInvocation, version: u32) -> Vec<String>
|
||||
args
|
||||
}
|
||||
|
||||
/// The nine `--output.<format>.path` sinks golangci-lint 2.x accepts, enumerated rather than
|
||||
/// pattern-matched: `starts_with("output.")` would also swallow spellings golangci rejects.
|
||||
/// One list, read by both the value-taking predicate and the collision check, so they cannot
|
||||
/// drift apart.
|
||||
const OUTPUT_PATH_FLAGS: &[&str] = &[
|
||||
"output.checkstyle.path",
|
||||
"output.code-climate.path",
|
||||
"output.html.path",
|
||||
"output.json.path",
|
||||
"output.junit-xml.path",
|
||||
"output.sarif.path",
|
||||
"output.tab.path",
|
||||
"output.teamcity.path",
|
||||
"output.text.path",
|
||||
];
|
||||
|
||||
/// True when RTK's own `--output.json.path stdout` would collide with what the user asked for:
|
||||
/// they already configured the json sink (whatever its destination -- golangci takes one path
|
||||
/// per format), or they directed some other format at stdout, where two reports would
|
||||
/// interleave and the json parse would choke on whichever landed first. A *file* sink for some
|
||||
/// other format takes nothing away from stdout, so RTK still injects there or it is left with
|
||||
/// nothing to parse.
|
||||
fn has_output_flag(args: &[String]) -> bool {
|
||||
args.iter().any(|a| {
|
||||
a == "--out-format"
|
||||
|| a.starts_with("--out-format=")
|
||||
|| a == "--output.json.path"
|
||||
|| a.starts_with("--output.json.path=")
|
||||
let tokens = arg_tokenizer::tokenize_grammar(args, &run_takes_value, Dialect::Posix);
|
||||
tokens.iter().any(|t| {
|
||||
if t.kind != TokenKind::Long {
|
||||
return false;
|
||||
}
|
||||
match t.text {
|
||||
"out-format" | "output.json.path" => true,
|
||||
other => {
|
||||
OUTPUT_PATH_FLAGS.contains(&other)
|
||||
&& t.value(&tokens).is_none_or(|dest| dest == "stdout")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -533,6 +602,47 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_invocation_with_short_flag_separate_value_uses_filtered_path() {
|
||||
// -c takes a separate-token value; its value ("foo.yml") must not be mistaken for
|
||||
// the subcommand.
|
||||
assert_eq!(
|
||||
classify_invocation(&[
|
||||
"-c".into(),
|
||||
"foo.yml".into(),
|
||||
"run".into(),
|
||||
"./...".into(),
|
||||
]),
|
||||
Invocation::FilteredRun(RunInvocation {
|
||||
global_args: vec!["-c".into(), "foo.yml".into()],
|
||||
run_args: vec!["./...".into()],
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_invocation_dashdash_before_subcommand_is_passthrough() {
|
||||
// `--` ends option parsing before any subcommand was found; golangci-lint's own
|
||||
// parser gets to decide what follows, not rtk's filter.
|
||||
assert_eq!(
|
||||
classify_invocation(&["--".into(), "run".into()]),
|
||||
Invocation::Passthrough
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_invocation_bare_dash_before_subcommand_uses_filtered_path() {
|
||||
// Regression: a bare "-" (e.g. a stdin placeholder) is unrecognized-flag-like, not a
|
||||
// stopping condition -- must not be mistaken for "no subcommand found."
|
||||
assert_eq!(
|
||||
classify_invocation(&["-".into(), "run".into(), "./...".into()]),
|
||||
Invocation::FilteredRun(RunInvocation {
|
||||
global_args: vec!["-".into()],
|
||||
run_args: vec!["./...".into()],
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_invocation_with_inline_value_flag_uses_filtered_path() {
|
||||
assert_eq!(
|
||||
@@ -589,6 +699,95 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_has_output_flag_ignores_positional_after_dashdash() {
|
||||
// Regression: a positional argument literally named "--out-format" after `--` (e.g.
|
||||
// a package path to lint) must not be mistaken for the real flag.
|
||||
assert!(!has_output_flag(&[
|
||||
"./...".to_string(),
|
||||
"--".to_string(),
|
||||
"--out-format".to_string(),
|
||||
]));
|
||||
assert!(has_output_flag(&["--out-format=json".to_string()]));
|
||||
assert!(has_output_flag(&["--output.json.path".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_has_output_flag_sees_every_output_destination() {
|
||||
// golangci-lint 2.x has one --output.<format>.path per format; RTK injecting a second
|
||||
// sink makes it write two reports to stdout and the JSON parse then fails.
|
||||
for flag in [
|
||||
"--output.text.path",
|
||||
"--output.tab.path",
|
||||
"--output.sarif.path",
|
||||
"--output.checkstyle.path",
|
||||
"--output.code-climate.path",
|
||||
"--output.html.path",
|
||||
"--output.junit-xml.path",
|
||||
"--output.teamcity.path",
|
||||
"--output.json.path",
|
||||
] {
|
||||
assert!(
|
||||
has_output_flag(&[flag.to_string(), "stdout".to_string()]),
|
||||
"{flag} is a user-chosen destination"
|
||||
);
|
||||
}
|
||||
assert!(!has_output_flag(&["--tests".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_run_level_value_flags_swallow_their_own_values() {
|
||||
// `-e '--out-format'` is 1.x's --exclude pattern, not an output flag.
|
||||
assert!(!has_output_flag(&[
|
||||
"-e".to_string(),
|
||||
"--out-format".to_string()
|
||||
]));
|
||||
assert!(!has_output_flag(&[
|
||||
"--concurrency".to_string(),
|
||||
"--output.json.path".to_string()
|
||||
]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_has_output_flag_does_not_misread_a_run_level_flags_value() {
|
||||
// --path-prefix's separate-token value must not be misdetected as the real output flag.
|
||||
assert!(!has_output_flag(&[
|
||||
"--path-prefix".to_string(),
|
||||
"--output.json.path".to_string(),
|
||||
]));
|
||||
assert!(!has_output_flag(&[
|
||||
"--disable".to_string(),
|
||||
"errcheck".to_string(),
|
||||
]));
|
||||
assert!(!has_output_flag(&["--timeout".to_string(), "30s".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_clustered_short_flag_does_not_swallow_the_subcommand() {
|
||||
// Cobra rejects a value-taking shorthand inside a cluster ("unknown shorthand flag:
|
||||
// 'c' in -c", golangci-lint 2.13.1), so reading `-Egosec`'s trailing `c` as --config
|
||||
// and eating `run` lost the subcommand and with it all filtering.
|
||||
let args: Vec<String> = ["-Egosec", "run"].iter().map(|a| a.to_string()).collect();
|
||||
assert_eq!(find_subcommand_index(&args), Some(1));
|
||||
|
||||
// Solo, it still takes its value -- that spelling golangci-lint does accept.
|
||||
let args: Vec<String> = ["-c", "cfg.yml", "run"].iter().map(|a| a.to_string()).collect();
|
||||
assert_eq!(find_subcommand_index(&args), Some(2));
|
||||
|
||||
// And the attached spelling is untouched by the solo-only rule.
|
||||
let args: Vec<String> = ["-cCfg.yml", "run"].iter().map(|a| a.to_string()).collect();
|
||||
assert_eq!(find_subcommand_index(&args), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_golangci_run_takes_value_links_out_format_separate_token_value() {
|
||||
// --out-format is a v1-only legacy flag; its value must still link, not tokenize as an
|
||||
// unlinked Positional.
|
||||
let args = vec!["--out-format".to_string(), "json".to_string()];
|
||||
let tokens = arg_tokenizer::tokenize_grammar(&args, &run_takes_value, Dialect::Posix);
|
||||
assert!(tokens[0].linked.is_some(), "\"json\" must link to --out-format");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_golangci_v2_fields_parse_cleanly() {
|
||||
// v2 JSON includes Severity, SourceLines, Offset — must not panic
|
||||
|
||||
@@ -72,6 +72,21 @@ const NPM_SUBCOMMANDS: &[&str] = &[
|
||||
"start",
|
||||
"stop",
|
||||
"restart",
|
||||
"completion",
|
||||
"edit",
|
||||
"explore",
|
||||
"find-dupes",
|
||||
"help-search",
|
||||
"hook",
|
||||
"install-ci-test",
|
||||
"install-test",
|
||||
"ll",
|
||||
"org",
|
||||
"query",
|
||||
"run-script",
|
||||
"sbom",
|
||||
"shrinkwrap",
|
||||
"unstar",
|
||||
];
|
||||
|
||||
pub fn run(args: &[String], verbose: u8, skip_env: bool) -> Result<i32> {
|
||||
@@ -257,6 +272,34 @@ npm notice
|
||||
assert!(!needs_run_injection(&["run", "build"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extended_official_subcommands_do_not_inject_run() {
|
||||
let subcommands = [
|
||||
"completion",
|
||||
"edit",
|
||||
"explore",
|
||||
"find-dupes",
|
||||
"help-search",
|
||||
"hook",
|
||||
"install-ci-test",
|
||||
"install-test",
|
||||
"ll",
|
||||
"org",
|
||||
"query",
|
||||
"run-script",
|
||||
"sbom",
|
||||
"shrinkwrap",
|
||||
"unstar",
|
||||
];
|
||||
|
||||
for subcommand in subcommands {
|
||||
assert!(
|
||||
NPM_SUBCOMMANDS.contains(&subcommand),
|
||||
"npm {subcommand} must be routed as a native subcommand"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_npm_output_empty() {
|
||||
let output = "\n\n\n";
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
//! Filters `ast-grep run` plain-mode output by grouping matches by file and
|
||||
//! capping how many are shown. `--json` is left near-passthrough (explicit
|
||||
//! structured-output request — see Correctness vs Token Savings).
|
||||
|
||||
use crate::core::stream::exec_capture;
|
||||
use crate::core::tracking;
|
||||
use crate::core::utils::resolved_command;
|
||||
use anyhow::{Context, Result};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
/// Matches the `path:line:` prefix ast-grep emits for every match/context line.
|
||||
static MATCH_LINE_RE: LazyLock<regex::Regex> =
|
||||
LazyLock::new(|| regex::Regex::new(r"^(?P<file>[^:]+):(?P<line>\d+):(?P<content>.*)$").unwrap());
|
||||
|
||||
const DEFAULT_MAX_TOTAL: usize = 50;
|
||||
const DEFAULT_MAX_PER_FILE: usize = 5;
|
||||
|
||||
/// Counts non-blank lines that are not `path:line:content`.
|
||||
///
|
||||
/// Plain `ast-grep run` output is made up entirely of that shape. Other modes
|
||||
/// are not: in an `ast-grep scan` diagnostic only the ` ┌─ a.rs:2:13` locator
|
||||
/// parses, while the rule id, severity, message and source line do not, and
|
||||
/// `--heading` mode and Windows drive-letter paths (`C:\src\a.rs`, which
|
||||
/// `[^:]+` cannot match) fail to parse the same way. Grouping such a shape
|
||||
/// would keep whichever lines happen to parse and discard the rest, so any
|
||||
/// non-zero count leaves the output alone. `search.rs::unparsed_signal` guards
|
||||
/// grep/rg with the same rule.
|
||||
fn unparsed_signal(raw: &str) -> usize {
|
||||
raw.lines()
|
||||
.filter(|line| !line.trim().is_empty() && !MATCH_LINE_RE.is_match(line))
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Groups raw `ast-grep run` plain output by file, keeping at most
|
||||
/// `max_per_file` lines per file and `max_total` lines overall. Every line the
|
||||
/// caps hold back is counted in a hint, so nothing disappears silently; any
|
||||
/// other output shape is returned unchanged.
|
||||
fn filter_ast_grep(raw: &str, max_per_file: usize, max_total: usize) -> String {
|
||||
if unparsed_signal(raw) > 0 {
|
||||
return raw.to_string();
|
||||
}
|
||||
|
||||
let mut by_file: HashMap<&str, Vec<(usize, &str)>> = HashMap::new();
|
||||
let mut order: Vec<&str> = Vec::new();
|
||||
|
||||
for line in raw.lines() {
|
||||
let Some(caps) = MATCH_LINE_RE.captures(line) else {
|
||||
continue;
|
||||
};
|
||||
let file = caps.name("file").unwrap().as_str();
|
||||
let line_num: usize = caps.name("line").unwrap().as_str().parse().unwrap_or(0);
|
||||
let content = caps.name("content").unwrap().as_str();
|
||||
if !by_file.contains_key(file) {
|
||||
order.push(file);
|
||||
}
|
||||
by_file.entry(file).or_default().push((line_num, content));
|
||||
}
|
||||
|
||||
if order.is_empty() {
|
||||
return raw.to_string();
|
||||
}
|
||||
|
||||
let mut out = String::new();
|
||||
let mut shown_total = 0;
|
||||
let mut skipped_files = 0;
|
||||
|
||||
for file in &order {
|
||||
let entries = &by_file[file];
|
||||
if shown_total >= max_total {
|
||||
skipped_files += 1;
|
||||
continue;
|
||||
}
|
||||
let mut shown_here = 0;
|
||||
for (line_num, content) in entries.iter().take(max_per_file) {
|
||||
if shown_total >= max_total {
|
||||
break;
|
||||
}
|
||||
out.push_str(file);
|
||||
out.push(':');
|
||||
out.push_str(&line_num.to_string());
|
||||
out.push(':');
|
||||
out.push_str(content);
|
||||
out.push('\n');
|
||||
shown_total += 1;
|
||||
shown_here += 1;
|
||||
}
|
||||
// `shown_here`, not `max_per_file`: `max_total` can cut a file short of
|
||||
// its own cap, and the hint has to cover every line this loop skipped.
|
||||
// ast-grep prints one line per matched source line and a structural
|
||||
// match spans several, so the unit is lines rather than matches.
|
||||
if entries.len() > shown_here {
|
||||
out.push_str(&format!(
|
||||
" … {} more match line(s) in {}\n",
|
||||
entries.len() - shown_here,
|
||||
file
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if skipped_files > 0 {
|
||||
out.push_str(&format!(
|
||||
"… {} more file(s) with matches not shown (use --json or narrow the pattern)\n",
|
||||
skipped_files
|
||||
));
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
pub fn run(args: &[String]) -> Result<i32> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
let real_cmd = format!("ast-grep {}", args.join(" "));
|
||||
|
||||
let is_json = args.iter().any(|a| a == "--json" || a.starts_with("--json="));
|
||||
|
||||
let mut cmd = resolved_command("ast-grep");
|
||||
cmd.args(args);
|
||||
let result = exec_capture(&mut cmd).context("Failed to execute ast-grep")?;
|
||||
|
||||
let filtered_owned;
|
||||
let filtered: &str = if is_json {
|
||||
&result.stdout
|
||||
} else {
|
||||
filtered_owned = filter_ast_grep(&result.stdout, DEFAULT_MAX_PER_FILE, DEFAULT_MAX_TOTAL);
|
||||
&filtered_owned
|
||||
};
|
||||
|
||||
let shown = crate::core::guard::never_worse(&result.stdout, filtered);
|
||||
timer.track(&real_cmd, "rtk ast-grep", &result.stdout, shown);
|
||||
print!("{}", shown);
|
||||
|
||||
if !result.stderr.is_empty() {
|
||||
eprint!("{}", result.stderr);
|
||||
}
|
||||
|
||||
Ok(result.exit_code)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn count_tokens(s: &str) -> usize {
|
||||
s.split_whitespace().count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_groups_and_caps_by_file() {
|
||||
let input = "\
|
||||
src/a.rs:1:fn foo() {}
|
||||
src/a.rs:2:fn bar() {}
|
||||
src/a.rs:3:fn baz() {}
|
||||
src/b.rs:10:fn qux() {}
|
||||
";
|
||||
let out = filter_ast_grep(input, 2, 50);
|
||||
assert!(out.contains("src/a.rs:1:"));
|
||||
assert!(out.contains("src/a.rs:2:"));
|
||||
assert!(!out.contains("src/a.rs:3:"));
|
||||
assert!(out.contains("1 more match line(s) in src/a.rs"));
|
||||
assert!(out.contains("src/b.rs:10:"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_empty_input() {
|
||||
assert_eq!(filter_ast_grep("", 5, 50), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_unparseable_input_falls_back_unchanged() {
|
||||
let input = "no colons here\njust plain text\n";
|
||||
assert_eq!(filter_ast_grep(input, 5, 50), input);
|
||||
}
|
||||
|
||||
/// A scan diagnostic parses only on its locator line, so grouping it would
|
||||
/// keep ` ┌─ a.rs:2:13` and discard the rule id, severity, message and
|
||||
/// source line.
|
||||
#[test]
|
||||
fn test_scan_diagnostic_shape_passes_through() {
|
||||
let input = "\
|
||||
warning[no-unwrap]: avoid unwrap
|
||||
┌─ a.rs:2:13
|
||||
│
|
||||
2 │ let x = foo().unwrap();
|
||||
│ ^^^^^^^^^^^^^^
|
||||
";
|
||||
assert_eq!(filter_ast_grep(input, 5, 50), input);
|
||||
}
|
||||
|
||||
/// `max_total` can cut a file short before its own `max_per_file` cap is
|
||||
/// reached; the per-file hint must still account for the remainder.
|
||||
#[test]
|
||||
fn test_total_cap_hints_lines_it_cut() {
|
||||
let input = "\
|
||||
a.rs:1:one
|
||||
a.rs:2:two
|
||||
a.rs:3:three
|
||||
a.rs:4:four
|
||||
a.rs:5:five
|
||||
b.rs:1:six
|
||||
b.rs:2:seven
|
||||
b.rs:3:eight
|
||||
";
|
||||
let out = filter_ast_grep(input, 5, 6);
|
||||
assert!(out.contains("b.rs:1:six"), "{out}");
|
||||
assert!(!out.contains("b.rs:2:seven"), "{out}");
|
||||
assert!(
|
||||
out.contains("2 more match line(s) in b.rs"),
|
||||
"cut lines must be hinted, got: {out}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_real_fixture_savings() {
|
||||
let input = include_str!("../../../tests/fixtures/ast_grep_lazylock_raw.txt");
|
||||
let output = filter_ast_grep(input, DEFAULT_MAX_PER_FILE, DEFAULT_MAX_TOTAL);
|
||||
|
||||
let input_tokens = count_tokens(input);
|
||||
let output_tokens = count_tokens(&output);
|
||||
let savings = 100.0 - (output_tokens as f64 / input_tokens as f64 * 100.0);
|
||||
|
||||
assert!(
|
||||
savings >= 60.0,
|
||||
"ast-grep filter: expected >=60% savings, got {:.1}% ({} -> {} tokens)",
|
||||
savings,
|
||||
input_tokens,
|
||||
output_tokens
|
||||
);
|
||||
}
|
||||
}
|
||||
+262
-22
@@ -5,12 +5,14 @@ use crate::core::guard::never_worse;
|
||||
use crate::core::tracking;
|
||||
use anyhow::{Context, Result};
|
||||
use std::fs;
|
||||
use std::io::{self, Read as IoRead, Write};
|
||||
use std::path::Path;
|
||||
|
||||
pub fn run(
|
||||
file: &Path,
|
||||
level: FilterLevel,
|
||||
max_lines: Option<usize>,
|
||||
head_lines: Option<usize>,
|
||||
tail_lines: Option<usize>,
|
||||
line_numbers: bool,
|
||||
verbose: u8,
|
||||
@@ -22,8 +24,25 @@ pub fn run(
|
||||
}
|
||||
|
||||
// Read file content
|
||||
let content = fs::read_to_string(file)
|
||||
let bytes = fs::read(file)
|
||||
.with_context(|| format!("Failed to read file: {}", file.display()))?;
|
||||
if level == FilterLevel::None && !line_numbers {
|
||||
if let Some(window) = byte_line_window(&bytes, head_lines, tail_lines) {
|
||||
io::stdout()
|
||||
.lock()
|
||||
.write_all(window)
|
||||
.context("Failed to write line window")?;
|
||||
timer.track(
|
||||
&format!("cat {}", file.display()),
|
||||
"rtk read",
|
||||
&String::from_utf8_lossy(&bytes),
|
||||
&String::from_utf8_lossy(window),
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let content = String::from_utf8(bytes)
|
||||
.with_context(|| format!("Failed to decode file: {}", file.display()))?;
|
||||
|
||||
// Detect language from extension
|
||||
let lang = file
|
||||
@@ -64,7 +83,7 @@ pub fn run(
|
||||
);
|
||||
}
|
||||
|
||||
filtered = apply_line_window(&filtered, max_lines, tail_lines, &lang);
|
||||
filtered = apply_line_window(&filtered, max_lines, head_lines, tail_lines, &lang);
|
||||
|
||||
let (raw, rtk_output) = if line_numbers {
|
||||
(
|
||||
@@ -88,12 +107,11 @@ pub fn run(
|
||||
pub fn run_stdin(
|
||||
level: FilterLevel,
|
||||
max_lines: Option<usize>,
|
||||
head_lines: Option<usize>,
|
||||
tail_lines: Option<usize>,
|
||||
line_numbers: bool,
|
||||
verbose: u8,
|
||||
) -> Result<()> {
|
||||
use std::io::{self, Read as IoRead};
|
||||
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
if verbose > 0 {
|
||||
@@ -101,11 +119,27 @@ pub fn run_stdin(
|
||||
}
|
||||
|
||||
// Read from stdin
|
||||
let mut content = String::new();
|
||||
let mut bytes = Vec::new();
|
||||
io::stdin()
|
||||
.lock()
|
||||
.read_to_string(&mut content)
|
||||
.read_to_end(&mut bytes)
|
||||
.context("Failed to read from stdin")?;
|
||||
if level == FilterLevel::None && !line_numbers {
|
||||
if let Some(window) = byte_line_window(&bytes, head_lines, tail_lines) {
|
||||
io::stdout()
|
||||
.lock()
|
||||
.write_all(window)
|
||||
.context("Failed to write line window")?;
|
||||
timer.track(
|
||||
"cat - (stdin)",
|
||||
"rtk read -",
|
||||
&String::from_utf8_lossy(&bytes),
|
||||
&String::from_utf8_lossy(window),
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let content = String::from_utf8(bytes).context("Failed to decode stdin")?;
|
||||
|
||||
// No file extension, so use Unknown language
|
||||
let lang = Language::Unknown;
|
||||
@@ -132,7 +166,7 @@ pub fn run_stdin(
|
||||
);
|
||||
}
|
||||
|
||||
filtered = apply_line_window(&filtered, max_lines, tail_lines, &lang);
|
||||
filtered = apply_line_window(&filtered, max_lines, head_lines, tail_lines, &lang);
|
||||
|
||||
let (raw, rtk_output) = if line_numbers {
|
||||
(
|
||||
@@ -162,20 +196,12 @@ fn format_with_line_numbers(content: &str) -> String {
|
||||
fn apply_line_window(
|
||||
content: &str,
|
||||
max_lines: Option<usize>,
|
||||
head_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(window) = byte_line_window(content.as_bytes(), head_lines, tail_lines) {
|
||||
return String::from_utf8_lossy(window).into_owned();
|
||||
}
|
||||
|
||||
if let Some(max) = max_lines {
|
||||
@@ -185,6 +211,61 @@ fn apply_line_window(
|
||||
content.to_string()
|
||||
}
|
||||
|
||||
/// First `n` lines, sliced on byte offsets rather than round-tripped through
|
||||
/// `lines()`, so CRLF endings and an unterminated final line survive verbatim.
|
||||
/// `\n` is ASCII, so valid UTF-8 input also stays valid after slicing.
|
||||
fn head_window(content: &[u8], n: usize) -> &[u8] {
|
||||
if n == 0 {
|
||||
return &[];
|
||||
}
|
||||
let mut seen = 0;
|
||||
for (idx, &byte) in content.iter().enumerate() {
|
||||
if byte == b'\n' {
|
||||
seen += 1;
|
||||
if seen == n {
|
||||
return &content[..=idx];
|
||||
}
|
||||
}
|
||||
}
|
||||
content
|
||||
}
|
||||
|
||||
/// Last `n` lines, byte-sliced for the same fidelity reasons as `head_window`.
|
||||
/// A trailing newline terminates the final line instead of starting a new one,
|
||||
/// so it is excluded before counting separators backwards — otherwise `n` would
|
||||
/// select one line too few for newline-terminated input.
|
||||
fn tail_window(content: &[u8], n: usize) -> &[u8] {
|
||||
if n == 0 {
|
||||
return &[];
|
||||
}
|
||||
let search_end = match content.last() {
|
||||
Some(b'\n') => content.len() - 1,
|
||||
_ => content.len(),
|
||||
};
|
||||
let mut seen = 0;
|
||||
for idx in (0..search_end).rev() {
|
||||
if content[idx] == b'\n' {
|
||||
seen += 1;
|
||||
if seen == n {
|
||||
return &content[idx + 1..];
|
||||
}
|
||||
}
|
||||
}
|
||||
content
|
||||
}
|
||||
|
||||
fn byte_line_window(
|
||||
content: &[u8],
|
||||
head_lines: Option<usize>,
|
||||
tail_lines: Option<usize>,
|
||||
) -> Option<&[u8]> {
|
||||
if let Some(head) = head_lines {
|
||||
Some(head_window(content, head))
|
||||
} else {
|
||||
tail_lines.map(|tail| tail_window(content, tail))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -203,7 +284,7 @@ fn main() {{
|
||||
)?;
|
||||
|
||||
// Just verify it doesn't panic
|
||||
run(file.path(), FilterLevel::Minimal, None, None, false, 0)?;
|
||||
run(file.path(), FilterLevel::Minimal, None, None, None, false, 0)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -217,21 +298,180 @@ fn main() {{
|
||||
#[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);
|
||||
let output = apply_line_window(input, None, 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);
|
||||
let output = apply_line_window(input, None, None, Some(2), &Language::Unknown);
|
||||
assert_eq!(output, "c\nd");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_head_window_matches_native_head() {
|
||||
let input = "1\n2\n3\n4\n5\n";
|
||||
assert_eq!(
|
||||
apply_line_window(input, None, Some(3), None, &Language::Unknown),
|
||||
"1\n2\n3\n"
|
||||
);
|
||||
}
|
||||
|
||||
/// The defect this window exists to fix: `--max-lines N` keeps only about
|
||||
/// N/2 lines, so it could never stand in for `head -N`.
|
||||
#[test]
|
||||
fn test_head_window_keeps_all_n_lines_unlike_max_lines() {
|
||||
let input = (1..=200)
|
||||
.map(|n| n.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
+ "\n";
|
||||
let head = apply_line_window(&input, None, Some(10), None, &Language::Unknown);
|
||||
assert_eq!(head.lines().count(), 10);
|
||||
assert_eq!(head.lines().last(), Some("10"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_head_window_single_line() {
|
||||
let input = "1\n2\n3\n";
|
||||
assert_eq!(
|
||||
apply_line_window(input, None, Some(1), None, &Language::Unknown),
|
||||
"1\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_head_window_zero_is_empty() {
|
||||
assert_eq!(
|
||||
apply_line_window("a\nb\n", None, Some(0), None, &Language::Unknown),
|
||||
""
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_head_window_n_exceeds_line_count() {
|
||||
let input = "a\nb\n";
|
||||
assert_eq!(
|
||||
apply_line_window(input, None, Some(99), None, &Language::Unknown),
|
||||
input
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_head_window_empty_input() {
|
||||
assert_eq!(apply_line_window("", None, Some(5), None, &Language::Unknown), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_head_window_unterminated_final_line() {
|
||||
assert_eq!(
|
||||
apply_line_window("a\nb\nc", None, Some(3), None, &Language::Unknown),
|
||||
"a\nb\nc"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_head_window_preserves_crlf() {
|
||||
assert_eq!(
|
||||
apply_line_window("a\r\nb\r\nc\r\n", None, Some(2), None, &Language::Unknown),
|
||||
"a\r\nb\r\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tail_window_preserves_crlf() {
|
||||
assert_eq!(
|
||||
apply_line_window("a\r\nb\r\nc\r\n", None, None, Some(2), &Language::Unknown),
|
||||
"b\r\nc\r\n"
|
||||
);
|
||||
}
|
||||
|
||||
/// Without discounting the terminal newline, counting separators backwards
|
||||
/// selects one line too few for newline-terminated input.
|
||||
#[test]
|
||||
fn test_tail_window_unterminated_single_line() {
|
||||
assert_eq!(
|
||||
apply_line_window("a\nb\nc", None, None, Some(1), &Language::Unknown),
|
||||
"c"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tail_window_n_exceeds_line_count() {
|
||||
let input = "a\nb\n";
|
||||
assert_eq!(
|
||||
apply_line_window(input, None, None, Some(99), &Language::Unknown),
|
||||
input
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tail_window_empty_input() {
|
||||
assert_eq!(apply_line_window("", None, None, Some(5), &Language::Unknown), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_max_lines_zero_is_empty() {
|
||||
assert_eq!(
|
||||
apply_line_window("a\nb\nc\n", Some(0), None, None, &Language::Unknown),
|
||||
""
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_head_window_mixed_line_endings() {
|
||||
assert_eq!(
|
||||
apply_line_window("a\r\nb\nc\r\n", None, Some(2), None, &Language::Unknown),
|
||||
"a\r\nb\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tail_window_mixed_line_endings() {
|
||||
assert_eq!(
|
||||
apply_line_window("a\r\nb\nc\r\n", None, None, Some(2), &Language::Unknown),
|
||||
"b\nc\r\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_windows_preserve_multibyte_utf8() {
|
||||
let input = "héllo\n日本語\nثالث\n";
|
||||
assert_eq!(
|
||||
apply_line_window(input, None, Some(2), None, &Language::Unknown),
|
||||
"héllo\n日本語\n"
|
||||
);
|
||||
assert_eq!(
|
||||
apply_line_window(input, None, None, Some(2), &Language::Unknown),
|
||||
"日本語\nثالث\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_windows_on_blank_lines_only() {
|
||||
assert_eq!(
|
||||
apply_line_window("\n\n\n", None, Some(2), None, &Language::Unknown),
|
||||
"\n\n"
|
||||
);
|
||||
assert_eq!(
|
||||
apply_line_window("\n\n\n", None, None, Some(2), &Language::Unknown),
|
||||
"\n\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tail_window_zero_is_empty() {
|
||||
assert_eq!(
|
||||
apply_line_window("a\nb\n", None, None, Some(0), &Language::Unknown),
|
||||
""
|
||||
);
|
||||
}
|
||||
|
||||
#[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);
|
||||
let output = apply_line_window(input, Some(2), None, None, &Language::Unknown);
|
||||
assert!(output.starts_with("a\n"));
|
||||
assert!(output.contains("more lines"));
|
||||
}
|
||||
|
||||
+938
-484
File diff suppressed because it is too large.
Load diff
@@ -111,6 +111,28 @@ Key functions available to all command modules:
|
||||
| `ruby_exec(tool)` | Auto-detect `bundle exec` when `Gemfile` exists |
|
||||
| `count_tokens(text)` | Estimate tokens: `ceil(chars / 4.0)` |
|
||||
|
||||
## Argument Tokenizer (arg_tokenizer.rs)
|
||||
|
||||
Shared classifier for an already-`--`-restored args slice (see `args_utils::restore_double_dash`) into flags, their values, and positionals. `tokenize_grammar` takes a `takes_value(kind, name)` predicate the caller supplies — the list of which flags take a value is per-tool, but the token-walking around it isn't. `tokenize(args)` is the structural-only entry point, for a caller asking which arguments are flags and where `--` is; it assumes **no flag takes a value**, so anything reading a value or counting free positionals needs `tokenize_grammar`.
|
||||
|
||||
**Use it for anything that decides what an argument is.** A new command filter, a new flag on an existing one, or a fix to how one is detected goes through `tokenize_grammar` — not `starts_with('-')`, not `args.iter().any(|a| a == "--flag")`. Those miss exactly what this module exists for: a flag's own value (`git log --grep -p` searches for the string "-p"), an attached value (`--flag=v`, `/bl:x`), a short cluster (`-rn`), and everything past `--`. Every bug the migration fixed was one of those four.
|
||||
|
||||
Four rules, each of which cost a real bug before it was written down:
|
||||
|
||||
- **One grammar per tool and subcommand.** Never reuse a sibling's predicate wholesale because it looks close enough — `-u` means `-p` in `git log` but `--include-untracked` in `git stash show`, and `-T` is `--initial-tab` in grep but `--type-not` in rg. Transcribe from the tool's own `--help` and verify against the real binary; grep and rg share 13 of ~50 value-taking flags, so one merged table is wrong for both.
|
||||
- **Scope the lookup to the region the tool parses.** Everything past `--` is a pathspec or an argument forwarded to another program — `before_dashdash` gives the tool's own tokens. `Dialect::Msbuild` keeps classifying past the boundary (it forwards rather than ending option parsing), which makes this explicit slice mandatory there, not optional.
|
||||
- **Inject before the boundary.** RTK's own flags go at `injection_point`, never appended: dotnet parks anything after `--` in UnparsedTokens and git reads it as a pathspec, so an appended `--verify-no-changes` silently does nothing.
|
||||
- **Detect and act with one rule.** Strip or inject using the detected token's `source_index`; re-matching the text lets the two disagree, which deleted a pathspec named `--no-compact` and swallowed a forwarded `--write`.
|
||||
|
||||
`takes_value` returns `Option<ValueSpec>`, not a `bool`: one table per tool, answering every question the tokenizer has about a flag's value rather than one predicate per question, which is how two lists start drifting apart.
|
||||
|
||||
- `ValueSpec::value()` — `--flag=v` or `--flag v`, and a literal `--` is the boundary. The common case.
|
||||
- `ValueSpec::attached_only()` — `--flag=v` only, the next argument is never the value (git's `-M`/`-U`/`-C`/`-B` take an optional attached number and nothing else).
|
||||
- `ValueSpec::solo_only()` — a `Short` flag takes a separate value only when it is the whole argument: `git log -n 2` does, `git log -pn 2` does not. No meaning for a `Long` flag.
|
||||
- `.claiming_dash_dash()` — lets a literal `--` be this flag's value. A per-tool split, not per-flag: grep and rg let any value-taking flag swallow it, git and cargo reject it whichever flag is asking.
|
||||
|
||||
The dialect is the one axis that is not per-flag, so it stays a parameter: `tokenize_grammar(args, takes_value, Dialect::Msbuild)`.
|
||||
|
||||
## Consumer Contracts
|
||||
|
||||
Core provides infrastructure that `cmds/` and other components consume. These contracts define expected usage.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+7
-1
@@ -318,6 +318,12 @@ pub fn get_filter(level: FilterLevel) -> Box<dyn FilterStrategy> {
|
||||
}
|
||||
|
||||
pub fn smart_truncate(content: &str, max_lines: usize, _lang: &Language) -> String {
|
||||
// A zero budget shows nothing, matching `--tail-lines 0`/`--head-lines 0`.
|
||||
// Returning early also keeps `max_lines - 1` below from underflowing.
|
||||
if max_lines == 0 {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
let lines: Vec<&str> = content.lines().collect();
|
||||
if lines.len() <= max_lines {
|
||||
return content.to_string();
|
||||
@@ -346,7 +352,7 @@ pub fn smart_truncate(content: &str, max_lines: usize, _lang: &Language) -> Stri
|
||||
// Non-important lines beyond max_lines/2 are silently skipped —
|
||||
// no inline markers that could be mistaken for file content.
|
||||
|
||||
if kept_lines >= max_lines - 1 {
|
||||
if kept_lines + 1 >= max_lines {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Building blocks shared across all RTK modules.
|
||||
|
||||
pub mod arg_tokenizer;
|
||||
pub mod args_utils;
|
||||
pub mod config;
|
||||
pub mod constants;
|
||||
|
||||
+18
-6
@@ -2,6 +2,7 @@
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use regex::Regex;
|
||||
use std::borrow::Cow;
|
||||
use std::process::Command;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
@@ -138,6 +139,8 @@ where
|
||||
raw
|
||||
};
|
||||
|
||||
// stderr is forwarded unchanged below, so it costs the same whether or not rtk is
|
||||
// in the way. What the guard must not inflate is the stdout it replaces.
|
||||
let shown = if let Some(label) = opts.tee_label {
|
||||
print_with_hint(&filtered, raw, raw_for_tracking, label, exit_code)
|
||||
} else {
|
||||
@@ -150,12 +153,21 @@ where
|
||||
guarded
|
||||
};
|
||||
|
||||
timer.track(
|
||||
cmd_label,
|
||||
&format!("rtk {}", cmd_label),
|
||||
raw_for_tracking,
|
||||
&shown,
|
||||
);
|
||||
// Stdout-only filters parse structured stdout; stderr still carries diagnostics
|
||||
// (config errors, missing linters) that the user needs.
|
||||
let forwarded_stderr = opts.filter_stdout_only && !result.raw_stderr.trim().is_empty();
|
||||
if forwarded_stderr {
|
||||
eprint!("{}", result.raw_stderr);
|
||||
}
|
||||
|
||||
// Forwarded stderr reaches the user just as much as stdout does, so counting only
|
||||
// stdout would book a passed-through stream as if the filter had removed it.
|
||||
let emitted = if forwarded_stderr {
|
||||
Cow::Owned(format!("{}{}", shown, result.raw_stderr))
|
||||
} else {
|
||||
Cow::Borrowed(shown.as_str())
|
||||
};
|
||||
timer.track(cmd_label, &format!("rtk {}", cmd_label), raw, &emitted);
|
||||
Ok(exit_code)
|
||||
}
|
||||
|
||||
|
||||
+294
-10
@@ -202,7 +202,7 @@ pub struct GainSummary {
|
||||
pub total_time_ms: u64,
|
||||
/// Average execution time per command (milliseconds)
|
||||
pub avg_time_ms: u64,
|
||||
/// Top 10 commands by tokens saved: (cmd, count, saved, avg_pct, avg_time_ms)
|
||||
/// Top 10 commands by tokens saved: (cmd, count, saved, weighted_rate, avg_time_ms)
|
||||
pub by_command: Vec<(String, usize, usize, f64, u64)>,
|
||||
/// Last 30 days of activity: (date, saved_tokens)
|
||||
pub by_day: Vec<(String, usize)>,
|
||||
@@ -295,7 +295,16 @@ pub struct MonthStats {
|
||||
pub avg_time_ms: u64,
|
||||
}
|
||||
|
||||
/// Type alias for command statistics tuple: (command, count, saved_tokens, avg_savings_pct, avg_time_ms)
|
||||
/// Type alias for command statistics tuple: (command, count, saved_tokens, weighted_savings_rate, avg_time_ms)
|
||||
///
|
||||
/// # Warning
|
||||
/// The 4th field is a **weighted** savings rate: `SUM(saved_tokens) / SUM(input_tokens) * 100.0`,
|
||||
/// guarded so that a group whose every row has zero input reports 0.0 rather than NULL.
|
||||
/// Do NOT aggregate this column with `AVG()` — that would produce an unweighted mean that
|
||||
/// under-weights high-volume commands. Always recompute it as
|
||||
/// `CASE WHEN SUM(input_tokens) > 0 THEN SUM(saved_tokens) / SUM(input_tokens) * 100.0 ELSE 0.0 END`
|
||||
/// instead. `saved_tokens` is signed, so the rate can be negative where the 3rd field, being
|
||||
/// unsigned, is clamped to 0.
|
||||
type CommandStats = (String, usize, usize, f64, u64);
|
||||
|
||||
/// Current tracking-DB schema version, stored in the SQLite `user_version` pragma.
|
||||
@@ -893,7 +902,9 @@ impl Tracker {
|
||||
) -> Result<Vec<CommandStats>> {
|
||||
let (project_exact, project_glob) = project_filter_params(project_path); // added
|
||||
let mut stmt = self.conn.prepare(
|
||||
"SELECT rtk_cmd, COUNT(*), SUM(saved_tokens), AVG(savings_pct), AVG(exec_time_ms)
|
||||
"SELECT rtk_cmd, COUNT(*), SUM(saved_tokens),
|
||||
CASE WHEN SUM(input_tokens) > 0 THEN SUM(saved_tokens) * 100.0 / SUM(input_tokens) ELSE 0.0 END,
|
||||
AVG(exec_time_ms)
|
||||
FROM commands
|
||||
WHERE (?1 IS NULL OR project_path = ?1 OR project_path GLOB ?2)
|
||||
GROUP BY rtk_cmd
|
||||
@@ -1312,12 +1323,21 @@ impl Tracker {
|
||||
}
|
||||
|
||||
/// Count commands with low savings (<30%) — filters that need improvement.
|
||||
///
|
||||
/// Uses the same weighted rate as `get_by_command`, `SUM(saved_tokens) / SUM(input_tokens)`
|
||||
/// over every call of the command, so that a handful of 0%-savings passthrough calls don't
|
||||
/// dilute a filter that genuinely performs well on high-volume invocations, and so that the
|
||||
/// figure sent here is the one `rtk gain` prints for the same command. A net-regressing
|
||||
/// command (negative rate) is listed: it is the filter most in need of improvement. Exact
|
||||
/// 0% is left out, `passthrough_top` already reports it, and a command whose calls never
|
||||
/// had any input carries no signal, so it is skipped rather than reported as 0%.
|
||||
pub fn low_savings_commands(&self, limit: usize) -> Result<Vec<(String, f64)>> {
|
||||
let mut stmt = self.conn.prepare(
|
||||
"SELECT rtk_cmd, AVG(savings_pct) as avg_sav FROM commands
|
||||
WHERE input_tokens > 0
|
||||
"SELECT rtk_cmd,
|
||||
SUM(saved_tokens) * 100.0 / SUM(input_tokens) AS sav
|
||||
FROM commands
|
||||
GROUP BY rtk_cmd
|
||||
HAVING avg_sav < 30.0 AND avg_sav > 0.0
|
||||
HAVING SUM(input_tokens) > 0 AND sav < 30.0 AND sav <> 0.0
|
||||
ORDER BY COUNT(*) DESC LIMIT ?1",
|
||||
)?;
|
||||
let rows = stmt.query_map(params![limit as i64], |row| {
|
||||
@@ -1329,7 +1349,15 @@ impl Tracker {
|
||||
Ok(rows.filter_map(|r| r.ok()).collect())
|
||||
}
|
||||
|
||||
/// Average savings percentage per command (unweighted — each command name counts once).
|
||||
/// Average savings percentage per command (unweighted across command names — each distinct
|
||||
/// command counts once, regardless of how many times it was invoked).
|
||||
///
|
||||
/// The *inner* rate per command is weighted by volume (`SUM(saved)/SUM(input)`) so that
|
||||
/// passthrough calls don't dilute a command's own rate. The *outer* average across command
|
||||
/// names stays unweighted — this is intentional: it gives equal weight to every filter
|
||||
/// instead of being dominated by the most-called one. Documented in `docs/TELEMETRY.md`.
|
||||
/// A command whose calls never had any input carries no signal about its filter and is
|
||||
/// skipped, not counted as 0%.
|
||||
///
|
||||
/// Keeps the honest signed value: a command whose filter consistently emits
|
||||
/// more than it saves yields a negative average, mirroring `overall_savings_pct`
|
||||
@@ -1338,10 +1366,12 @@ impl Tracker {
|
||||
/// not on a `0..=100` floor.
|
||||
pub fn avg_savings_per_command(&self) -> Result<f64> {
|
||||
let avg: f64 = self.conn.query_row(
|
||||
"SELECT COALESCE(AVG(avg_sav), 0.0) FROM (
|
||||
SELECT rtk_cmd, AVG(savings_pct) as avg_sav
|
||||
FROM commands WHERE input_tokens > 0
|
||||
"SELECT COALESCE(AVG(cmd_rate), 0.0) FROM (
|
||||
SELECT rtk_cmd,
|
||||
SUM(saved_tokens) * 100.0 / SUM(input_tokens) AS cmd_rate
|
||||
FROM commands
|
||||
GROUP BY rtk_cmd
|
||||
HAVING SUM(input_tokens) > 0
|
||||
)",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
@@ -2535,4 +2565,258 @@ mod tests {
|
||||
assert_eq!(categorize_command(cmd), "js", "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
// 14. get_by_command uses weighted savings rate, not unweighted average
|
||||
//
|
||||
// Regression test for: AVG(savings_pct) gave wrong results when small invocations
|
||||
// with 0% savings diluted the average of high-volume commands.
|
||||
//
|
||||
// Setup: one small command (10% savings) + one large command (95% savings).
|
||||
// Unweighted avg would be ~52.5%. Weighted rate must be ~95%.
|
||||
//
|
||||
// Rows carry a project path so the project-filtered form of the query is the one
|
||||
// under test.
|
||||
#[test]
|
||||
fn test_get_by_command_weighted_savings_rate() {
|
||||
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
|
||||
let cmd_name = "weighted_test";
|
||||
let project = "/tmp/rtk_weighted_test";
|
||||
|
||||
// Override project_path by inserting directly via conn
|
||||
let saved_small = 10_i64; // 100 in - 90 out = 10 saved → 10%
|
||||
let saved_large = 95_000_i64; // 100_000 in - 5_000 out = 95_000 saved → 95%
|
||||
tracker
|
||||
.conn
|
||||
.execute(
|
||||
"INSERT INTO commands (timestamp, original_cmd, rtk_cmd, project_path, input_tokens, output_tokens, saved_tokens, savings_pct, exec_time_ms)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
|
||||
rusqlite::params![
|
||||
chrono::Utc::now().to_rfc3339(),
|
||||
cmd_name, cmd_name, project,
|
||||
100_i64, 90_i64, saved_small, 10.0_f64, 5_i64
|
||||
],
|
||||
)
|
||||
.expect("Failed to insert small invocation");
|
||||
tracker
|
||||
.conn
|
||||
.execute(
|
||||
"INSERT INTO commands (timestamp, original_cmd, rtk_cmd, project_path, input_tokens, output_tokens, saved_tokens, savings_pct, exec_time_ms)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
|
||||
rusqlite::params![
|
||||
chrono::Utc::now().to_rfc3339(),
|
||||
cmd_name, cmd_name, project,
|
||||
100_000_i64, 5_000_i64, saved_large, 95.0_f64, 10_i64
|
||||
],
|
||||
)
|
||||
.expect("Failed to insert large invocation");
|
||||
|
||||
let by_cmd = tracker
|
||||
.get_by_command(Some(project))
|
||||
.expect("Failed to get by_command stats");
|
||||
|
||||
let entry = by_cmd
|
||||
.iter()
|
||||
.find(|(name, _, _, _, _)| name == cmd_name)
|
||||
.expect("Test command not found in by_command stats");
|
||||
|
||||
let (_name, _count, _saved, rate, _time) = entry;
|
||||
|
||||
// Weighted rate = (10 + 95_000) / (100 + 100_000) * 100.0 ≈ 94.9%
|
||||
// Unweighted avg would be (10.0 + 95.0) / 2 = 52.5%
|
||||
// The gap proves the fix works.
|
||||
assert!(
|
||||
*rate > 90.0,
|
||||
"Expected weighted rate >90%, got {:.1}% — unweighted avg would be ~52.5%",
|
||||
rate
|
||||
);
|
||||
}
|
||||
|
||||
// 15. The weighted rate tracks SUM(saved_tokens), not the mean of per-call percentages
|
||||
//
|
||||
// A long-tailed pair under one rtk_cmd: a 1M-token call saving 90% and a 100-token
|
||||
// call saving 10%. The mean of the two percentages is 50%; the weighted rate is
|
||||
// ~89.99% and is the figure consistent with the Saved column in the same row.
|
||||
#[test]
|
||||
fn test_weighted_rate_via_get_by_command() {
|
||||
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
|
||||
|
||||
tracker
|
||||
.record("grep huge", "rtk grep", 1_000_000, 100_000, 50)
|
||||
.expect("record huge");
|
||||
tracker
|
||||
.record("grep tiny", "rtk grep", 100, 90, 5)
|
||||
.expect("record tiny");
|
||||
|
||||
let by_command = tracker.get_by_command(None).expect("get_by_command");
|
||||
|
||||
let (_cmd, count, saved, pct, _avg_time) = by_command
|
||||
.iter()
|
||||
.find(|(cmd, ..)| cmd == "rtk grep")
|
||||
.expect("rtk grep row not found");
|
||||
|
||||
assert_eq!(*count, 2);
|
||||
assert_eq!(*saved, 900_010);
|
||||
let expected = 900_010.0 / 1_000_100.0 * 100.0;
|
||||
assert!(
|
||||
(pct - expected).abs() < 0.01,
|
||||
"expected weighted rate ~{expected:.2}, got {pct:.2}"
|
||||
);
|
||||
assert!(
|
||||
(pct - 50.0).abs() > 1.0,
|
||||
"mean-of-percentages regression: got {pct:.2}"
|
||||
);
|
||||
}
|
||||
|
||||
// 16. The rate reaches the gain summary through get_summary(), not only get_by_command
|
||||
#[test]
|
||||
fn test_weighted_rate_via_get_summary() {
|
||||
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
|
||||
|
||||
tracker
|
||||
.record("large grep", "rtk grep", 1000, 100, 10)
|
||||
.expect("Failed to record large command");
|
||||
tracker
|
||||
.record("small grep", "rtk grep", 10, 9, 20)
|
||||
.expect("Failed to record small command");
|
||||
|
||||
let summary = tracker.get_summary().expect("Failed to get summary");
|
||||
let (_, count, saved, savings_pct, _) = summary
|
||||
.by_command
|
||||
.iter()
|
||||
.find(|(command, _, _, _, _)| command == "rtk grep")
|
||||
.expect("rtk grep stats not found");
|
||||
|
||||
assert_eq!(*count, 2);
|
||||
assert_eq!(*saved, 901);
|
||||
let expected_pct = 901.0 / 1010.0 * 100.0;
|
||||
assert!(
|
||||
(savings_pct - expected_pct).abs() < 1e-10,
|
||||
"expected weighted rate {expected_pct}, got {savings_pct}"
|
||||
);
|
||||
}
|
||||
|
||||
// 17. A group whose every call has zero input reports 0%, not a division by zero
|
||||
#[test]
|
||||
fn test_by_command_zero_input_has_zero_savings_percentage() {
|
||||
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
|
||||
tracker
|
||||
.record("interactive command", "rtk proxy", 0, 0, 5)
|
||||
.expect("Failed to record passthrough command");
|
||||
|
||||
let summary = tracker.get_summary().expect("Failed to get summary");
|
||||
let (_, _, _, savings_pct, _) = summary
|
||||
.by_command
|
||||
.iter()
|
||||
.find(|(command, _, _, _, _)| command == "rtk proxy")
|
||||
.expect("rtk proxy stats not found");
|
||||
|
||||
assert_eq!(*savings_pct, 0.0);
|
||||
}
|
||||
|
||||
// 18. low_savings_commands reports the same weighted rate as the `rtk gain` By Command
|
||||
// table, including net-regressing commands, and nothing for commands without input.
|
||||
//
|
||||
// `rtk ls -R`: one 95% call plus four 0% passthrough calls. Unweighted AVG(savings_pct)
|
||||
// over those five rows is 19%, under the 30% threshold, so the command would reach
|
||||
// telemetry as low-savings while `get_by_command` shows it at ~94.6% in the same
|
||||
// `rtk gain` run. Weighted, 95_000 / 100_400 ≈ 94.6%: not listed.
|
||||
// `rtk grep`: 25% on one call, then a call with no input that still printed 10 tokens.
|
||||
// Every row counts, as in `get_by_command`: (250 - 10) / 1_000 = 24%, listed at 24.
|
||||
// `rtk read`: emits more than it saves, -50%. Listed: it is the filter to fix first.
|
||||
// `rtk proxy`: never had any input. Nothing to say about its filter, not listed.
|
||||
#[test]
|
||||
fn test_low_savings_commands_matches_gain_weighted_rate() {
|
||||
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
|
||||
tracker
|
||||
.record("ls -R big", "rtk ls -R", 100_000, 5_000, 10)
|
||||
.expect("record big call");
|
||||
for _ in 0..4 {
|
||||
tracker
|
||||
.record("ls -R empty", "rtk ls -R", 100, 100, 5)
|
||||
.expect("record passthrough call");
|
||||
}
|
||||
tracker
|
||||
.record("grep x", "rtk grep", 1_000, 750, 5)
|
||||
.expect("record 25% call");
|
||||
tracker
|
||||
.record("grep none", "rtk grep", 0, 10, 5)
|
||||
.expect("record no-input call");
|
||||
tracker
|
||||
.record("read big.json", "rtk read", 100, 150, 5)
|
||||
.expect("record regressing call");
|
||||
tracker
|
||||
.record("interactive", "rtk proxy", 0, 0, 5)
|
||||
.expect("record zero-input call");
|
||||
|
||||
let low = tracker
|
||||
.low_savings_commands(10)
|
||||
.expect("low_savings_commands");
|
||||
let listed: Vec<(&str, f64)> = low.iter().map(|(n, r)| (n.as_str(), *r)).collect();
|
||||
assert_eq!(
|
||||
listed.len(),
|
||||
2,
|
||||
"expected `rtk grep` (24%) and `rtk read` (-50%); ~94.6% weighted must not be \
|
||||
listed (unweighted AVG(savings_pct) would put it at 19%), got {listed:?}"
|
||||
);
|
||||
assert_eq!(listed[0].0, "rtk grep");
|
||||
assert!((listed[0].1 - 24.0).abs() < 1e-9, "got {listed:?}");
|
||||
assert_eq!(listed[1].0, "rtk read");
|
||||
assert!((listed[1].1 - (-50.0)).abs() < 1e-9, "got {listed:?}");
|
||||
|
||||
// The figure sent to telemetry is the one `rtk gain` prints for the same command.
|
||||
let summary = tracker.get_summary().expect("get_summary");
|
||||
for (name, rate) in &low {
|
||||
let (_, _, _, gain_rate, _) = summary
|
||||
.by_command
|
||||
.iter()
|
||||
.find(|(command, _, _, _, _)| command == name)
|
||||
.unwrap_or_else(|| panic!("{name} missing from by_command"));
|
||||
assert!(
|
||||
(gain_rate - rate).abs() < 1e-9,
|
||||
"{name}: telemetry says {rate}, rtk gain says {gain_rate}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 19. avg_savings_per_command weights each command's own rate by volume (every call
|
||||
// counted, as in test 18), then averages the per-command rates without weighting: each
|
||||
// command name counts once, and a command that never had any input is not counted.
|
||||
//
|
||||
// Same rows as test 18: `rtk ls -R` ≈ 94.6% (19% if the inner aggregate were
|
||||
// AVG(savings_pct)), `rtk grep` 24%, `rtk read` -50%, `rtk proxy` skipped.
|
||||
#[test]
|
||||
fn test_avg_savings_per_command_inner_rate_is_weighted() {
|
||||
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
|
||||
tracker
|
||||
.record("ls -R big", "rtk ls -R", 100_000, 5_000, 10)
|
||||
.expect("record big call");
|
||||
for _ in 0..4 {
|
||||
tracker
|
||||
.record("ls -R empty", "rtk ls -R", 100, 100, 5)
|
||||
.expect("record passthrough call");
|
||||
}
|
||||
tracker
|
||||
.record("grep x", "rtk grep", 1_000, 750, 5)
|
||||
.expect("record 25% call");
|
||||
tracker
|
||||
.record("grep none", "rtk grep", 0, 10, 5)
|
||||
.expect("record no-input call");
|
||||
tracker
|
||||
.record("read big.json", "rtk read", 100, 150, 5)
|
||||
.expect("record regressing call");
|
||||
tracker
|
||||
.record("interactive", "rtk proxy", 0, 0, 5)
|
||||
.expect("record zero-input call");
|
||||
|
||||
let avg = tracker
|
||||
.avg_savings_per_command()
|
||||
.expect("avg_savings_per_command");
|
||||
let ls_rate = 95_000.0 * 100.0 / 100_400.0;
|
||||
let expected = (ls_rate + 24.0 - 50.0) / 3.0;
|
||||
assert!(
|
||||
(avg - expected).abs() < 1e-6,
|
||||
"expected ({ls_rate:.1} + 24 - 50) / 3 = {expected:.1}%, got {avg:.1}% \
|
||||
(an unweighted inner AVG(savings_pct) would give (19 + 12.5 - 50) / 3 = -6.2%)"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@ When a hook sends `cargo fmt --all && cargo test 2>&1 | tail -20`:
|
||||
**Per-segment rewriting** — Each segment goes through:
|
||||
|
||||
1. Strip trailing redirects (`2>&1`, `>/dev/null`) — matched via lexer tokens, set aside, re-appended after rewriting
|
||||
2. Short-circuit special cases — `head -20 file` → `rtk read file --max-lines 20`, `tail -n 5 file` → `rtk read file --tail-lines 5`. These can't go through generic prefix replacement because it would produce `rtk read -20 file` (wrong flag position)
|
||||
2. Short-circuit special cases — `head -20 file` → `rtk read file --head-lines 20`, `tail -n 5 file` → `rtk read file --tail-lines 5`. These can't go through generic prefix replacement because it would produce `rtk read -20 file` (wrong flag position)
|
||||
3. Classify the command — strip env prefixes (`FOO="bar baz"`), normalize paths (`/usr/bin/grep` → `grep`), strip git global opts (`git -C /tmp` → `git`), then match against 60+ regex patterns from `rules.rs`
|
||||
4. Apply the rewrite — find the matching rule, replace the command prefix with `rtk <cmd>`, re-prepend the env prefix, re-append the redirect suffix
|
||||
|
||||
|
||||
+264
-15
@@ -80,10 +80,67 @@ static GIT_GLOBAL_OPT: LazyLock<Regex> = LazyLock::new(|| {
|
||||
// Issue #1362: each capture expects a SINGLE file argument (`\S+$`). Multi-file
|
||||
// invocations like `head -3 a b c` fail to match so the segment is passed through
|
||||
// to the native `head`/`tail` binary — which already handles multi-file with
|
||||
// `==> name <==` banners that `rtk read --max-lines` cannot reproduce.
|
||||
// `==> name <==` banners that a single `rtk read` window cannot reproduce.
|
||||
static HEAD_N: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^head\s+-(\d+)\s+(\S+)$").unwrap());
|
||||
static HEAD_LINES: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"^head\s+--lines=(\d+)\s+(\S+)$").unwrap());
|
||||
// `-n N` and `--lines N` are the spellings `tail` already accepted below; `head`
|
||||
// silently fell through to no rewrite at all without them.
|
||||
static HEAD_N_SPACE: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"^head\s+-n\s+(\d+)\s+(\S+)$").unwrap());
|
||||
static HEAD_LINES_SPACE: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"^head\s+--lines\s+(\d+)\s+(\S+)$").unwrap());
|
||||
// Bare `head FILE` means ten lines, not the whole file. Restricted to a single
|
||||
// operand: multi-file and optioned forms stay with the native binary.
|
||||
static HEAD_BARE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^head\s+(\S+)$").unwrap());
|
||||
|
||||
/// Re-attach a trailing redirect to a rewritten head/tail command.
|
||||
///
|
||||
/// `head -n 1 f>out` strips to a suffix with no leading space, and these
|
||||
/// rewrites end in a bare number, so plain concatenation yields
|
||||
/// `--head-lines 1>out` — which the shell reads as an fd-1 redirect, leaving
|
||||
/// `--head-lines` with no value. A separating space keeps the flag intact.
|
||||
///
|
||||
/// Deliberately not applied to the shared prefix rewrites: those keep the
|
||||
/// original argument/redirect boundary, where inserting a space could split a
|
||||
/// descriptor-duplication form such as `1>&2` and demote the descriptor number
|
||||
/// into an argument.
|
||||
fn join_redirect_suffix(rewritten: &str, redirect_suffix: &str) -> String {
|
||||
if redirect_suffix.is_empty() || redirect_suffix.starts_with(char::is_whitespace) {
|
||||
format!("{}{}", rewritten, redirect_suffix)
|
||||
} else {
|
||||
format!("{} {}", rewritten, redirect_suffix)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an operand is safe to hand to `rtk read` as one concrete file.
|
||||
///
|
||||
/// One whitespace-delimited token is not one shell operand: `*.rs`, `{a,b}` and
|
||||
/// `$FILES` each expand to several at execution time, and `rtk read`
|
||||
/// concatenates files where `head`/`tail` print `==> name <==` banners.
|
||||
///
|
||||
/// The token is raw shell source, not the argument the callee receives, so
|
||||
/// character-class blocklists kept missing cases: `'--'` and `\--help` hide an
|
||||
/// option behind a quote or backslash, and a leading `#` opens a comment that
|
||||
/// swallows the flags this rewrite appends. Hence an allowlist: only characters
|
||||
/// that cannot change the operand's word count or turn it into an option are
|
||||
/// accepted, and anything else is left to the native binary. `~` is the one
|
||||
/// shell-active character kept, because tilde expansion yields exactly one word
|
||||
/// and the operand is passed through unchanged. Unicode alphanumerics stay
|
||||
/// eligible so non-ASCII filenames still route.
|
||||
///
|
||||
/// The cost is deliberate: a quoted literal like `'literal*.txt'` also stays
|
||||
/// native even though the quoting would prevent expansion. Losing a rewrite is
|
||||
/// recoverable; changing what the user's command does is not.
|
||||
fn is_single_file_operand(operand: &str) -> bool {
|
||||
if operand.is_empty() || operand.starts_with('-') {
|
||||
return false;
|
||||
}
|
||||
operand.chars().all(|c| {
|
||||
c.is_alphanumeric()
|
||||
|| matches!(c, '.' | '_' | '/' | '-' | '~' | '+' | '@' | ':' | ',' | '=')
|
||||
})
|
||||
}
|
||||
static TAIL_N: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^tail\s+-(\d+)\s+(\S+)$").unwrap());
|
||||
static TAIL_N_SPACE: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"^tail\s+-n\s+(\d+)\s+(\S+)$").unwrap());
|
||||
@@ -1242,14 +1299,23 @@ fn rewrite_compound(
|
||||
}
|
||||
|
||||
fn rewrite_line_range(cmd: &str) -> Option<String> {
|
||||
for re in [&*HEAD_N, &*HEAD_LINES] {
|
||||
for re in [&*HEAD_N, &*HEAD_LINES, &*HEAD_N_SPACE, &*HEAD_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 {} --max-lines {}", file, n));
|
||||
if is_single_file_operand(file) {
|
||||
return Some(format!("rtk read {} --head-lines {}", file, n));
|
||||
}
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if cmd.starts_with("head -") {
|
||||
if let Some(caps) = HEAD_BARE.captures(cmd) {
|
||||
let file = caps.get(1)?.as_str();
|
||||
if is_single_file_operand(file) {
|
||||
return Some(format!("rtk read {} --head-lines 10", file));
|
||||
}
|
||||
}
|
||||
if cmd.starts_with("head") {
|
||||
return None;
|
||||
}
|
||||
for re in [
|
||||
@@ -1261,7 +1327,10 @@ fn rewrite_line_range(cmd: &str) -> Option<String> {
|
||||
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));
|
||||
if is_single_file_operand(file) {
|
||||
return Some(format!("rtk read {} --tail-lines {}", file, n));
|
||||
}
|
||||
return None;
|
||||
}
|
||||
}
|
||||
None
|
||||
@@ -1578,7 +1647,7 @@ fn rewrite_segment_inner(
|
||||
}
|
||||
|
||||
if context == RewriteContext::Normal
|
||||
&& (cmd_part.starts_with("head -") || cmd_part.starts_with("tail "))
|
||||
&& (cmd_part.starts_with("head ") || cmd_part.starts_with("tail "))
|
||||
{
|
||||
// head/tail rewrite to `rtk read`, so honour exclude_commands here too:
|
||||
// this branch returns before the checks below. Any env prefix has already
|
||||
@@ -1586,7 +1655,7 @@ fn rewrite_segment_inner(
|
||||
if is_excluded(cmd_part, excluded) {
|
||||
return None;
|
||||
}
|
||||
return rewrite_line_range(cmd_part).map(|r| format!("{}{}", r, redirect_suffix));
|
||||
return rewrite_line_range(cmd_part).map(|r| join_redirect_suffix(&r, redirect_suffix));
|
||||
}
|
||||
|
||||
// Most cat flags (-v, -A, -e, -t, -s, -b, --show-all, etc.) have different
|
||||
@@ -2417,6 +2486,7 @@ mod tests {
|
||||
assert_eq!(
|
||||
safe_rules,
|
||||
vec![
|
||||
"rtk ast-grep",
|
||||
"rtk brew",
|
||||
"rtk bundle",
|
||||
"rtk cargo",
|
||||
@@ -3831,7 +3901,7 @@ mod tests {
|
||||
// A non-excluded inner command still rewrites through the wrapper.
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("uv run head -20 src/main.rs", &["cat".to_string()]),
|
||||
Some("uv run rtk read src/main.rs --max-lines 20".into())
|
||||
Some("uv run rtk read src/main.rs --head-lines 20".into())
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3839,33 +3909,211 @@ mod tests {
|
||||
fn test_head_tail_rewrite_when_not_excluded() {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("head -20 src/main.rs", &["cat".to_string()]),
|
||||
Some("rtk read src/main.rs --max-lines 20".into())
|
||||
Some("rtk read src/main.rs --head-lines 20".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_head_numeric_flag() {
|
||||
// head -20 file → rtk read file --max-lines 20 (not rtk read -20 file)
|
||||
// head -20 file → rtk read file --head-lines 20 (not rtk read -20 file)
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("head -20 src/main.rs", &[]),
|
||||
Some("rtk read src/main.rs --max-lines 20".into())
|
||||
Some("rtk read src/main.rs --head-lines 20".into())
|
||||
);
|
||||
}
|
||||
|
||||
/// A single token that the shell expands into several operands must stay
|
||||
/// native: `rtk read` concatenates files, losing `head`'s `==> name <==`
|
||||
/// banners. Covers the newly added `-n N` / `--lines N` routes, which had
|
||||
/// no matcher at all before and so were native by accident.
|
||||
#[test]
|
||||
fn test_rewrite_head_expanding_operand_stays_native() {
|
||||
for cmd in [
|
||||
"head src/core/*.rs",
|
||||
"head -1 src/core/*.rs",
|
||||
"head -n 1 src/core/*.rs",
|
||||
"head --lines 1 src/core/*.rs",
|
||||
"head --lines=1 src/core/*.rs",
|
||||
"head -n 1 src/core/{a,b}.rs",
|
||||
"head -n 1 $FILES",
|
||||
"head -n 1 src/core/?.rs",
|
||||
] {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes(cmd, &[]),
|
||||
None,
|
||||
"expanding operand must stay native: {}",
|
||||
cmd
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `head -n 1 --help` must reach `head`, not print `rtk read`'s help. The
|
||||
/// quoted and escaped spellings matter as much as the bare one: the matcher
|
||||
/// sees shell source, so `'--'` and `\--help` slip past a leading-`-` test
|
||||
/// while still reaching the tool as options.
|
||||
#[test]
|
||||
fn test_rewrite_head_option_operand_stays_native() {
|
||||
for cmd in [
|
||||
"head -n 1 --help",
|
||||
"head --lines 1 --version",
|
||||
"head --help",
|
||||
"head -n 1 '--'",
|
||||
"head -n 1 \"--\"",
|
||||
"head -n 1 '--help'",
|
||||
"head -n 1 \"--help\"",
|
||||
"head -n 1 \\--help",
|
||||
"head '--'",
|
||||
"head -n 1 #comment",
|
||||
"head #comment",
|
||||
"head -n 1 a|b",
|
||||
"head -n 1 (x)",
|
||||
] {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes(cmd, &[]),
|
||||
None,
|
||||
"option-like operand must stay native: {}",
|
||||
cmd
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The same expansion hazard applied to `tail`, which shared the code path.
|
||||
#[test]
|
||||
fn test_rewrite_tail_expanding_operand_stays_native() {
|
||||
for cmd in [
|
||||
"tail -20 src/core/*.rs",
|
||||
"tail -n 20 src/core/*.rs",
|
||||
"tail --lines 20 $FILES",
|
||||
"tail -n 1 '--'",
|
||||
"tail -n 1 \\--help",
|
||||
"tail -n 1 #comment",
|
||||
] {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes(cmd, &[]),
|
||||
None,
|
||||
"expanding operand must stay native: {}",
|
||||
cmd
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `;` and `&` are operators the lexer splits on before the operand is ever
|
||||
/// examined, so the trailing text is a separate command and the real operand
|
||||
/// is just `f`. These rewrite, and should: the allowlist only has to judge
|
||||
/// characters that survive segmentation.
|
||||
#[test]
|
||||
fn test_rewrite_head_operand_after_operator_split() {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("head -n 1 f;rm", &[]),
|
||||
Some("rtk read f --head-lines 1; rm".into())
|
||||
);
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("head -n 1 a&b", &[]),
|
||||
Some("rtk read a --head-lines 1 & b".into())
|
||||
);
|
||||
}
|
||||
|
||||
/// A trailing redirect is stripped before the operand is judged, so `a>b`
|
||||
/// rewrites with operand `a` — but the suffix must not fuse onto the numeric
|
||||
/// flag value, or the shell reads `1>b` as an fd-1 redirect and
|
||||
/// `--head-lines` loses its argument.
|
||||
#[test]
|
||||
fn test_rewrite_head_redirect_suffix_keeps_flag_value() {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("head -n 1 a>b", &[]),
|
||||
Some("rtk read a --head-lines 1 >b".into())
|
||||
);
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("tail -n 1 a>b", &[]),
|
||||
Some("rtk read a --tail-lines 1 >b".into())
|
||||
);
|
||||
// An already-spaced suffix must not gain a second space.
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("head -n 1 a > b", &[]),
|
||||
Some("rtk read a --head-lines 1 > b".into())
|
||||
);
|
||||
}
|
||||
|
||||
/// Shapes the allowlist must keep accepting, including a non-ASCII name.
|
||||
#[test]
|
||||
fn test_rewrite_head_accepts_ordinary_paths() {
|
||||
for (cmd, want) in [
|
||||
(
|
||||
"head -10 /tmp/seq.txt",
|
||||
"rtk read /tmp/seq.txt --head-lines 10",
|
||||
),
|
||||
("head ./a-b_c.txt", "rtk read ./a-b_c.txt --head-lines 10"),
|
||||
("head ~/x.txt", "rtk read ~/x.txt --head-lines 10"),
|
||||
(
|
||||
"head /tmp/a.b.c-d_e.txt",
|
||||
"rtk read /tmp/a.b.c-d_e.txt --head-lines 10",
|
||||
),
|
||||
(
|
||||
"head src/日本語.rs",
|
||||
"rtk read src/日本語.rs --head-lines 10",
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes(cmd, &[]),
|
||||
Some(want.into()),
|
||||
"must still rewrite: {}",
|
||||
cmd
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_tail_plain_operand_still_rewrites() {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("tail -20 src/main.rs", &[]),
|
||||
Some("rtk read src/main.rs --tail-lines 20".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_head_n_space_flag() {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("head -n 50 src/lib.rs", &[]),
|
||||
Some("rtk read src/lib.rs --head-lines 50".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_head_lines_space_flag() {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("head --lines 50 src/lib.rs", &[]),
|
||||
Some("rtk read src/lib.rs --head-lines 50".into())
|
||||
);
|
||||
}
|
||||
|
||||
/// Multi-file and optioned bare forms stay native: the rewrite emits one
|
||||
/// path (see `is_single_file_operand`), and `head` prints `==> name <==`
|
||||
/// banners for several files, which a concatenated read cannot reproduce.
|
||||
#[test]
|
||||
fn test_rewrite_head_bare_multifile_stays_native() {
|
||||
assert_eq!(rewrite_command_no_prefixes("head a.txt b.txt", &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_head_unsupported_option_stays_native() {
|
||||
assert_eq!(rewrite_command_no_prefixes("head -c 10 f.bin", &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_head_lines_long_flag() {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("head --lines=50 src/lib.rs", &[]),
|
||||
Some("rtk read src/lib.rs --max-lines 50".into())
|
||||
Some("rtk read src/lib.rs --head-lines 50".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_head_no_flag_still_rewrites() {
|
||||
// plain `head file` → `rtk read file` (no numeric flag)
|
||||
// plain `head file` means ten lines, so the rewrite must bound the read
|
||||
// rather than dumping the whole file.
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("head src/main.rs", &[]),
|
||||
Some("rtk read src/main.rs".into())
|
||||
Some("rtk read src/main.rs --head-lines 10".into())
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3925,7 +4173,8 @@ mod tests {
|
||||
|
||||
// --- Issue #1362: head/tail with multiple files falls back to native command ---
|
||||
//
|
||||
// `rtk read <file> --max-lines N` only accepts a single positional file path in
|
||||
// The head/tail rewrite emits a single positional path (see
|
||||
// `is_single_file_operand`), even though `rtk read` itself accepts several, in
|
||||
// a shape that maps cleanly to `head -N`. Rewriting `head -N a b c` to
|
||||
// `rtk read a b c --max-lines N` previously produced a command where `rtk read`
|
||||
// would concatenate the files without the `==> name <==` banners that native
|
||||
|
||||
@@ -147,6 +147,18 @@ pub const RULES: &[RtkRule] = &[
|
||||
savings_pct: 75.0,
|
||||
..RtkRule::DEFAULT
|
||||
},
|
||||
RtkRule {
|
||||
pattern: r"^ast-grep\s+",
|
||||
rtk_cmd: "rtk ast-grep",
|
||||
// Unlike grep/rg, `rtk ast-grep`'s run() execs with stdin null (no
|
||||
// piped-stdin support yet), so it must not be rewritten as a
|
||||
// pipeline's final stage — that would silently drop the pipe input.
|
||||
pipeline_safety: PipelineSafety::ProducerOnly,
|
||||
rewrite_prefixes: &["ast-grep"],
|
||||
category: "Files",
|
||||
savings_pct: 85.0,
|
||||
..RtkRule::DEFAULT
|
||||
},
|
||||
RtkRule {
|
||||
pattern: r"^ls(\s|$)",
|
||||
rtk_cmd: "rtk ls",
|
||||
|
||||
+3
-3
@@ -29,7 +29,7 @@ LLM agent integration layer that installs, validates, and executes command-rewri
|
||||
| Claude-MD (legacy) | `rtk init --claude-md` | 134-line RTK block | CLAUDE.md |
|
||||
| Windsurf | `rtk init -g --agent windsurf` | `.windsurfrules` | -- |
|
||||
| Cline | `rtk init --agent cline` | `.clinerules` | -- |
|
||||
| Codex | `rtk init --codex` | RTK.md in `$CODEX_HOME` or `~/.codex` | AGENTS.md |
|
||||
| Codex | `rtk init --codex` | RTK.md + `.codex/hooks.json` (local) or `$CODEX_HOME/hooks.json` (global) | AGENTS.md + `PreToolUse` hook |
|
||||
| Cursor | `rtk init -g --agent cursor` | Cursor hook | hooks.json |
|
||||
| Pi | `rtk init --agent pi` | `.pi/extensions/rtk.ts` | -- |
|
||||
| Oh My Pi (OMP) | `rtk init --agent omp` | `.omp/extensions/rtk.ts` (shared Pi extension) | -- |
|
||||
@@ -91,14 +91,14 @@ Rules are loaded from all Claude Code `settings.json` files (project + global, i
|
||||
| Cursor (rtk hook cursor) | Ready | `permission: "ask",` — users will be prompted when Cursor enforces the permission; in the meantime, allow |
|
||||
| Gemini CLI (rtk hook gemini) | No (allow/deny only) | allow (limitation — no ask mode in Gemini) |
|
||||
| Copilot CLI (rtk hook copilot) | No updatedInput | deny-with-suggestion (unchanged) |
|
||||
| Codex | ask parsed but no-op | allow (limitation — fails open) |
|
||||
| Codex (`rtk hook codex`) | Native approval runs after rewrite | Emit required protocol `allow` with `updatedInput`; Codex then evaluates the rewritten command normally |
|
||||
| Mistral Vibe (rtk hook vibe) | No native ask surface | passthrough — Vibe's own approval prompt fires on the rewritten command |
|
||||
|
||||
### Implementation
|
||||
|
||||
- `permissions.rs` — loads deny/ask/allow rules, evaluates precedence, returns `PermissionVerdict`
|
||||
- `rewrite_cmd.rs` — maps verdict to exit code (consumed by shell hook)
|
||||
- `hook_cmd.rs` — maps verdict to JSON `permissionDecision` field (Copilot/Gemini)
|
||||
- `hook_cmd.rs` — maps decisions to each agent's JSON protocol, including Codex `updatedInput`
|
||||
|
||||
## Exit Code Contract
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@ pub const BEFORE_TOOL_KEY: &str = "BeforeTool";
|
||||
|
||||
/// Native Rust hook command for Claude Code (replaces rtk-rewrite.sh).
|
||||
pub const CLAUDE_HOOK_COMMAND: &str = "rtk hook claude";
|
||||
/// Native Rust hook command for Codex CLI.
|
||||
pub const CODEX_HOOK_COMMAND: &str = "rtk hook codex";
|
||||
/// Native Rust hook command for Cursor (replaces rtk-rewrite.sh).
|
||||
pub const CURSOR_HOOK_COMMAND: &str = "rtk hook cursor";
|
||||
/// Native Rust hook command for Factory Droid.
|
||||
|
||||
+16
-3
@@ -193,10 +193,9 @@ impl AgentPath {
|
||||
match agent {
|
||||
// `copilot` reads Claude Code's settings rather than a Copilot file
|
||||
// (see `hook_cmd`'s `vscode_response` and `copilot_cli_response`).
|
||||
"antigravity" | "cline" | "codex" | "kilocode" | "kimi" | "windsurf" => {
|
||||
Some(Self::RulesOnly)
|
||||
}
|
||||
"antigravity" | "cline" | "kilocode" | "kimi" | "windsurf" => Some(Self::RulesOnly),
|
||||
"claude" | "copilot" => Some(Self::InProcess(Host::Claude)),
|
||||
"codex" => Some(Self::InProcess(Host::Codex)),
|
||||
"cursor" => Some(Self::InProcess(Host::Cursor)),
|
||||
"droid" => Some(Self::InProcess(Host::Droid)),
|
||||
"gemini" => Some(Self::InProcess(Host::Gemini)),
|
||||
@@ -408,6 +407,20 @@ mod tests {
|
||||
assert!(AgentPath::lookup("Claude").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_uses_shared_decision_without_claiming_permission() {
|
||||
assert!(matches!(
|
||||
AgentPath::lookup("codex"),
|
||||
Some(AgentPath::InProcess(Host::Codex))
|
||||
));
|
||||
assert_eq!(
|
||||
check_command_for("git status", Host::Codex),
|
||||
PermissionVerdict::Default
|
||||
);
|
||||
let (deny, ask, allow) = super::super::permissions::load_rules_for(Host::Codex);
|
||||
assert!(deny.is_empty() && ask.is_empty() && allow.is_empty());
|
||||
}
|
||||
|
||||
/// A rules-file agent has no hook and no permission rules, so its answer
|
||||
/// must not depend on any host's settings.
|
||||
#[test]
|
||||
|
||||
+409
-47
@@ -564,11 +564,34 @@ enum PayloadAction {
|
||||
},
|
||||
Skip {
|
||||
decision: HookOutcome,
|
||||
reason: &'static str,
|
||||
cmd: String,
|
||||
},
|
||||
Ignore,
|
||||
}
|
||||
|
||||
fn pre_tool_use_rewrite_output(
|
||||
v: &Value,
|
||||
rewritten: &str,
|
||||
permission_decision: Option<&str>,
|
||||
) -> Value {
|
||||
let mut updated_input = v.get("tool_input").cloned().unwrap_or_else(|| json!({}));
|
||||
if let Some(obj) = updated_input.as_object_mut() {
|
||||
obj.insert("command".into(), Value::String(rewritten.to_string()));
|
||||
}
|
||||
|
||||
let mut hook_output = json!({
|
||||
"hookEventName": PRE_TOOL_USE_KEY,
|
||||
"permissionDecisionReason": "RTK auto-rewrite",
|
||||
"updatedInput": updated_input
|
||||
});
|
||||
if let Some(decision) = permission_decision {
|
||||
hook_output["permissionDecision"] = Value::String(decision.to_string());
|
||||
}
|
||||
|
||||
json!({ "hookSpecificOutput": hook_output })
|
||||
}
|
||||
|
||||
fn process_claude_payload(v: &Value) -> PayloadAction {
|
||||
let cmd = match v
|
||||
.pointer("/tool_input/command")
|
||||
@@ -595,12 +618,14 @@ fn process_claude_payload_from_decision(
|
||||
HookDecision::Deny => {
|
||||
return PayloadAction::Skip {
|
||||
decision: HookOutcome::Deny,
|
||||
reason: "skip:deny_rule",
|
||||
cmd: cmd.to_string(),
|
||||
}
|
||||
}
|
||||
HookDecision::Defer => {
|
||||
return PayloadAction::Skip {
|
||||
decision: HookOutcome::Defer,
|
||||
reason: "skip:defer",
|
||||
cmd: cmd.to_string(),
|
||||
}
|
||||
}
|
||||
@@ -608,36 +633,15 @@ fn process_claude_payload_from_decision(
|
||||
HookDecision::AskRewrite(r) => (r, false),
|
||||
};
|
||||
|
||||
let updated_input = {
|
||||
let mut ti = v.get("tool_input").cloned().unwrap_or_else(|| json!({}));
|
||||
if let Some(obj) = ti.as_object_mut() {
|
||||
obj.insert("command".into(), Value::String(rewritten.clone()));
|
||||
}
|
||||
ti
|
||||
};
|
||||
|
||||
let mut hook_output = json!({
|
||||
"hookEventName": PRE_TOOL_USE_KEY,
|
||||
"permissionDecisionReason": "RTK auto-rewrite",
|
||||
"updatedInput": updated_input
|
||||
});
|
||||
|
||||
if allow {
|
||||
hook_output
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.insert("permissionDecision".into(), json!("allow"));
|
||||
}
|
||||
|
||||
PayloadAction::Rewrite {
|
||||
cmd: cmd.to_string(),
|
||||
output: pre_tool_use_rewrite_output(v, &rewritten, allow.then_some("allow")),
|
||||
rewritten,
|
||||
decision: if allow {
|
||||
HookOutcome::Allow
|
||||
} else {
|
||||
HookOutcome::Ask
|
||||
},
|
||||
output: json!({ "hookSpecificOutput": hook_output }),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -721,22 +725,20 @@ pub fn run_claude() -> Result<()> {
|
||||
audit_log("rewrite", &cmd, &rewritten);
|
||||
log_hook_decision(&v, &cmd, decision, Some(&rewritten));
|
||||
}
|
||||
PayloadAction::Skip { decision, cmd } => {
|
||||
PayloadAction::Skip {
|
||||
decision,
|
||||
cmd,
|
||||
reason,
|
||||
} => {
|
||||
// `rtk hook audit`'s skip-breakdown groups by a "skip:<reason>" prefix
|
||||
// (see hook_audit_cmd.rs) — Skip is only ever reached via Deny/Defer,
|
||||
// so map those to the reasons it expects rather than the bare
|
||||
// HookOutcome::Display used for the Rewrite/tracking-DB paths.
|
||||
// (see hook_audit_cmd.rs). Carry the reason separately from the
|
||||
// decision so distinct defer causes remain diagnosable.
|
||||
//
|
||||
// Skip has no stdout response to write (Claude Code falls through to
|
||||
// its own native handling), but log_hook_decision is still deferred to
|
||||
// last for the same reason as the Rewrite arm above: it must never be
|
||||
// what a Bash tool call is waiting on.
|
||||
let audit_action = match decision {
|
||||
HookOutcome::Deny => "skip:deny_rule",
|
||||
HookOutcome::Defer => "skip:defer",
|
||||
HookOutcome::Allow | HookOutcome::Ask => "skip",
|
||||
};
|
||||
audit_log(audit_action, &cmd, "");
|
||||
audit_log(reason, &cmd, "");
|
||||
log_hook_decision(&v, &cmd, decision, None);
|
||||
}
|
||||
PayloadAction::Ignore => {}
|
||||
@@ -755,6 +757,146 @@ fn run_claude_inner(input: &str) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Codex CLI native hook ─────────────────────────────────────
|
||||
|
||||
fn is_supported_codex_permission_mode(v: &Value) -> bool {
|
||||
matches!(
|
||||
v.get("permission_mode").and_then(Value::as_str),
|
||||
Some("default" | "acceptEdits" | "plan" | "dontAsk" | "bypassPermissions")
|
||||
)
|
||||
}
|
||||
|
||||
fn process_codex_payload(v: &Value) -> PayloadAction {
|
||||
if v.get("hook_event_name").and_then(Value::as_str) != Some(PRE_TOOL_USE_KEY)
|
||||
|| !matches!(
|
||||
v.get("tool_name").and_then(Value::as_str),
|
||||
Some("Bash" | "bash")
|
||||
)
|
||||
{
|
||||
return PayloadAction::Ignore;
|
||||
}
|
||||
|
||||
let cmd = match v
|
||||
.pointer("/tool_input/command")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|cmd| !cmd.is_empty())
|
||||
{
|
||||
Some(cmd) => cmd,
|
||||
None => return PayloadAction::Ignore,
|
||||
};
|
||||
|
||||
// Codex deliberately includes this field in every hook event. Fail open
|
||||
// for missing or future modes instead of assuming their approval semantics.
|
||||
if !is_supported_codex_permission_mode(v) {
|
||||
return PayloadAction::Skip {
|
||||
decision: HookOutcome::Defer,
|
||||
reason: "skip:unsupported_permission_mode",
|
||||
cmd: cmd.to_string(),
|
||||
};
|
||||
}
|
||||
|
||||
if crate::discover::lexer::contains_unattestable_construct(cmd) {
|
||||
return PayloadAction::Skip {
|
||||
decision: HookOutcome::Defer,
|
||||
reason: "skip:defer",
|
||||
cmd: cmd.to_string(),
|
||||
};
|
||||
}
|
||||
|
||||
process_codex_payload_from_decision(v, cmd, decide_hook_action(cmd, permissions::Host::Codex))
|
||||
}
|
||||
|
||||
fn process_codex_payload_from_decision(
|
||||
v: &Value,
|
||||
cmd: &str,
|
||||
decision: HookDecision,
|
||||
) -> PayloadAction {
|
||||
let (rewritten, outcome) = match decision {
|
||||
HookDecision::AllowRewrite(rewritten) => (rewritten, HookOutcome::Allow),
|
||||
HookDecision::AskRewrite(rewritten) => (rewritten, HookOutcome::Ask),
|
||||
HookDecision::Deny => {
|
||||
return PayloadAction::Skip {
|
||||
decision: HookOutcome::Deny,
|
||||
reason: "skip:deny_rule",
|
||||
cmd: cmd.to_string(),
|
||||
}
|
||||
}
|
||||
HookDecision::Defer => {
|
||||
return PayloadAction::Skip {
|
||||
decision: HookOutcome::Defer,
|
||||
reason: "skip:no_rewrite",
|
||||
cmd: cmd.to_string(),
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Both AllowRewrite and AskRewrite require protocol-level allow: Codex
|
||||
// cannot accept updatedInput with ask or an omitted permissionDecision.
|
||||
// The internal outcome remains Ask for Default, not an RTK auto-approval.
|
||||
// Its runtime applies the replacement before native approval and sandbox
|
||||
// checks, so this is a protocol-level allow rather than RTK approving the
|
||||
// command. Those checks inspect the rewritten argv, however, and Codex's
|
||||
// safe/dangerous-command classifiers do not currently unwrap `rtk`. This
|
||||
// can add prompts for known-safe commands and obscure classifier signals
|
||||
// for wrapped mutating commands such as git push. Keep the passthrough gates
|
||||
// above conservative and revisit this boundary whenever coverage expands.
|
||||
PayloadAction::Rewrite {
|
||||
cmd: cmd.to_string(),
|
||||
output: pre_tool_use_rewrite_output(v, &rewritten, Some("allow")),
|
||||
decision: outcome,
|
||||
rewritten,
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the Codex CLI PreToolUse hook natively.
|
||||
pub fn run_codex() -> Result<()> {
|
||||
let input = match read_stdin_limited() {
|
||||
Ok(input) => input,
|
||||
Err(e) => {
|
||||
let _ = writeln!(io::stderr(), "[rtk hook] Failed to read JSON input: {e}");
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
let input = strip_leading_bom(&input).trim();
|
||||
if input.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let v: Value = match serde_json::from_str(input) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
let _ = writeln!(io::stderr(), "[rtk hook] Failed to parse JSON input: {e}");
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
|
||||
match process_codex_payload(&v) {
|
||||
PayloadAction::Rewrite {
|
||||
cmd,
|
||||
rewritten,
|
||||
output,
|
||||
..
|
||||
} => {
|
||||
audit_log("rewrite", &cmd, &rewritten);
|
||||
let _ = writeln!(io::stdout(), "{output}");
|
||||
}
|
||||
PayloadAction::Skip { cmd, reason, .. } => audit_log(reason, &cmd, ""),
|
||||
PayloadAction::Ignore => {}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn run_codex_inner(input: &str) -> Option<String> {
|
||||
let input = strip_leading_bom(input).trim();
|
||||
let v: Value = serde_json::from_str(input).ok()?;
|
||||
match process_codex_payload(&v) {
|
||||
PayloadAction::Rewrite { output, .. } => Some(output.to_string()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
// ── Cursor native hook ─────────────────────────────────────────
|
||||
|
||||
/// Run the Cursor Agent hook natively.
|
||||
@@ -906,21 +1048,7 @@ fn droid_response_from_decision(v: &Value, cmd: &str, decision: HookDecision) ->
|
||||
|
||||
audit_log("rewrite", cmd, &rewritten);
|
||||
|
||||
let updated_input = {
|
||||
let mut ti = v.get("tool_input").cloned().unwrap_or_else(|| json!({}));
|
||||
if let Some(obj) = ti.as_object_mut() {
|
||||
obj.insert("command".into(), Value::String(rewritten));
|
||||
}
|
||||
ti
|
||||
};
|
||||
|
||||
Some(json!({
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": PRE_TOOL_USE_KEY,
|
||||
"permissionDecisionReason": "RTK auto-rewrite",
|
||||
"updatedInput": updated_input
|
||||
}
|
||||
}))
|
||||
Some(pre_tool_use_rewrite_output(v, &rewritten, None))
|
||||
}
|
||||
|
||||
/// Run the Factory Droid PreToolUse hook natively.
|
||||
@@ -1444,6 +1572,32 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_pre_tool_use_rewrite_output_merges_input_and_optional_decision() {
|
||||
let input = json!({
|
||||
"tool_input": {
|
||||
"command": "git status",
|
||||
"timeout": 30_000,
|
||||
"description": "Inspect the working tree"
|
||||
}
|
||||
});
|
||||
|
||||
let ask = pre_tool_use_rewrite_output(&input, "rtk git status", None);
|
||||
let ask_hook = &ask["hookSpecificOutput"];
|
||||
assert_eq!(ask_hook["hookEventName"], PRE_TOOL_USE_KEY);
|
||||
assert_eq!(ask_hook["permissionDecisionReason"], "RTK auto-rewrite");
|
||||
assert!(ask_hook.get("permissionDecision").is_none());
|
||||
assert_eq!(ask_hook["updatedInput"]["command"], "rtk git status");
|
||||
assert_eq!(ask_hook["updatedInput"]["timeout"], 30_000);
|
||||
assert_eq!(
|
||||
ask_hook["updatedInput"]["description"],
|
||||
"Inspect the working tree"
|
||||
);
|
||||
|
||||
let allow = pre_tool_use_rewrite_output(&input, "rtk git status", Some("allow"));
|
||||
assert_eq!(allow["hookSpecificOutput"]["permissionDecision"], "allow");
|
||||
}
|
||||
|
||||
// --- Claude handler ---
|
||||
|
||||
fn claude_input(cmd: &str) -> String {
|
||||
@@ -1751,6 +1905,214 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
// --- Codex handler ---
|
||||
|
||||
fn codex_input_with_permission_mode(cmd: &str, permission_mode: Option<&str>) -> String {
|
||||
let mut input = json!({
|
||||
"session_id": "session-1",
|
||||
"turn_id": "turn-1",
|
||||
"hook_event_name": PRE_TOOL_USE_KEY,
|
||||
"tool_name": "Bash",
|
||||
"tool_use_id": "tool-1",
|
||||
"tool_input": { "command": cmd }
|
||||
});
|
||||
if let Some(permission_mode) = permission_mode {
|
||||
input["permission_mode"] = json!(permission_mode);
|
||||
}
|
||||
input.to_string()
|
||||
}
|
||||
|
||||
// Normal Codex payloads include `default`; missing permission_mode is
|
||||
// covered deliberately by the dedicated fail-open test below.
|
||||
fn codex_input(cmd: &str) -> String {
|
||||
codex_input_with_permission_mode(cmd, Some("default"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_codex_rewrite_uses_required_allow_shape() {
|
||||
let result = run_codex_inner(&codex_input("git status")).unwrap();
|
||||
let v: Value = serde_json::from_str(&result).unwrap();
|
||||
let hook = &v["hookSpecificOutput"];
|
||||
|
||||
assert_eq!(hook["hookEventName"], PRE_TOOL_USE_KEY);
|
||||
assert_eq!(hook["permissionDecision"], "allow");
|
||||
assert_eq!(hook["permissionDecisionReason"], "RTK auto-rewrite");
|
||||
assert_eq!(hook["updatedInput"]["command"], "rtk git status");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_codex_shared_decision_preserves_host_approval_and_deny() {
|
||||
let input = json!({"tool_input": {"command": "git status", "timeout": 30000}});
|
||||
for (verdict, expected) in [
|
||||
(PermissionVerdict::Default, HookOutcome::Ask),
|
||||
(PermissionVerdict::Ask, HookOutcome::Ask),
|
||||
(PermissionVerdict::Allow, HookOutcome::Allow),
|
||||
] {
|
||||
let decision =
|
||||
super::super::decision::decide_with_params("git status", verdict, &[], &[]);
|
||||
let PayloadAction::Rewrite {
|
||||
output, decision, ..
|
||||
} = process_codex_payload_from_decision(&input, "git status", decision)
|
||||
else {
|
||||
panic!("expected rewrite")
|
||||
};
|
||||
assert_eq!(decision, expected);
|
||||
assert_eq!(output["hookSpecificOutput"]["permissionDecision"], "allow");
|
||||
assert_eq!(
|
||||
output["hookSpecificOutput"]["updatedInput"]["timeout"],
|
||||
30000
|
||||
);
|
||||
assert_eq!(
|
||||
output["hookSpecificOutput"]["updatedInput"]["command"],
|
||||
"rtk git status"
|
||||
);
|
||||
}
|
||||
let denied = super::super::decision::decide_with_params(
|
||||
"git status",
|
||||
PermissionVerdict::Deny,
|
||||
&[],
|
||||
&[],
|
||||
);
|
||||
assert!(matches!(
|
||||
process_codex_payload_from_decision(&input, "git status", denied),
|
||||
PayloadAction::Skip {
|
||||
decision: HookOutcome::Deny,
|
||||
reason: "skip:deny_rule",
|
||||
..
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_codex_skip_reasons_remain_distinct() {
|
||||
for (command, mode, expected) in [
|
||||
("git status", None, "skip:unsupported_permission_mode"),
|
||||
(
|
||||
"git status",
|
||||
Some("futureMode"),
|
||||
"skip:unsupported_permission_mode",
|
||||
),
|
||||
("git status $(whoami)", Some("default"), "skip:defer"),
|
||||
("htop", Some("default"), "skip:no_rewrite"),
|
||||
] {
|
||||
let input: Value =
|
||||
serde_json::from_str(&codex_input_with_permission_mode(command, mode)).unwrap();
|
||||
let PayloadAction::Skip { reason, .. } = process_codex_payload(&input) else {
|
||||
panic!("expected skip for {command}")
|
||||
};
|
||||
assert_eq!(reason, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_codex_rewrites_all_documented_permission_modes() {
|
||||
for permission_mode in [
|
||||
"default",
|
||||
"acceptEdits",
|
||||
"plan",
|
||||
"dontAsk",
|
||||
"bypassPermissions",
|
||||
] {
|
||||
assert!(
|
||||
run_codex_inner(&codex_input_with_permission_mode(
|
||||
"git status",
|
||||
Some(permission_mode)
|
||||
))
|
||||
.is_some(),
|
||||
"documented permission mode should rewrite: {permission_mode}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_codex_unknown_or_missing_permission_mode_passes_through() {
|
||||
assert!(run_codex_inner(&codex_input_with_permission_mode("git status", None)).is_none());
|
||||
assert!(run_codex_inner(&codex_input_with_permission_mode(
|
||||
"git status",
|
||||
Some("futureMode")
|
||||
))
|
||||
.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_codex_rewrites_commands_that_still_need_native_approval() {
|
||||
let result = run_codex_inner(&codex_input("cargo test")).unwrap();
|
||||
let v: Value = serde_json::from_str(&result).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
v.pointer("/hookSpecificOutput/updatedInput/command"),
|
||||
Some(&json!("rtk cargo test"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_codex_rewrite_preserves_tool_input_fields() {
|
||||
let input = json!({
|
||||
"hook_event_name": PRE_TOOL_USE_KEY,
|
||||
"tool_name": "Bash",
|
||||
"permission_mode": "default",
|
||||
"tool_input": {
|
||||
"command": "git status --short",
|
||||
"timeout": 30_000,
|
||||
"description": "Inspect the working tree"
|
||||
}
|
||||
})
|
||||
.to_string();
|
||||
let result = run_codex_inner(&input).unwrap();
|
||||
let v: Value = serde_json::from_str(&result).unwrap();
|
||||
let updated = &v["hookSpecificOutput"]["updatedInput"];
|
||||
|
||||
assert_eq!(updated["command"], "rtk git status --short");
|
||||
assert_eq!(updated["timeout"], 30_000);
|
||||
assert_eq!(updated["description"], "Inspect the working tree");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_codex_ignores_other_events_and_tools() {
|
||||
let other_event = json!({
|
||||
"hook_event_name": "PostToolUse",
|
||||
"tool_name": "Bash",
|
||||
"tool_input": { "command": "git status" }
|
||||
})
|
||||
.to_string();
|
||||
let other_tool = json!({
|
||||
"hook_event_name": PRE_TOOL_USE_KEY,
|
||||
"tool_name": "apply_patch",
|
||||
"tool_input": { "command": "git status" }
|
||||
})
|
||||
.to_string();
|
||||
|
||||
assert!(run_codex_inner(&other_event).is_none());
|
||||
assert!(run_codex_inner(&other_tool).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_codex_passthrough_for_unsupported_or_unattestable_commands() {
|
||||
assert!(run_codex_inner(&codex_input("rtk git status")).is_none());
|
||||
assert!(run_codex_inner(&codex_input("htop")).is_none());
|
||||
assert!(run_codex_inner(&codex_input("rm -rf /tmp/rtk-safety-test")).is_none());
|
||||
assert!(run_codex_inner(&codex_input("sudo rm -rf /tmp/rtk-safety-test")).is_none());
|
||||
assert!(run_codex_inner(&codex_input("git status > /tmp/status")).is_none());
|
||||
assert!(run_codex_inner(&codex_input("git status $(touch /tmp/x)")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_codex_rewrites_compound_command_directly() {
|
||||
let result = run_codex_inner(&codex_input("git add . && cargo test")).unwrap();
|
||||
let v: Value = serde_json::from_str(&result).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
v.pointer("/hookSpecificOutput/updatedInput/command"),
|
||||
Some(&json!("rtk git add . && rtk cargo test"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_codex_malformed_json_and_empty_command_pass_through() {
|
||||
assert!(run_codex_inner("not valid json {{{").is_none());
|
||||
assert!(run_codex_inner(&codex_input("")).is_none());
|
||||
}
|
||||
|
||||
// --- Cursor handler ---
|
||||
|
||||
fn cursor_input(cmd: &str) -> String {
|
||||
|
||||
+711
-137
File diff suppressed because it is too large.
Load diff
+34
-4
@@ -17,15 +17,26 @@ pub mod rewrite_cmd;
|
||||
pub mod trust;
|
||||
pub mod verify_cmd;
|
||||
|
||||
pub fn is_claude_hook_command(command: &str) -> bool {
|
||||
fn is_rtk_binary(binary: &str) -> bool {
|
||||
let binary_name = binary.rsplit(['/', '\\']).next().unwrap_or(binary);
|
||||
matches!(binary_name, "rtk" | "rtk.exe")
|
||||
}
|
||||
|
||||
fn is_rtk_hook_command(command: &str, agent: &str) -> bool {
|
||||
let parts = crate::discover::lexer::shell_split(command);
|
||||
let [binary, hook, claude] = parts.as_slice() else {
|
||||
let [parsed_binary, hook, target] = parts.as_slice() else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let binary_name = binary.rsplit(['/', '\\']).next().unwrap_or(binary);
|
||||
is_rtk_binary(parsed_binary) && hook == "hook" && target == agent
|
||||
}
|
||||
|
||||
binary_name == "rtk" && hook == "hook" && claude == "claude"
|
||||
pub fn is_claude_hook_command(command: &str) -> bool {
|
||||
is_rtk_hook_command(command, "claude")
|
||||
}
|
||||
|
||||
pub fn is_codex_hook_command(command: &str) -> bool {
|
||||
is_rtk_hook_command(command, "codex")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -39,6 +50,9 @@ mod tests {
|
||||
assert!(is_claude_hook_command(
|
||||
"\"/opt/homebrew/bin/rtk\" hook claude"
|
||||
));
|
||||
assert!(is_claude_hook_command(
|
||||
"/Users/jane/My\\ Apps/rtk hook claude"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -47,4 +61,20 @@ mod tests {
|
||||
assert!(!is_claude_hook_command("/opt/homebrew/bin/rtk hook cursor"));
|
||||
assert!(!is_claude_hook_command("echo rtk hook claude"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_hook_command_matches_bare_absolute_and_windows_rtk() {
|
||||
assert!(is_codex_hook_command("rtk hook codex"));
|
||||
assert!(is_codex_hook_command("/opt/homebrew/bin/rtk hook codex"));
|
||||
assert!(is_codex_hook_command(
|
||||
"\"C:\\Program Files\\rtk.exe\" hook codex"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_hook_command_rejects_other_commands() {
|
||||
assert!(!is_codex_hook_command("rtk hook claude"));
|
||||
assert!(!is_codex_hook_command("echo rtk hook codex"));
|
||||
assert!(!is_codex_hook_command("\"rtk\"evil hook codex"));
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,7 @@ pub fn check_command(cmd: &str) -> PermissionVerdict {
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Host {
|
||||
Claude,
|
||||
Codex,
|
||||
Cursor,
|
||||
Gemini,
|
||||
Droid,
|
||||
@@ -57,7 +58,11 @@ pub(crate) fn load_rules_for(host: Host) -> (Vec<String>, Vec<String>, Vec<Strin
|
||||
Host::Cursor => load_cursor_rules(),
|
||||
Host::Gemini => load_gemini_rules(),
|
||||
Host::Droid => load_droid_rules(),
|
||||
Host::Vibe => (Vec::new(), Vec::new(), Vec::new()),
|
||||
// Hosts with no RTK-side rule source. Codex enforces its native
|
||||
// execution rules after updatedInput. Do not interpret either host's
|
||||
// rules as Claude Bash patterns or borrow another host's settings.
|
||||
// No RTK-side match means Default, not an explicit Allow.
|
||||
Host::Codex | Host::Vibe => (Vec::new(), Vec::new(), Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+53
-9
@@ -24,8 +24,8 @@ use cmds::ruby::{rake_cmd, rspec_cmd, rubocop_cmd};
|
||||
use cmds::rust::{cargo_cmd, runner};
|
||||
use cmds::scala::sbt_cmd;
|
||||
use cmds::system::{
|
||||
ctest_cmd, deps, env_cmd, find_cmd, format_cmd, json_cmd, local_llm, log_cmd, ls, pipe_cmd,
|
||||
read, search, summary, tree, wc_cmd,
|
||||
ast_grep_cmd, ctest_cmd, deps, env_cmd, find_cmd, format_cmd, json_cmd, local_llm, log_cmd, ls,
|
||||
pipe_cmd, read, search, summary, tree, wc_cmd,
|
||||
};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
@@ -111,11 +111,16 @@ enum Commands {
|
||||
/// Filter: none (default, full content), minimal, aggressive
|
||||
#[arg(short, long, default_value = "none")]
|
||||
level: core::filter::FilterLevel,
|
||||
/// Max lines
|
||||
#[arg(short, long, conflicts_with = "tail_lines")]
|
||||
/// Structural preview capped at N lines (keeps signatures and imports;
|
||||
/// not the first N lines — use --head-lines for that)
|
||||
#[arg(short, long, conflicts_with_all = ["head_lines", "tail_lines"])]
|
||||
max_lines: Option<usize>,
|
||||
/// Keep only the first N lines (byte-exact at the default --level none
|
||||
/// with -n off; --level and -n still transform the window)
|
||||
#[arg(long, conflicts_with_all = ["max_lines", "tail_lines"])]
|
||||
head_lines: Option<usize>,
|
||||
/// Keep only last N lines
|
||||
#[arg(long, conflicts_with = "max_lines")]
|
||||
#[arg(long, conflicts_with_all = ["max_lines", "head_lines"])]
|
||||
tail_lines: Option<usize>,
|
||||
/// Show line numbers
|
||||
#[arg(short = 'n', long)]
|
||||
@@ -355,6 +360,13 @@ enum Commands {
|
||||
extra_args: Vec<String>,
|
||||
},
|
||||
|
||||
/// Compact ast-grep - runs ast-grep natively, groups matches by file
|
||||
AstGrep {
|
||||
/// ast-grep subcommand, pattern, path, and any flags (e.g. run -p '$$$', --json)
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
extra_args: Vec<String>,
|
||||
},
|
||||
|
||||
/// Initialize rtk instructions for assistant CLI usage
|
||||
Init {
|
||||
/// Add to global assistant config directory instead of local project file
|
||||
@@ -405,7 +417,7 @@ enum Commands {
|
||||
#[arg(long)]
|
||||
uninstall: bool,
|
||||
|
||||
/// Target Codex CLI (uses AGENTS.md + RTK.md, no Claude hook patching)
|
||||
/// Target Codex CLI (uses PreToolUse hook + AGENTS.md + RTK.md)
|
||||
#[arg(long)]
|
||||
codex: bool,
|
||||
|
||||
@@ -953,6 +965,8 @@ enum Commands {
|
||||
enum HookCommands {
|
||||
/// Process Claude Code PreToolUse hook (reads JSON from stdin)
|
||||
Claude,
|
||||
/// Process Codex CLI PreToolUse hook (reads JSON from stdin)
|
||||
Codex,
|
||||
/// Process Cursor Agent hook (reads JSON from stdin)
|
||||
Cursor,
|
||||
/// Process Gemini CLI BeforeTool hook (reads JSON from stdin)
|
||||
@@ -1848,8 +1862,11 @@ fn run_cli() -> Result<i32> {
|
||||
};
|
||||
|
||||
// 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 { .. }) {
|
||||
// Skip for Gain (shows its own inline warning), Init/Verify (manage the hook themselves).
|
||||
if !matches!(
|
||||
cli.command,
|
||||
Commands::Gain { .. } | Commands::Init { .. } | Commands::Verify { .. }
|
||||
) {
|
||||
hooks::hook_check::maybe_warn();
|
||||
}
|
||||
|
||||
@@ -1870,6 +1887,7 @@ fn run_cli() -> Result<i32> {
|
||||
files,
|
||||
level,
|
||||
max_lines,
|
||||
head_lines,
|
||||
tail_lines,
|
||||
line_numbers,
|
||||
} => {
|
||||
@@ -1882,12 +1900,20 @@ fn run_cli() -> Result<i32> {
|
||||
continue;
|
||||
}
|
||||
stdin_seen = true;
|
||||
read::run_stdin(level, max_lines, tail_lines, line_numbers, cli.verbose)
|
||||
read::run_stdin(
|
||||
level,
|
||||
max_lines,
|
||||
head_lines,
|
||||
tail_lines,
|
||||
line_numbers,
|
||||
cli.verbose,
|
||||
)
|
||||
} else {
|
||||
read::run(
|
||||
file,
|
||||
level,
|
||||
max_lines,
|
||||
head_lines,
|
||||
tail_lines,
|
||||
line_numbers,
|
||||
cli.verbose,
|
||||
@@ -2248,6 +2274,7 @@ fn run_cli() -> Result<i32> {
|
||||
&extra_args,
|
||||
cli.verbose,
|
||||
)?,
|
||||
Commands::AstGrep { extra_args } => ast_grep_cmd::run(&extra_args)?,
|
||||
Commands::Rg { extra_args } => {
|
||||
search::run(search::Engine::Rg, 80, 200, false, &extra_args, cli.verbose)?
|
||||
}
|
||||
@@ -2768,6 +2795,10 @@ fn run_cli() -> Result<i32> {
|
||||
hooks::hook_cmd::run_claude()?;
|
||||
0
|
||||
}
|
||||
HookCommands::Codex => {
|
||||
hooks::hook_cmd::run_codex()?;
|
||||
0
|
||||
}
|
||||
HookCommands::Cursor => {
|
||||
hooks::hook_cmd::run_cursor()?;
|
||||
0
|
||||
@@ -3117,6 +3148,7 @@ fn is_operational_command(cmd: &Commands) -> bool {
|
||||
| Commands::Summary { .. }
|
||||
| Commands::Grep { .. }
|
||||
| Commands::Rg { .. }
|
||||
| Commands::AstGrep { .. }
|
||||
| Commands::Wget { .. }
|
||||
| Commands::Vitest { .. }
|
||||
| Commands::Ctest { .. }
|
||||
@@ -3590,6 +3622,7 @@ mod tests {
|
||||
"tree",
|
||||
"read",
|
||||
"rg",
|
||||
"ast-grep",
|
||||
"git",
|
||||
"gh",
|
||||
"glab",
|
||||
@@ -3716,6 +3749,17 @@ mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hook_codex_parses() {
|
||||
let cli = Cli::try_parse_from(["rtk", "hook", "codex"]).unwrap();
|
||||
assert!(matches!(
|
||||
cli.command,
|
||||
Commands::Hook {
|
||||
command: HookCommands::Codex
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hook_check_parses() {
|
||||
let cli = Cli::try_parse_from(["rtk", "hook", "check", "git", "status"]).unwrap();
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
//! Regression test for the missing `restore_double_dash` call in dotnet_cmd.rs
|
||||
//! (see run_dotnet_with_binlog/run_format): without it, `inject_report_trx_into_args`
|
||||
//! can't tell "the user passed no `--`" from "the user passed `--` but clap's
|
||||
//! trailing_var_arg stripped it". Since args then look like `["FullyQualifiedName=MyFilter"]`
|
||||
//! (no `--` at all), it appends a *fresh* `-- --report-trx` at the end instead of reusing the
|
||||
//! user's own `--` — landing the user's MTP-runtime filter expression BEFORE the separator
|
||||
//! (misread as a `dotnet test` CLI arg) instead of after it, and stranding `--report-trx` with
|
||||
//! nothing following it.
|
||||
//!
|
||||
//! Stubs `dotnet` on PATH with a script that records its argv, since the real
|
||||
//! dotnet SDK isn't available in this environment.
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn dotnet_test_reuses_users_double_dash_for_report_trx_injection() {
|
||||
use std::process::Command;
|
||||
|
||||
fn shell_quote(path: &std::path::Path) -> String {
|
||||
format!("'{}'", path.display().to_string().replace('\'', "'\\''"))
|
||||
}
|
||||
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let argv_file = dir.path().join("argv.txt");
|
||||
let stub_path = dir.path().join("dotnet");
|
||||
|
||||
// --report-trx is only injected after `--` in VsTestBridge mode (detect_test_runner_mode),
|
||||
// which requires a project file with UseMicrosoftTestingPlatformRunner/UseTestingPlatformRunner.
|
||||
std::fs::write(
|
||||
dir.path().join("MyProject.csproj"),
|
||||
r#"<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>
|
||||
</PropertyGroup>
|
||||
</Project>"#,
|
||||
)
|
||||
.expect("write csproj");
|
||||
|
||||
std::fs::write(
|
||||
&stub_path,
|
||||
format!(
|
||||
"#!/bin/sh\nprintf '%s\\n' \"$@\" > {}\nexit 0\n",
|
||||
shell_quote(&argv_file)
|
||||
),
|
||||
)
|
||||
.expect("write stub");
|
||||
let mut perms = std::fs::metadata(&stub_path)
|
||||
.expect("stat stub")
|
||||
.permissions();
|
||||
std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o755);
|
||||
std::fs::set_permissions(&stub_path, perms).expect("chmod stub");
|
||||
|
||||
let path_with_stub = format!(
|
||||
"{}:{}",
|
||||
dir.path().display(),
|
||||
std::env::var("PATH").unwrap_or_default()
|
||||
);
|
||||
|
||||
let out = Command::new(env!("CARGO_BIN_EXE_rtk"))
|
||||
.env("PATH", path_with_stub)
|
||||
.current_dir(dir.path())
|
||||
.args(["dotnet", "test", "--", "FullyQualifiedName=MyFilter"])
|
||||
.output()
|
||||
.expect("spawn rtk");
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"rtk dotnet test failed: stdout={} stderr={}",
|
||||
String::from_utf8_lossy(&out.stdout),
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
|
||||
let argv: Vec<String> = std::fs::read_to_string(&argv_file)
|
||||
.expect("read captured argv")
|
||||
.lines()
|
||||
.map(str::to_string)
|
||||
.collect();
|
||||
|
||||
let dashdash_count = argv.iter().filter(|a| a.as_str() == "--").count();
|
||||
assert_eq!(
|
||||
dashdash_count, 1,
|
||||
"the user's -- must be reused, not duplicated: {argv:?}"
|
||||
);
|
||||
|
||||
let sep = argv.iter().position(|a| a == "--").expect("has --");
|
||||
assert_eq!(
|
||||
argv.get(sep + 1).map(String::as_str),
|
||||
Some("--report-trx"),
|
||||
"--report-trx should be injected right after the user's --: {argv:?}"
|
||||
);
|
||||
|
||||
let filter_pos = argv
|
||||
.iter()
|
||||
.position(|a| a == "FullyQualifiedName=MyFilter")
|
||||
.expect("filter expression present");
|
||||
assert!(
|
||||
filter_pos > sep,
|
||||
"the user's filter expression must stay AFTER --, not be pulled before it \
|
||||
when clap's stripped -- gets a fresh one appended at the end: {argv:?}"
|
||||
);
|
||||
}
|
||||
+3674
File diff suppressed because it is too large.
Load diff
+387
@@ -0,0 +1,387 @@
|
||||
src/learn/detector.rs:51:static UNKNOWN_FLAG_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/learn/detector.rs:52: Regex::new(
|
||||
src/learn/detector.rs:53: r"(?i)(unexpected argument|unknown (option|flag)|unrecognized (option|flag)|invalid (option|flag))"
|
||||
src/learn/detector.rs:54: ).unwrap()
|
||||
src/learn/detector.rs:55:});
|
||||
src/learn/detector.rs:57:static CMD_NOT_FOUND_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/learn/detector.rs:58: Regex::new(
|
||||
src/learn/detector.rs:59: r"(?i)(command not found|not recognized as an internal|no such file or directory.*command)",
|
||||
src/learn/detector.rs:60: )
|
||||
src/learn/detector.rs:61: .unwrap()
|
||||
src/learn/detector.rs:62:});
|
||||
src/learn/detector.rs:64:static WRONG_PATH_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/learn/detector.rs:65: Regex::new(r"(?i)(no such file or directory|cannot find the path|file not found)").unwrap()
|
||||
src/learn/detector.rs:66:});
|
||||
src/learn/detector.rs:68:static MISSING_ARG_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/learn/detector.rs:69: Regex::new(
|
||||
src/learn/detector.rs:70: r"(?i)(requires a value|requires an argument|missing (required )?argument|expected.*argument)"
|
||||
src/learn/detector.rs:71: ).unwrap()
|
||||
src/learn/detector.rs:72:});
|
||||
src/learn/detector.rs:75: LazyLock::new(|| Regex::new(r"(?i)(permission denied|access denied|not permitted)").unwrap());
|
||||
src/learn/detector.rs:78:static USER_REJECTION_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/learn/detector.rs:79: Regex::new(
|
||||
src/learn/detector.rs:80: r"(?i)(user (doesn't want|declined|rejected|cancelled)|operation (cancelled|aborted) by user)"
|
||||
src/learn/detector.rs:81: ).unwrap()
|
||||
src/learn/detector.rs:82:});
|
||||
src/cmds/git/gh_cmd.rs:16:static HTML_COMMENT_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?s)<!--.*?-->").unwrap());
|
||||
src/cmds/git/gh_cmd.rs:18: LazyLock::new(|| Regex::new(r"(?m)^\s*\[!\[[^\]]*\]\([^)]*\)\]\([^)]*\)\s*$").unwrap());
|
||||
src/cmds/git/gh_cmd.rs:20: LazyLock::new(|| Regex::new(r"(?m)^\s*!\[[^\]]*\]\([^)]*\)\s*$").unwrap());
|
||||
src/cmds/git/gh_cmd.rs:22: LazyLock::new(|| Regex::new(r"(?m)^\s*(?:---+|\*\*\*+|___+)\s*$").unwrap());
|
||||
src/cmds/git/gh_cmd.rs:23:static MULTI_BLANK_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\n{3,}").unwrap());
|
||||
src/cmds/system/ctest_cmd.rs:24:static TEST_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/system/ctest_cmd.rs:25: Regex::new(
|
||||
src/cmds/system/ctest_cmd.rs:26: r"(?s)^\s*(?:\d+/(\d+)\s+)?Test\s+#(\d+):\s+(.+?)\s+\.{2,}\s*(?:\*{3})?\s*(.+?)\s+([\d.]+)\s+sec\s*$",
|
||||
src/cmds/system/ctest_cmd.rs:27: )
|
||||
src/cmds/system/ctest_cmd.rs:28: .expect("invalid ctest result regex")
|
||||
src/cmds/system/ctest_cmd.rs:29:});
|
||||
src/cmds/system/ctest_cmd.rs:30:static RESULT_PREFIX_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/system/ctest_cmd.rs:31: Regex::new(r"^\s*(?:\d+/\d+\s+)?Test\s+#\d+:")
|
||||
src/cmds/system/ctest_cmd.rs:32: .expect("invalid ctest result prefix regex")
|
||||
src/cmds/system/ctest_cmd.rs:33:});
|
||||
src/cmds/system/ctest_cmd.rs:34:static RESULT_TERMINATOR_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/system/ctest_cmd.rs:35: Regex::new(r"[\d.]+\s+sec\s*$").expect("invalid ctest result terminator regex")
|
||||
src/cmds/system/ctest_cmd.rs:36:});
|
||||
src/cmds/system/ctest_cmd.rs:37:static START_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/system/ctest_cmd.rs:38: Regex::new(r"^\s*Start\s+(\d+):\s*(.*?)\s*$").expect("invalid ctest start regex")
|
||||
src/cmds/system/ctest_cmd.rs:39:});
|
||||
src/cmds/system/ctest_cmd.rs:40:static SUMMARY_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/system/ctest_cmd.rs:41: Regex::new(r"^\s*\d+%\s+tests passed,\s+(\d+)\s+tests failed out of\s+(\d+)")
|
||||
src/cmds/system/ctest_cmd.rs:42: .expect("invalid ctest summary regex")
|
||||
src/cmds/system/ctest_cmd.rs:43:});
|
||||
src/cmds/system/ctest_cmd.rs:44:static TIME_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/system/ctest_cmd.rs:45: Regex::new(r"^\s*Total Test time \(real\)\s+=\s+([\d.]+)\s+sec")
|
||||
src/cmds/system/ctest_cmd.rs:46: .expect("invalid ctest time regex")
|
||||
src/cmds/system/ctest_cmd.rs:47:});
|
||||
src/cmds/git/glab_cmd.rs:23:static HTML_COMMENT_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?s)<!--.*?-->").unwrap());
|
||||
src/cmds/git/glab_cmd.rs:25: LazyLock::new(|| Regex::new(r"(?m)^\s*\[!\[[^\]]*\]\([^)]*\)\]\([^)]*\)\s*$").unwrap());
|
||||
src/cmds/git/glab_cmd.rs:27: LazyLock::new(|| Regex::new(r"(?m)^\s*!\[[^\]]*\]\([^)]*\)\s*$").unwrap());
|
||||
src/cmds/git/glab_cmd.rs:29: LazyLock::new(|| Regex::new(r"(?m)^\s*(?:---+|\*\*\*+|___+)\s*$").unwrap());
|
||||
src/cmds/git/glab_cmd.rs:30:static MULTI_BLANK_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\n{3,}").unwrap());
|
||||
src/cmds/git/glab_cmd.rs:32: LazyLock::new(|| Regex::new(r"/-/merge_requests/(\d+)").unwrap());
|
||||
src/cmds/git/glab_cmd.rs:34:static SECTION_MARKER_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/git/glab_cmd.rs:35: Regex::new(r"section_(?:start|end):\d+:[a-z0-9_]+(?:\x1b\[0K|\[0K)*").unwrap()
|
||||
src/cmds/git/glab_cmd.rs:36:});
|
||||
src/cmds/git/glab_cmd.rs:38:static BARE_ANSI_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\[[\d;]+[A-Za-z]").unwrap());
|
||||
src/cmds/ruby/rake_cmd.rs:168: LazyLock::new(|| regex::Regex::new(r"^\d+\)\s+(Failure|Error):$").unwrap());
|
||||
src/cmds/system/ls.rs:14:static LS_DATE_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/system/ls.rs:15: Regex::new(
|
||||
src/cmds/system/ls.rs:16: r"\s+(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+\d{1,2}\s+(?:\d{4}|\d{2}:\d{2})\s+"
|
||||
src/cmds/system/ls.rs:17: )
|
||||
src/cmds/system/ls.rs:18: .unwrap()
|
||||
src/cmds/system/ls.rs:19:});
|
||||
src/cmds/git/gt_cmd.rs:13: LazyLock::new(|| Regex::new(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b").unwrap());
|
||||
src/cmds/git/gt_cmd.rs:14:static BRANCH_NAME_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/git/gt_cmd.rs:15: Regex::new(
|
||||
src/cmds/git/gt_cmd.rs:16: r#"(?:Created|Pushed|pushed|Deleted|deleted)\s+branch\s+[`"']?([a-zA-Z0-9/_.\-+@]+)"#,
|
||||
src/cmds/git/gt_cmd.rs:17: )
|
||||
src/cmds/git/gt_cmd.rs:18: .unwrap()
|
||||
src/cmds/git/gt_cmd.rs:19:});
|
||||
src/cmds/git/gt_cmd.rs:20:static PR_LINE_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/git/gt_cmd.rs:21: Regex::new(r"(Created|Updated)\s+pull\s+request\s+#(\d+)\s+for\s+([^\s:]+)(?::\s*(\S+))?")
|
||||
src/cmds/git/gt_cmd.rs:22: .unwrap()
|
||||
src/cmds/git/gt_cmd.rs:23:});
|
||||
src/cmds/system/search.rs:739: LazyLock::new(|| Regex::new(r"^([^\x00]+)\x00(\d+)([:-])(.*)$").unwrap());
|
||||
src/discover/registry.rs:54:static REGEX_SET: LazyLock<RegexSet> = LazyLock::new(|| {
|
||||
src/discover/registry.rs:55: RegexSet::new(RULES.iter().map(|r| r.pattern)).expect("invalid regex patterns")
|
||||
src/discover/registry.rs:56:});
|
||||
src/discover/registry.rs:57:static COMPILED: LazyLock<Vec<Regex>> = LazyLock::new(|| {
|
||||
src/discover/registry.rs:58: RULES
|
||||
src/discover/registry.rs:59: .iter()
|
||||
src/discover/registry.rs:60: .map(|r| Regex::new(r.pattern).expect("invalid regex"))
|
||||
src/discover/registry.rs:61: .collect()
|
||||
src/discover/registry.rs:62:});
|
||||
src/discover/registry.rs:63:static ENV_PREFIX: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/discover/registry.rs:64: let double_quoted = r#""(?:[^"\\]|\\.)*""#;
|
||||
src/discover/registry.rs:65: let single_quoted = r#"'(?:[^'\\]|\\.)*'"#;
|
||||
src/discover/registry.rs:66: let unquoted = r#"[^\s]*"#;
|
||||
src/discover/registry.rs:67: let env_value = format!("(?:{}|{}|{})", double_quoted, single_quoted, unquoted);
|
||||
src/discover/registry.rs:68: let env_assign = format!(r#"[A-Z_][A-Z0-9_]*={}"#, env_value);
|
||||
src/discover/registry.rs:69: Regex::new(&format!(r#"^(?:sudo\s+|env\s+|{}\s+)+"#, env_assign)).unwrap()
|
||||
src/discover/registry.rs:70:});
|
||||
src/discover/registry.rs:73:static GIT_GLOBAL_OPT: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/discover/registry.rs:74: Regex::new(r"^(?:(?:-C\s+\S+|-c\s+\S+|--git-dir(?:=\S+|\s+\S+)|--work-tree(?:=\S+|\s+\S+)|--no-pager|--no-optional-locks|--bare|--literal-pathspecs)\s+)+").unwrap()
|
||||
src/discover/registry.rs:75:});
|
||||
src/discover/registry.rs:80:static HEAD_N: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^head\s+-(\d+)\s+(\S+)$").unwrap());
|
||||
src/discover/registry.rs:82: LazyLock::new(|| Regex::new(r"^head\s+--lines=(\d+)\s+(\S+)$").unwrap());
|
||||
src/discover/registry.rs:83:static TAIL_N: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^tail\s+-(\d+)\s+(\S+)$").unwrap());
|
||||
src/discover/registry.rs:85: LazyLock::new(|| Regex::new(r"^tail\s+-n\s+(\d+)\s+(\S+)$").unwrap());
|
||||
src/discover/registry.rs:87: LazyLock::new(|| Regex::new(r"^tail\s+--lines=(\d+)\s+(\S+)$").unwrap());
|
||||
src/discover/registry.rs:89: LazyLock::new(|| Regex::new(r"^tail\s+--lines\s+(\d+)\s+(\S+)$").unwrap());
|
||||
src/discover/registry.rs:539: LazyLock::new(|| Regex::new(r"(?m)[ \t\x0B\x0C]*\\\r?\n[ \t\x0B\x0C]*").unwrap());
|
||||
src/discover/registry.rs:541:static BASH_JOIN_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\\\r?\n").unwrap());
|
||||
src/cmds/system/log_cmd.rs:14:static TIMESTAMP_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/system/log_cmd.rs:15: Regex::new(r"^\d{4}[-/]\d{2}[-/]\d{2}[T ]\d{2}:\d{2}:\d{2}[.,]?\d*\s*").unwrap()
|
||||
src/cmds/system/log_cmd.rs:16:});
|
||||
src/cmds/system/log_cmd.rs:17:static UUID_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/system/log_cmd.rs:18: Regex::new(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")
|
||||
src/cmds/system/log_cmd.rs:19: .unwrap()
|
||||
src/cmds/system/log_cmd.rs:20:});
|
||||
src/cmds/system/log_cmd.rs:21:static HEX_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"0x[0-9a-fA-F]+").unwrap());
|
||||
src/cmds/system/log_cmd.rs:22:static NUM_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\b\d{4,}\b").unwrap());
|
||||
src/cmds/system/log_cmd.rs:23:static PATH_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"/[\w./\-]+").unwrap());
|
||||
src/cmds/ruby/rspec_cmd.rs:22: LazyLock::new(|| Regex::new(r"(?i)running via spring preloader").unwrap());
|
||||
src/cmds/ruby/rspec_cmd.rs:23:static RE_SIMPLECOV: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/ruby/rspec_cmd.rs:24: Regex::new(r"(?i)(coverage report|simplecov|coverage/|\.simplecov|All Files.*Lines)").unwrap()
|
||||
src/cmds/ruby/rspec_cmd.rs:25:});
|
||||
src/cmds/ruby/rspec_cmd.rs:27: LazyLock::new(|| Regex::new(r"^DEPRECATION WARNING:").unwrap());
|
||||
src/cmds/ruby/rspec_cmd.rs:28:static RE_FINISHED_IN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^Finished in \d").unwrap());
|
||||
src/cmds/ruby/rspec_cmd.rs:30: LazyLock::new(|| Regex::new(r"saved screenshot to (.+)").unwrap());
|
||||
src/cmds/ruby/rspec_cmd.rs:32: LazyLock::new(|| Regex::new(r"(\d+) examples?, (\d+) failures?").unwrap());
|
||||
src/cmds/js/playwright_cmd.rs:168: LazyLock::new(|| Regex::new(r"(\d+)\s+(passed|failed|flaky|skipped)").unwrap());
|
||||
src/cmds/js/playwright_cmd.rs:170: LazyLock::new(|| Regex::new(r"\((\d+(?:\.\d+)?)(ms|s|m)\)").unwrap());
|
||||
src/cmds/js/playwright_cmd.rs:220: LazyLock::new(|| Regex::new(r"[×✗]\s+.*?›\s+([^›]+\.spec\.[tj]sx?)").unwrap());
|
||||
src/cmds/js/next_cmd.rs:45: static BUNDLE_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/js/next_cmd.rs:46: Regex::new(r"^[○●◐λ✓]\s+([\w/\-\.]+)\s+(\d+(?:\.\d+)?)\s*(kB|B)\s+(\d+(?:\.\d+)?)\s*(kB|B)")
|
||||
src/cmds/js/next_cmd.rs:47: .unwrap()
|
||||
src/cmds/js/next_cmd.rs:48: });
|
||||
src/cmds/js/next_cmd.rs:172: LazyLock::new(|| Regex::new(r"(\d+(?:\.\d+)?)\s*(s|ms)").unwrap());
|
||||
src/cmds/php/artisan_cmd.rs:8:static BOX_CHARS_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/php/artisan_cmd.rs:9: Regex::new(r"[\u{2500}-\u{257F}\u{2580}-\u{259F}\u{25A0}-\u{25FF}\u{27A0}-\u{27BF}]+").unwrap()
|
||||
src/cmds/php/artisan_cmd.rs:10:});
|
||||
src/cmds/php/artisan_cmd.rs:11:static DOTS_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\.{3,}").unwrap());
|
||||
src/cmds/php/artisan_cmd.rs:12:static MULTI_SPACE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[ \t]{2,}").unwrap());
|
||||
src/cmds/php/artisan_cmd.rs:13:static MULTI_BLANK_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\n{3,}").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:13:static TASK_LINE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^> Task :").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:15: LazyLock::new(|| Regex::new(r"^\* Try:|^> Run with --|^> Get more help at").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:17: LazyLock::new(|| Regex::new(r"^BUILD (SUCCESSFUL|FAILED)").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:19: LazyLock::new(|| Regex::new(r"^\d+ actionable tasks?").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:180: static DAEMON_LINE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/jvm/gradlew_cmd.rs:181: Regex::new(
|
||||
src/cmds/jvm/gradlew_cmd.rs:182: r"^(Starting a Gradle Daemon|Daemon will be stopped|Reusing configuration cache|Calculating task graph|> Configure project|Deprecated Gradle features|You can use|For more on this|Configuration cache entry)"
|
||||
src/cmds/jvm/gradlew_cmd.rs:183: )
|
||||
src/cmds/jvm/gradlew_cmd.rs:184: .unwrap()
|
||||
src/cmds/jvm/gradlew_cmd.rs:185: });
|
||||
src/cmds/jvm/gradlew_cmd.rs:186: static PROGRESS: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/jvm/gradlew_cmd.rs:187: Regex::new(r"^\s*\d+%|^Downloading|^Configuring|^Resolving|^\[Incubating\]|^Wrote HTML report|^class \S+ could not|^\[android-")
|
||||
src/cmds/jvm/gradlew_cmd.rs:188: .unwrap()
|
||||
src/cmds/jvm/gradlew_cmd.rs:189: });
|
||||
src/cmds/jvm/gradlew_cmd.rs:190: static ERROR_LINE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/jvm/gradlew_cmd.rs:191: Regex::new(
|
||||
src/cmds/jvm/gradlew_cmd.rs:192: r"(?i)(^FAILURE:|^\* What went wrong:|^\* Where:|> Could not|e: |error:|^Execution failed|Lint found \d+ error)"
|
||||
src/cmds/jvm/gradlew_cmd.rs:193: )
|
||||
src/cmds/jvm/gradlew_cmd.rs:194: .unwrap()
|
||||
src/cmds/jvm/gradlew_cmd.rs:195: });
|
||||
src/cmds/jvm/gradlew_cmd.rs:198: LazyLock::new(|| Regex::new(r"^(w: |warning:|Warning:|WARNING:)").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:200: LazyLock::new(|| Regex::new(r"gradle\.com/s/|Publishing build scan").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:234: LazyLock::new(|| Regex::new(r"FAILED$| FAILED ").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:236: LazyLock::new(|| Regex::new(r" PASSED$| SKIPPED$").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:237: static SUMMARY_LINE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/jvm/gradlew_cmd.rs:238: Regex::new(
|
||||
src/cmds/jvm/gradlew_cmd.rs:239: r"\d+ tests? completed|\d+ tests? failed|There were failing tests|See the report at",
|
||||
src/cmds/jvm/gradlew_cmd.rs:240: )
|
||||
src/cmds/jvm/gradlew_cmd.rs:241: .unwrap()
|
||||
src/cmds/jvm/gradlew_cmd.rs:242: });
|
||||
src/cmds/jvm/gradlew_cmd.rs:312: LazyLock::new(|| Regex::new(r"^INSTRUMENTATION_STATUS[_CODE]*:").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:314: LazyLock::new(|| Regex::new(r"^INSTRUMENTATION_RESULT:").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:316: LazyLock::new(|| Regex::new(r"^INSTRUMENTATION_CODE:").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:318: LazyLock::new(|| Regex::new(r"^Starting \d+ tests? on ").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:320: LazyLock::new(|| Regex::new(r"^Installing APK").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:363: LazyLock::new(|| Regex::new(r"[^:]+:\d+:.*[Ee]rror:.*\[").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:366: LazyLock::new(|| Regex::new(r"[^:]+:\d+:.*[Ww]arning:.*\[").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:369: LazyLock::new(|| Regex::new(r"[^:]+:\d+:\d+:.*[Ll]int").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:372: LazyLock::new(|| Regex::new(r"[^:]+:\d+:\d+:.*error").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:375: LazyLock::new(|| Regex::new(r"\d+ (issues?|errors?|warnings?)").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:377: static REPORT_LINE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/jvm/gradlew_cmd.rs:378: Regex::new(r"Wrote (HTML|XML|text) report|file://|/build/reports/lint").unwrap()
|
||||
src/cmds/jvm/gradlew_cmd.rs:379: });
|
||||
src/cmds/php/utils.rs:7:static ANSI_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\x1b\[[0-9;]*[A-Za-z]").unwrap());
|
||||
src/cmds/php/utils.rs:9: LazyLock::new(|| Regex::new(r"[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]").unwrap());
|
||||
src/cmds/cloud/psql_cmd.rs:17: LazyLock::new(|| Regex::new(r"-\[ RECORD \d+ \]-").unwrap());
|
||||
src/cmds/cloud/psql_cmd.rs:18:static SEPARATOR: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[-+]+$").unwrap());
|
||||
src/cmds/cloud/psql_cmd.rs:19:static ROW_COUNT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\(\d+ rows?\)$").unwrap());
|
||||
src/cmds/cloud/psql_cmd.rs:21: LazyLock::new(|| Regex::new(r"^-\[ RECORD (\d+) \]-").unwrap());
|
||||
src/cmds/php/phpunit_cmd.rs:20:static FAILURE_HEADING_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\d+\) \S").unwrap());
|
||||
src/cmds/rust/runner.rs:13:static ERROR_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
|
||||
src/cmds/rust/runner.rs:14: vec![
|
||||
src/cmds/rust/runner.rs:15: // Generic errors
|
||||
src/cmds/rust/runner.rs:16: Regex::new(r"(?i)^.*error[\s:\[].*$").unwrap(),
|
||||
src/cmds/rust/runner.rs:17: Regex::new(r"(?i)^.*\berr\b.*$").unwrap(),
|
||||
src/cmds/rust/runner.rs:18: Regex::new(r"(?i)^.*warning[\s:\[].*$").unwrap(),
|
||||
src/cmds/rust/runner.rs:19: Regex::new(r"(?i)^.*\bwarn\b.*$").unwrap(),
|
||||
src/cmds/rust/runner.rs:20: Regex::new(r"(?i)^.*failed.*$").unwrap(),
|
||||
src/cmds/rust/runner.rs:21: Regex::new(r"(?i)^.*failure.*$").unwrap(),
|
||||
src/cmds/rust/runner.rs:22: Regex::new(r"(?i)^.*exception.*$").unwrap(),
|
||||
src/cmds/rust/runner.rs:23: Regex::new(r"(?i)^.*panic.*$").unwrap(),
|
||||
src/cmds/rust/runner.rs:24: // Rust specific
|
||||
src/cmds/rust/runner.rs:25: Regex::new(r"^error\[E\d+\]:.*$").unwrap(),
|
||||
src/cmds/rust/runner.rs:26: Regex::new(r"^\s*--> .*:\d+:\d+$").unwrap(),
|
||||
src/cmds/rust/runner.rs:27: // Python
|
||||
src/cmds/rust/runner.rs:28: Regex::new(r"^Traceback.*$").unwrap(),
|
||||
src/cmds/rust/runner.rs:29: Regex::new(r#"^\s*File ".*", line \d+.*$"#).unwrap(),
|
||||
src/cmds/rust/runner.rs:30: // JavaScript/TypeScript
|
||||
src/cmds/rust/runner.rs:31: Regex::new(r"^\s*at .*:\d+:\d+.*$").unwrap(),
|
||||
src/cmds/rust/runner.rs:32: // Go
|
||||
src/cmds/rust/runner.rs:33: Regex::new(r"^.*\.go:\d+:.*$").unwrap(),
|
||||
src/cmds/rust/runner.rs:34: ]
|
||||
src/cmds/rust/runner.rs:35:});
|
||||
src/cmds/js/vitest_cmd.rs:121: LazyLock::new(|| Regex::new(r"Tests\s+(?:(\d+)\s+failed\s+\|\s+)?(\d+)\s+passed").unwrap());
|
||||
src/cmds/js/vitest_cmd.rs:123: LazyLock::new(|| Regex::new(r"Duration\s+([\d.]+)(ms|s)").unwrap());
|
||||
src/cmds/dotnet/binlog.rs:55:static ISSUE_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/dotnet/binlog.rs:56: Regex::new(
|
||||
src/cmds/dotnet/binlog.rs:57: r"(?m)^\s*(?P<file>[^\r\n:(]+)\((?P<line>\d+),(?P<column>\d+)\):\s*(?P<kind>error|warning)\s*(?:(?P<code>[A-Za-z]+\d+)\s*:\s*)?(?P<msg>.*)$"
|
||||
src/cmds/dotnet/binlog.rs:58: )
|
||||
src/cmds/dotnet/binlog.rs:59: .expect("valid regex")
|
||||
src/cmds/dotnet/binlog.rs:60:});
|
||||
src/cmds/dotnet/binlog.rs:61:static BUILD_SUMMARY_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/dotnet/binlog.rs:62: Regex::new(r"(?mi)^\s*(?P<count>\d+)\s+(?P<kind>warning|error)\(s\)").expect("valid regex")
|
||||
src/cmds/dotnet/binlog.rs:63:});
|
||||
src/cmds/dotnet/binlog.rs:65: LazyLock::new(|| Regex::new(r"(?i)\b(?P<count>\d+)\s+error\(s\)").expect("valid regex"));
|
||||
src/cmds/dotnet/binlog.rs:67: LazyLock::new(|| Regex::new(r"(?i)\b(?P<count>\d+)\s+warning\(s\)").expect("valid regex"));
|
||||
src/cmds/dotnet/binlog.rs:68:static FALLBACK_ERROR_LINE_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/dotnet/binlog.rs:69: Regex::new(r"(?mi)^.+\(\d+,\d+\):\s*error(?:\s+[A-Za-z]{2,}\d{3,})?(?:\s*:.*)?$")
|
||||
src/cmds/dotnet/binlog.rs:70: .expect("valid regex")
|
||||
src/cmds/dotnet/binlog.rs:71:});
|
||||
src/cmds/dotnet/binlog.rs:72:static FALLBACK_WARNING_LINE_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/dotnet/binlog.rs:73: Regex::new(r"(?mi)^.+\(\d+,\d+\):\s*warning(?:\s+[A-Za-z]{2,}\d{3,})?(?:\s*:.*)?$")
|
||||
src/cmds/dotnet/binlog.rs:74: .expect("valid regex")
|
||||
src/cmds/dotnet/binlog.rs:75:});
|
||||
src/cmds/dotnet/binlog.rs:76:static DURATION_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/dotnet/binlog.rs:77: Regex::new(r"(?m)^\s*Time Elapsed\s+(?P<duration>[^\r\n]+)$").expect("valid regex")
|
||||
src/cmds/dotnet/binlog.rs:78:});
|
||||
src/cmds/dotnet/binlog.rs:79:static TEST_RESULT_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/dotnet/binlog.rs:80: Regex::new(
|
||||
src/cmds/dotnet/binlog.rs:81: r"(?m)(?:Passed!|Failed!)\s*-\s*Failed:\s*(?P<failed>\d+),\s*Passed:\s*(?P<passed>\d+),\s*Skipped:\s*(?P<skipped>\d+),\s*Total:\s*(?P<total>\d+),\s*Duration:\s*(?P<duration>[^\r\n-]+)"
|
||||
src/cmds/dotnet/binlog.rs:82: )
|
||||
src/cmds/dotnet/binlog.rs:83: .expect("valid regex")
|
||||
src/cmds/dotnet/binlog.rs:84:});
|
||||
src/cmds/dotnet/binlog.rs:85:static TEST_SUMMARY_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/dotnet/binlog.rs:86: Regex::new(
|
||||
src/cmds/dotnet/binlog.rs:87: r"(?mi)^\s*Test summary:\s*total:\s*(?P<total>\d+),\s*failed:\s*(?P<failed>\d+),\s*(?:succeeded|passed):\s*(?P<passed>\d+),\s*skipped:\s*(?P<skipped>\d+),\s*duration:\s*(?P<duration>[^\r\n]+)$"
|
||||
src/cmds/dotnet/binlog.rs:88: )
|
||||
src/cmds/dotnet/binlog.rs:89: .expect("valid regex")
|
||||
src/cmds/dotnet/binlog.rs:90:});
|
||||
src/cmds/dotnet/binlog.rs:91:static FAILED_TEST_HEAD_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/dotnet/binlog.rs:92: Regex::new(r"(?m)^\s*Failed\s+(?P<name>[^\r\n\[]+)\s+\[[^\]\r\n]+\]\s*$").expect("valid regex")
|
||||
src/cmds/dotnet/binlog.rs:93:});
|
||||
src/cmds/dotnet/binlog.rs:95: LazyLock::new(|| Regex::new(r"(?m)^\s*Restored\s+.+\.csproj\s*\(").expect("valid regex"));
|
||||
src/cmds/dotnet/binlog.rs:96:static RESTORE_DIAGNOSTIC_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/dotnet/binlog.rs:97: Regex::new(
|
||||
src/cmds/dotnet/binlog.rs:98: r"(?mi)^\s*(?:(?P<file>.+?)\s+:\s+)?(?P<kind>warning|error)\s+(?P<code>[A-Za-z]{2,}\d{3,})\s*:\s*(?P<msg>.+)$"
|
||||
src/cmds/dotnet/binlog.rs:99: )
|
||||
src/cmds/dotnet/binlog.rs:100: .expect("valid regex")
|
||||
src/cmds/dotnet/binlog.rs:101:});
|
||||
src/cmds/dotnet/binlog.rs:102:static PROJECT_PATH_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/dotnet/binlog.rs:103: Regex::new(r"(?m)^\s*([A-Za-z]:)?[^\r\n]*\.csproj(?:\s|$)").expect("valid regex")
|
||||
src/cmds/dotnet/binlog.rs:104:});
|
||||
src/cmds/dotnet/binlog.rs:106: LazyLock::new(|| Regex::new(r"[\x20-\x7E]{5,}").expect("valid regex"));
|
||||
src/cmds/dotnet/binlog.rs:108: LazyLock::new(|| Regex::new(r"^[A-Za-z]{2,}\d{3,}$").expect("valid regex"));
|
||||
src/cmds/dotnet/binlog.rs:110: LazyLock::new(|| Regex::new(r"(?i)([A-Za-z]:)?[/\\][^\s]+\.(cs|vb|fs)").expect("valid regex"));
|
||||
src/cmds/dotnet/binlog.rs:111:static SENSITIVE_ENV_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/dotnet/binlog.rs:112: let keys = SENSITIVE_ENV_VARS
|
||||
src/cmds/dotnet/binlog.rs:113: .iter()
|
||||
src/cmds/dotnet/binlog.rs:114: .map(|key| regex::escape(key))
|
||||
src/cmds/dotnet/binlog.rs:115: .collect::<Vec<_>>()
|
||||
src/cmds/dotnet/binlog.rs:116: .join("|");
|
||||
src/cmds/dotnet/binlog.rs:117: Regex::new(&format!(
|
||||
src/cmds/dotnet/binlog.rs:118: r"(?P<prefix>\b(?:{})\s*(?:=|:)\s*)(?P<value>[^\s;]+)",
|
||||
src/cmds/dotnet/binlog.rs:119: keys
|
||||
src/cmds/dotnet/binlog.rs:120: ))
|
||||
src/cmds/dotnet/binlog.rs:121: .expect("valid regex")
|
||||
src/cmds/dotnet/binlog.rs:122:});
|
||||
src/cmds/jvm/mvn_cmd.rs:34:static RUNNING: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\[INFO\] Running ").unwrap());
|
||||
src/cmds/jvm/mvn_cmd.rs:45: LazyLock::new(|| Regex::new(r"^\[INFO\] Running \S+\s*$").unwrap());
|
||||
src/cmds/jvm/mvn_cmd.rs:55:static CLOSE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/jvm/mvn_cmd.rs:56: Regex::new(
|
||||
src/cmds/jvm/mvn_cmd.rs:57: r"^\[(?:INFO|ERROR|WARNING)\] Tests run: \d+, Failures: (\d+), Errors: (\d+), Skipped: \d+, Time elapsed: [^ ]+ s(?:\s+<<<\s*(?:FAILURE|ERROR)!)?\s+--?\s+in (.+)$"
|
||||
src/cmds/jvm/mvn_cmd.rs:58: ).unwrap()
|
||||
src/cmds/jvm/mvn_cmd.rs:59:});
|
||||
src/cmds/jvm/mvn_cmd.rs:63: LazyLock::new(|| Regex::new(r"^\[(?:INFO|ERROR)\] BUILD (?:SUCCESS|FAILURE)$").unwrap());
|
||||
src/cmds/jvm/mvn_cmd.rs:66:static RESULTS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\[INFO\] Results:\s*$").unwrap());
|
||||
src/cmds/jvm/mvn_cmd.rs:69:static AGG: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/jvm/mvn_cmd.rs:70: Regex::new(r"^\[(?:INFO|ERROR)\] Tests run: \d+, Failures: \d+, Errors: \d+, Skipped: \d+\s*$")
|
||||
src/cmds/jvm/mvn_cmd.rs:71: .unwrap()
|
||||
src/cmds/jvm/mvn_cmd.rs:72:});
|
||||
src/cmds/jvm/mvn_cmd.rs:76: LazyLock::new(|| Regex::new(r"^\[INFO\] --- .* @ .* ---$").unwrap());
|
||||
src/cmds/jvm/mvn_cmd.rs:109:static TEST_PLUGIN_BANNER: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/jvm/mvn_cmd.rs:110: Regex::new(r"^\[INFO\] --- (?:maven-)?(surefire|failsafe)(?:-plugin)?:\S+ \([^)]*\) @ .* ---$")
|
||||
src/cmds/jvm/mvn_cmd.rs:111: .unwrap()
|
||||
src/cmds/jvm/mvn_cmd.rs:112:});
|
||||
src/cmds/jvm/mvn_cmd.rs:125: LazyLock::new(|| Regex::new(r"^\[INFO\] Building .*\[\d+/\d+\]\s*$").unwrap());
|
||||
src/cmds/jvm/mvn_cmd.rs:129: LazyLock::new(|| Regex::new(r"^\[INFO\] -+< .+ >-+$").unwrap());
|
||||
src/cmds/jvm/mvn_cmd.rs:134: LazyLock::new(|| Regex::new(r"^\[INFO\] Reactor Summary for ").unwrap());
|
||||
src/cmds/jvm/mvn_cmd.rs:138: LazyLock::new(|| Regex::new(r"/[^:]+\.java:\[\d+,\d+\]").unwrap());
|
||||
src/cmds/php/phpt_cmd.rs:163: static STATUS_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/php/phpt_cmd.rs:164: // Matches a status line. Anchor: either start-of-line ("FAIL desc [x.phpt]")
|
||||
src/cmds/php/phpt_cmd.rs:165: // or immediately after the test bracket ("TEST N/M [x.phpt]PASS desc [x.phpt]").
|
||||
src/cmds/php/phpt_cmd.rs:166: // We only accept the token after `]` or at line start so that prose like
|
||||
src/cmds/php/phpt_cmd.rs:167: // "FAILED TEST SUMMARY" does not match.
|
||||
src/cmds/php/phpt_cmd.rs:168: Regex::new(
|
||||
src/cmds/php/phpt_cmd.rs:169: r"(?:^|\])(PASS|FAIL|SKIP|BORK|WARN|XLEAK|LEAK|XFAIL)\s+(.*?)\s*\[([^\[\]]+\.phpt)\]",
|
||||
src/cmds/php/phpt_cmd.rs:170: )
|
||||
src/cmds/php/phpt_cmd.rs:171: .unwrap()
|
||||
src/cmds/php/phpt_cmd.rs:172: });
|
||||
src/cmds/php/phpt_cmd.rs:173: static STAT_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/php/phpt_cmd.rs:174: Regex::new(
|
||||
src/cmds/php/phpt_cmd.rs:175: r"^\s*(Tests passed|Tests failed|Tests skipped|Tests warned|Expected fail|Expected leak|Tests leaked|Tests borked)\s*:\s*(\d+)",
|
||||
src/cmds/php/phpt_cmd.rs:176: )
|
||||
src/cmds/php/phpt_cmd.rs:177: .unwrap()
|
||||
src/cmds/php/phpt_cmd.rs:178: });
|
||||
src/cmds/php/phpt_cmd.rs:180: LazyLock::new(|| Regex::new(r"^\s*Number of tests\s*:\s*(\d+)").unwrap());
|
||||
src/cmds/php/phpt_cmd.rs:182: LazyLock::new(|| Regex::new(r"^\s*Time taken\s*:\s*([0-9.]+)").unwrap());
|
||||
src/cmds/cloud/aws_cmd.rs:1327: LazyLock::new(|| Regex::new(r"^(upload|download|delete|copy|move):").unwrap());
|
||||
src/cmds/js/tsc_cmd.rs:22:static TSC_ERROR: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/js/tsc_cmd.rs:23: Regex::new(r"^(.+?)\((\d+),(\d+)\):\s+(error|warning)\s+(TS\d+):\s+(.+)$").unwrap()
|
||||
src/cmds/js/tsc_cmd.rs:24:});
|
||||
src/cmds/js/tsc_cmd.rs:26:static TSC_PRETTY_ERROR: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/js/tsc_cmd.rs:27: Regex::new(r"^(.+?):(\d+):(\d+)\s+-\s+(error|warning)\s+(TS\d+):\s+(.+)$").unwrap()
|
||||
src/cmds/js/tsc_cmd.rs:28:});
|
||||
src/cmds/js/tsc_cmd.rs:30: LazyLock::new(|| Regex::new(r"^(error|warning)\s+(TS\d+):\s+(.+)$").unwrap());
|
||||
src/core/utils.rs:54: LazyLock::new(|| Regex::new(r"\x1b\[[0-9;]*[a-zA-Z]").unwrap());
|
||||
src/cmds/python/uv_cmd.rs:20: LazyLock::new(|| Regex::new(r#"^\s*File ".*", line \d+.*$"#).unwrap());
|
||||
src/cmds/python/uv_cmd.rs:22: LazyLock::new(|| Regex::new(r"^\s*[A-Za-z_][A-Za-z0-9_.]*(?:Error|Exception):").unwrap());
|
||||
src/cmds/python/uv_cmd.rs:24: LazyLock::new(|| Regex::new(r"^\s*at .+:\d+:\d+.*$").unwrap());
|
||||
src/cmds/python/uv_cmd.rs:25:static ERROR_START_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
|
||||
src/cmds/python/uv_cmd.rs:26: vec![
|
||||
src/cmds/python/uv_cmd.rs:27: Regex::new(r"(?i)\berror\b").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:28: Regex::new(r"(?i)\bfailed\b").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:29: Regex::new(r"(?i)\bfailure\b").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:30: Regex::new(r"(?i)\bexception\b").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:31: Regex::new(r"(?i)\bpanic\b").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:32: Regex::new(r"(?i)\bwarn(?:ing)?\b").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:33: Regex::new(r"(?i)\bassert(?:ion)?\b").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:34: Regex::new(r"^\s*FAILED\b").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:35: Regex::new(r"^\s*ERROR\b").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:36: Regex::new(r"^\s*E\s+").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:37: Regex::new(r"^\s*Caused by:").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:38: Regex::new(r"^\s*note:").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:39: Regex::new(r"^\s*help:").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:40: ]
|
||||
src/cmds/python/uv_cmd.rs:41:});
|
||||
src/core/filter.rs:158:static MULTIPLE_BLANK_LINES: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\n{3,}").unwrap());
|
||||
src/core/filter.rs:233: LazyLock::new(|| Regex::new(r"^(use |import |from |require\(|#include)").unwrap());
|
||||
src/core/filter.rs:234:static FUNC_SIGNATURE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/core/filter.rs:235: Regex::new(
|
||||
src/core/filter.rs:236: r"^(pub\s+)?(async\s+)?(fn|def|function|func|class|struct|enum|trait|interface|type)\s+\w+",
|
||||
src/core/filter.rs:237: )
|
||||
src/core/filter.rs:238: .unwrap()
|
||||
src/core/filter.rs:239:});
|
||||
src/cmds/rust/cargo_cmd.rs:1050: static RE: LazyLock<regex::Regex> = LazyLock::new(|| {
|
||||
src/cmds/rust/cargo_cmd.rs:1051: regex::Regex::new(
|
||||
src/cmds/rust/cargo_cmd.rs:1052: r"test result: (\w+)\.\s+(\d+) passed;\s+(\d+) failed;\s+(\d+) ignored;\s+(\d+) measured;\s+(\d+) filtered out(?:;\s+finished in ([\d.]+)s)?"
|
||||
src/cmds/rust/cargo_cmd.rs:1053: ).unwrap()
|
||||
src/cmds/rust/cargo_cmd.rs:1054: });
|
||||
src/cmds/python/mypy_cmd.rs:57: static MYPY_DIAG: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/python/mypy_cmd.rs:58: Regex::new(r"^(.+?):(\d+)(?::\d+)?: (error|warning|note): (.+?)(?:\s+\[(.+)\])?$").unwrap()
|
||||
src/cmds/python/mypy_cmd.rs:59: });
|
||||
src/cmds/scala/sbt_cmd.rs:10:static TEST_SUMMARY_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/scala/sbt_cmd.rs:11: Regex::new(
|
||||
src/cmds/scala/sbt_cmd.rs:12: r"Tests: succeeded (\d+), failed (\d+), canceled (\d+), ignored (\d+), pending (\d+)",
|
||||
src/cmds/scala/sbt_cmd.rs:13: )
|
||||
src/cmds/scala/sbt_cmd.rs:14: .unwrap()
|
||||
src/cmds/scala/sbt_cmd.rs:15:});
|
||||
src/cmds/scala/sbt_cmd.rs:20:static MUNIT_SUMMARY_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/scala/sbt_cmd.rs:21: Regex::new(r"^\[info\] (?:Passed|Failed): Total \d+, Failed (\d+), Errors (\d+), Passed (\d+)")
|
||||
src/cmds/scala/sbt_cmd.rs:22: .unwrap()
|
||||
src/cmds/scala/sbt_cmd.rs:23:});
|
||||
src/cmds/scala/sbt_cmd.rs:28: LazyLock::new(|| Regex::new(r"Suites: completed (\d+), aborted (\d+)").unwrap());
|
||||
src/cmds/scala/sbt_cmd.rs:32: LazyLock::new(|| Regex::new(r"Run completed in (\d+) seconds?").unwrap());
|
||||
src/cmds/scala/sbt_cmd.rs:36: LazyLock::new(|| Regex::new(r"\[info\] Compiling (\d+) Scala source").unwrap());
|
||||
src/cmds/scala/sbt_cmd.rs:40: LazyLock::new(|| Regex::new(r"\[success\] Total time: (\d+) s").unwrap());
|
||||
src/cmds/scala/sbt_cmd.rs:43:static ERROR_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\[error\]").unwrap());
|
||||
src/cmds/scala/sbt_cmd.rs:46:static NOISE_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/scala/sbt_cmd.rs:47: Regex::new(
|
||||
src/cmds/scala/sbt_cmd.rs:48: r"^\[info\] (welcome to sbt|loading |set current project|Updating |Resolved |Fetching |downloading |Done )"
|
||||
src/cmds/scala/sbt_cmd.rs:49: ).unwrap()
|
||||
src/cmds/scala/sbt_cmd.rs:50:});
|
||||
src/core/toml_filter.rs:399:static REGISTRY: LazyLock<TomlFilterRegistry> = LazyLock::new(TomlFilterRegistry::load);
|
||||
src/core/toml_filter.rs:422:static MATCH_SET: LazyLock<RegexSet> = LazyLock::new(build_match_set);
|
||||
@@ -0,0 +1,139 @@
|
||||
//! `gh pr checks` exits non-zero as a normal result: 1 when a check failed, 8 while
|
||||
//! checks are still pending. Its stdout is complete and valid in both cases, so
|
||||
//! skipping the filter there dropped the whole table on the user exactly when they
|
||||
//! were asking why CI was red. These pin that the summary survives a non-zero exit
|
||||
//! without swallowing the exit code, the diagnostics on stderr, or a check row.
|
||||
|
||||
#![cfg(unix)]
|
||||
|
||||
use std::fs;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Output};
|
||||
|
||||
/// Writes an executable `name` in `dir` that runs `body`.
|
||||
fn fake_tool(dir: &Path, name: &str, body: &str) {
|
||||
let path = dir.join(name);
|
||||
fs::write(&path, format!("#!/bin/sh\n{}\n", body)).expect("write fake tool");
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).expect("chmod fake tool");
|
||||
}
|
||||
|
||||
/// Runs rtk with `dir` first on PATH, so the fake tool shadows any real one.
|
||||
fn rtk_with(dir: &Path, args: &[&str]) -> Output {
|
||||
let path = format!(
|
||||
"{}:{}",
|
||||
dir.display(),
|
||||
std::env::var("PATH").unwrap_or_default()
|
||||
);
|
||||
Command::new(env!("CARGO_BIN_EXE_rtk"))
|
||||
.args(args)
|
||||
.env("PATH", path)
|
||||
.output()
|
||||
.expect("run rtk")
|
||||
}
|
||||
|
||||
/// A `gh` whose `pr checks` prints `table` and exits `code`, the way it does when
|
||||
/// checks failed (1) or are still running (8).
|
||||
fn fake_gh(dir: &Path, table: &str, code: i32) {
|
||||
let path = dir.join("checks.txt");
|
||||
fs::write(&path, table).expect("write table");
|
||||
fake_tool(dir, "gh", &format!("cat {}\nexit {}", path.display(), code));
|
||||
}
|
||||
|
||||
/// Rows as `gh` 2.46 prints them: tab-separated name, state, elapsed, url, description.
|
||||
const RED_TABLE: &str = "doc review\tfail\t13s\thttps://example.test/job/1\t\n\
|
||||
fmt\tfail\t7s\thttps://example.test/job/2\t\n\
|
||||
Analyze (rust)\tpass\t4m17s\thttps://example.test/job/3\t\n\
|
||||
check\tpass\t5s\thttps://example.test/job/4\t\n";
|
||||
|
||||
#[test]
|
||||
fn failing_checks_are_summarised_not_dumped_raw() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
fake_gh(dir.path(), RED_TABLE, 1);
|
||||
|
||||
let out = rtk_with(dir.path(), &["gh", "pr", "checks", "123"]);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
|
||||
assert!(
|
||||
stdout.contains("CI Checks Summary:"),
|
||||
"filter must run on a non-zero exit, got:\n{stdout}"
|
||||
);
|
||||
assert!(stdout.contains("Passed: 2"), "got:\n{stdout}");
|
||||
assert!(stdout.contains("Failed: 2"), "got:\n{stdout}");
|
||||
assert!(
|
||||
stdout.contains("doc review") && stdout.contains("fmt"),
|
||||
"the failed checks are the reason the user ran this, got:\n{stdout}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_red_run_still_propagates_the_exit_code() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
fake_gh(dir.path(), RED_TABLE, 1);
|
||||
|
||||
let out = rtk_with(dir.path(), &["gh", "pr", "checks", "123"]);
|
||||
assert_eq!(out.status.code(), Some(1), "gh's exit code must survive");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_checks_are_counted_and_exit_eight_survives() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
fake_gh(
|
||||
dir.path(),
|
||||
"test (ubuntu)\tpending\t0\thttps://example.test/job/5\t\n\
|
||||
test (macos)\tpending\t0\thttps://example.test/job/6\t\n\
|
||||
test (windows)\tpending\t0\thttps://example.test/job/7\t\n\
|
||||
clippy\tpass\t31s\thttps://example.test/job/8\t\n",
|
||||
8,
|
||||
);
|
||||
|
||||
let out = rtk_with(dir.path(), &["gh", "pr", "checks", "123"]);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
assert!(stdout.contains("Pending: 3"), "got:\n{stdout}");
|
||||
assert_eq!(out.status.code(), Some(8), "gh exits 8 while checks pend");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancelled_run_does_not_read_as_nothing_wrong() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
fake_gh(
|
||||
dir.path(),
|
||||
"build\tcancelled\t45s\thttps://example.test/job/1\t\n\
|
||||
test (ubuntu)\tcancelled\t44s\thttps://example.test/job/2\t\n\
|
||||
Security Scan\tskipping\t0\thttps://example.test/job/3\t\n",
|
||||
1,
|
||||
);
|
||||
|
||||
let out = rtk_with(dir.path(), &["gh", "pr", "checks", "123"]);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
|
||||
assert!(
|
||||
stdout.contains("Skipped/cancelled: 3"),
|
||||
"a cancelled run must not summarise to all zeros, got:\n{stdout}"
|
||||
);
|
||||
assert_eq!(out.status.code(), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_error_with_empty_stdout_does_not_become_an_all_zero_summary() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
fake_tool(
|
||||
dir.path(),
|
||||
"gh",
|
||||
"echo 'GraphQL: Could not resolve to a Repository' >&2\nexit 1",
|
||||
);
|
||||
|
||||
let out = rtk_with(dir.path(), &["gh", "pr", "checks", "123"]);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
|
||||
assert!(
|
||||
!stdout.contains("Passed: 0"),
|
||||
"a failed lookup must not read as a PR with zero checks, got:\n{stdout}"
|
||||
);
|
||||
assert!(
|
||||
stderr.contains("Could not resolve to a Repository"),
|
||||
"the real diagnostic must reach the user, got:\n{stderr}"
|
||||
);
|
||||
assert_eq!(out.status.code(), Some(1));
|
||||
}
|
||||
@@ -212,6 +212,141 @@ fn git_log_dash_p_pathspec_after_double_dash_is_not_patch_flag() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_show_dash_dash_stat_pathspec_after_double_dash_is_not_stat_flag() {
|
||||
// Regression: `rtk git show -- --stat` must not be misread as a request for the real
|
||||
// `--stat` summary flag. Before restore_double_dash + arg_tokenizer, run_show's
|
||||
// wants_stat_only check was a raw `arg == "--stat"` scan with no `--`-boundary awareness, so
|
||||
// a file literally named "--stat" after the boundary was wrongly treated as the flag and
|
||||
// sent down the raw-passthrough path instead of RTK's own compacted-diff path.
|
||||
let dir = init_git_repo();
|
||||
std::fs::write(dir.path().join("--stat"), "not a summary flag\n").expect("write --stat file");
|
||||
git_in_dir(dir.path(), &["add", "--", "--stat"]);
|
||||
git_in_dir(
|
||||
dir.path(),
|
||||
&["commit", "-q", "-m", "add dash-dash-stat file"],
|
||||
);
|
||||
|
||||
let (stdout, stderr, code) = rtk_output_in_dir(dir.path(), &["git", "show", "--", "--stat"]);
|
||||
|
||||
assert_eq!(code, Some(0), "rtk stderr: {stderr}");
|
||||
assert!(
|
||||
!stdout.contains("diff --git"),
|
||||
"-- --stat should stay on RTK's compacted-diff path, not raw passthrough: {stdout:?}"
|
||||
);
|
||||
assert!(
|
||||
stdout.contains("--stat") && stdout.contains("+1"),
|
||||
"expected RTK's compacted diff summary for the --stat file: {stdout:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_diff_dash_dash_stat_pathspec_after_double_dash_is_not_stat_flag() {
|
||||
// Regression: `rtk git diff -- --stat` must not be misread as a request for the real
|
||||
// `--stat` diffstat-only flag. Before this fix, run_diff's wants_stat check was a raw
|
||||
// `arg == "--stat"` scan with no `--`-boundary awareness, so a file literally named "--stat"
|
||||
// after the boundary was wrongly treated as the flag and sent down the raw-passthrough path
|
||||
// (plain diffstat output) instead of RTK's own stat+compacted-diff path.
|
||||
let dir = init_git_repo();
|
||||
std::fs::write(dir.path().join("--stat"), "line one\n").expect("write --stat file");
|
||||
git_in_dir(dir.path(), &["add", "--", "--stat"]);
|
||||
git_in_dir(
|
||||
dir.path(),
|
||||
&["commit", "-q", "-m", "add dash-dash-stat file"],
|
||||
);
|
||||
std::fs::write(dir.path().join("--stat"), "line one\nline two\n").expect("modify --stat file");
|
||||
|
||||
let (stdout, stderr, code) = rtk_output_in_dir(dir.path(), &["git", "diff", "--", "--stat"]);
|
||||
|
||||
assert_eq!(code, Some(0), "rtk stderr: {stderr}");
|
||||
assert!(
|
||||
!stdout.contains("diff --git"),
|
||||
"-- --stat should stay on RTK's stat+compacted-diff path, not raw passthrough: {stdout:?}"
|
||||
);
|
||||
assert!(
|
||||
stdout.contains("--stat | 1 +") && stdout.contains("Changes:"),
|
||||
"expected RTK's stat-summary-plus-compacted-diff output for the modified --stat file: {stdout:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_diff_name_only_passes_through_raw() {
|
||||
// Regression: run_diff's wants_stat check only recognized --stat/--numstat/--shortstat, a
|
||||
// narrower list than requests_raw_diff_shape (which run_log already used, covering
|
||||
// --name-only/--name-status/--raw/--dirstat/--summary/-p/-u too). `--name-only` fell through
|
||||
// to RTK's default stat+compacted-diff path instead of a raw passthrough of git's own
|
||||
// name-only output.
|
||||
let dir = init_git_repo();
|
||||
std::fs::write(dir.path().join("file.txt"), "one\n").expect("write file");
|
||||
git_in_dir(dir.path(), &["add", "file.txt"]);
|
||||
git_in_dir(dir.path(), &["commit", "-q", "-m", "add file"]);
|
||||
std::fs::write(dir.path().join("file.txt"), "one\ntwo\n").expect("modify file");
|
||||
|
||||
let (stdout, stderr, code) = rtk_output_in_dir(dir.path(), &["git", "diff", "--name-only"]);
|
||||
|
||||
assert_eq!(code, Some(0), "rtk stderr: {stderr}");
|
||||
assert_eq!(
|
||||
stdout.trim(),
|
||||
"file.txt",
|
||||
"--name-only should pass through as git's own bare filename list: {stdout:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_branch_dash_prefixed_name_after_double_dash_attempts_creation_not_a_silent_list() {
|
||||
// Regression: `rtk git branch -- -weird` must be classified as a branch-creation attempt
|
||||
// (and let real git's own ref-name validation reject it), not silently fall through to list
|
||||
// mode as if no branch name were given. Before restore_double_dash + arg_tokenizer,
|
||||
// run_branch's has_positional_arg check was a raw `!a.starts_with('-')` scan with no
|
||||
// `--`-boundary awareness, so a branch name starting with '-' after the separator was
|
||||
// misclassified as a flag: has_positional_arg came back false, and (with no list flag
|
||||
// either) rtk silently ran `git branch -a --no-color -- -weird-branch` -- a harmless, empty,
|
||||
// exit-0 *list* filtered on a pattern that matches nothing, giving no indication the
|
||||
// requested branch was never created. A real branch named "-weird-branch" is impossible
|
||||
// (git's own check-ref-format forbids a leading '-'), so the observable signal here is that
|
||||
// rtk actually attempts the creation and surfaces git's real rejection, instead of quietly
|
||||
// doing nothing and exiting 0.
|
||||
let dir = init_git_repo();
|
||||
|
||||
let (stdout, stderr, code) =
|
||||
rtk_output_in_dir(dir.path(), &["git", "branch", "--", "-weird-branch"]);
|
||||
|
||||
assert_ne!(
|
||||
code,
|
||||
Some(0),
|
||||
"a creation attempt for an invalid ref name must fail, not silently succeed as an empty list: stdout={stdout:?} stderr={stderr:?}"
|
||||
);
|
||||
assert!(
|
||||
stderr.contains("-weird-branch"),
|
||||
"expected git's own rejection to mention the attempted branch name: {stderr:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_log_malformed_digit_run_propagates_real_git_error() {
|
||||
// "-5x" isn't a valid git log limit; real git rejects it outright ("fatal: '5x': not an
|
||||
// integer", verified against git 2.51). run_log's internal limit-parsing for this
|
||||
// malformed input differs before/after arg_tokenizer (5 vs the old fallback of 10), but
|
||||
// that's never observable here: run_log bails out on the real git failure before ever
|
||||
// reaching the formatting code that would use it.
|
||||
let dir = init_git_repo();
|
||||
|
||||
let raw = Command::new("git")
|
||||
.args(["log", "-5x"])
|
||||
.current_dir(dir.path())
|
||||
.output()
|
||||
.expect("spawn raw git log");
|
||||
assert!(!raw.status.success(), "expected real git to reject -5x");
|
||||
|
||||
let (_, rtk_stderr, rtk_code) = rtk_output_in_dir(dir.path(), &["git", "log", "-5x"]);
|
||||
|
||||
assert_eq!(rtk_code, raw.status.code());
|
||||
assert!(
|
||||
rtk_stderr.contains("not an integer"),
|
||||
"rtk should surface git's own error verbatim: {rtk_stderr:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_stash_show_no_stash_emits_empty_and_propagates_failure() {
|
||||
// Regression: previously printed "Empty stash" and returned Ok(0), masking
|
||||
@@ -251,13 +386,39 @@ fn git_checkout_new_branch_emits_compact_ok() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_checkout_reset_branch_does_not_claim_new_branch() {
|
||||
fn git_checkout_dash_b_capital_reports_what_git_actually_did() {
|
||||
let dir = init_git_repo();
|
||||
|
||||
// `-B` creates *or* resets, and only git knows which. Reading the branch name out of the
|
||||
// args and returning early claimed neither, so a created branch lost its `(new)` marker.
|
||||
//
|
||||
// rtk_output_in_dir pins LC_ALL=C, which is what makes the English scan land. Under
|
||||
// another locale this degrades to the args fallback ("ok feature/test") rather than
|
||||
// claiming a marker it cannot verify -- weaker, never wrong -- so `(new)` is asserted
|
||||
// here only because the locale is pinned.
|
||||
let (out, code) = rtk_in_dir(dir.path(), &["git", "checkout", "-B", "feature/test"]);
|
||||
|
||||
assert_eq!(code, Some(0));
|
||||
assert_eq!(out.trim(), "ok feature/test");
|
||||
assert_eq!(
|
||||
out.trim(),
|
||||
"ok feature/test (new)",
|
||||
"git: Switched to a new branch"
|
||||
);
|
||||
|
||||
// Reset of a branch that already exists: not new, and the args fallback names it.
|
||||
git_in_dir(dir.path(), &["checkout", "-q", "main"]);
|
||||
let (out, code) = rtk_in_dir(dir.path(), &["git", "checkout", "-B", "feature/test"]);
|
||||
assert_eq!(code, Some(0));
|
||||
assert_eq!(
|
||||
out.trim(),
|
||||
"ok feature/test",
|
||||
"git: Switched to and reset branch -- matches no scan prefix, so the args name it"
|
||||
);
|
||||
|
||||
// Glued spelling routes identically; the string scans it replaced could not read it.
|
||||
git_in_dir(dir.path(), &["checkout", "-q", "main"]);
|
||||
let (out, code) = rtk_in_dir(dir.path(), &["git", "checkout", "-Bfeature/glued"]);
|
||||
assert_eq!(code, Some(0));
|
||||
assert_eq!(out.trim(), "ok feature/glued (new)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -321,3 +482,120 @@ fn git_checkout_dirty_tree_error_keeps_file_list() {
|
||||
"dirty checkout failure should keep abort line: {combined:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A repo with one commit and one working-tree change, for the diff/show routing tests below.
|
||||
fn repo_with_a_change() -> tempfile::TempDir {
|
||||
let dir = init_git_repo();
|
||||
std::fs::write(dir.path().join("a.txt"), "l1\nl2\nl3\n").expect("write");
|
||||
git_in_dir(dir.path(), &["add", "-A"]);
|
||||
git_in_dir(dir.path(), &["commit", "-qm", "c1"]);
|
||||
std::fs::write(dir.path().join("a.txt"), "l1\nl2 CHANGED\nl3\n").expect("write");
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_diff_reports_the_error_git_gives_for_what_was_typed() {
|
||||
// RTK also runs a stat probe with the patch-shape flags stripped, so that probe answers a
|
||||
// different command: git rejects `-Uabc` (129) while the stripped probe got as far as the
|
||||
// unknown ref and said `ambiguous argument` (128). A probe must never be what reports.
|
||||
let dir = repo_with_a_change();
|
||||
|
||||
let (_, stderr, code) =
|
||||
rtk_output_in_dir(dir.path(), &["git", "diff", "-Uabc", "nonexistent-ref"]);
|
||||
assert_eq!(code, Some(129), "git's own code for the first bad flag");
|
||||
assert!(
|
||||
stderr.contains("--unified"),
|
||||
"expected git's --unified complaint, got: {stderr:?}"
|
||||
);
|
||||
|
||||
// Each alone still reports its own error.
|
||||
let (_, _, code) = rtk_output_in_dir(dir.path(), &["git", "diff", "-Uabc"]);
|
||||
assert_eq!(code, Some(129));
|
||||
let (_, _, code) = rtk_output_in_dir(dir.path(), &["git", "diff", "nonexistent-ref"]);
|
||||
assert_eq!(code, Some(128));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_diff_keeps_the_body_when_git_colours_it() {
|
||||
// Colour puts an escape at column 0, where the compaction looks for `diff --git` and `@@`,
|
||||
// so the body silently came back empty. RTK renders its own output, so the colour was
|
||||
// never going to survive compaction and is stripped before parsing.
|
||||
let dir = repo_with_a_change();
|
||||
|
||||
for args in [
|
||||
&["git", "diff", "--color"][..],
|
||||
&["git", "diff", "--color", "--unified=0"][..],
|
||||
&["git", "diff", "--color=always"][..],
|
||||
] {
|
||||
let (stdout, _, code) = rtk_output_in_dir(dir.path(), args);
|
||||
assert_eq!(code, Some(0), "{args:?}");
|
||||
assert!(
|
||||
stdout.contains("CHANGED"),
|
||||
"{args:?} lost the body: {stdout:?}"
|
||||
);
|
||||
}
|
||||
|
||||
// The same escape arrives from config, where no argument inspection could have seen it.
|
||||
git_in_dir(dir.path(), &["config", "color.ui", "always"]);
|
||||
let (stdout, _, _) = rtk_output_in_dir(dir.path(), &["git", "diff"]);
|
||||
assert!(
|
||||
stdout.contains("CHANGED"),
|
||||
"color.ui=always lost the body: {stdout:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_log_announces_its_limit_only_when_the_limit_took_something() {
|
||||
// The notice exists because that path streams and has no footer to notice missing commits
|
||||
// from. It must not claim a truncation that did not happen, nor precede a command git
|
||||
// rejects outright.
|
||||
let dir = repo_with_a_change();
|
||||
git_in_dir(dir.path(), &["add", "-A"]);
|
||||
git_in_dir(dir.path(), &["commit", "-qm", "c2"]);
|
||||
|
||||
let (_, stderr, code) = rtk_output_in_dir(dir.path(), &["git", "log", "--stat"]);
|
||||
assert_eq!(code, Some(0));
|
||||
assert!(
|
||||
!stderr.contains("[rtk]"),
|
||||
"two commits, limit of ten: nothing was truncated, but got: {stderr:?}"
|
||||
);
|
||||
|
||||
let (_, stderr, code) = rtk_output_in_dir(dir.path(), &["git", "log", "-pq"]);
|
||||
assert_ne!(code, Some(0), "git rejects -q for log");
|
||||
assert!(
|
||||
!stderr.contains("[rtk]"),
|
||||
"no notice ahead of a command git refuses: {stderr:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_show_quiet_loses_to_a_patch_request_from_either_side() {
|
||||
// git 2.53: `-s`/`--no-patch` fold in order against a patch request, `--quiet` never wins
|
||||
// over one. Modelling all three the same way dropped a patch that was asked for.
|
||||
let dir = repo_with_a_change();
|
||||
git_in_dir(dir.path(), &["add", "-A"]);
|
||||
git_in_dir(dir.path(), &["commit", "-qm", "c2"]);
|
||||
|
||||
for args in [
|
||||
&["git", "show", "--quiet", "-p"][..],
|
||||
&["git", "show", "-p", "--quiet"][..],
|
||||
&["git", "show", "-s", "-p"][..],
|
||||
] {
|
||||
let (stdout, _, _) = rtk_output_in_dir(dir.path(), args);
|
||||
assert!(
|
||||
stdout.contains("CHANGED"),
|
||||
"{args:?} should print the body: {stdout:?}"
|
||||
);
|
||||
}
|
||||
for args in [
|
||||
&["git", "show", "--quiet"][..],
|
||||
&["git", "show", "-s"][..],
|
||||
&["git", "show", "-p", "-s"][..],
|
||||
] {
|
||||
let (stdout, _, _) = rtk_output_in_dir(dir.path(), args);
|
||||
assert!(
|
||||
!stdout.contains("CHANGED"),
|
||||
"{args:?} should suppress the body: {stdout:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
//! The "hook missing/outdated" reminder is a once-a-day nudge, so where it is
|
||||
//! spent matters: a command the user ran to inspect or install the hook would
|
||||
//! both duplicate that command's own reporting and burn the daily marker,
|
||||
//! leaving the next filtered command silent.
|
||||
//!
|
||||
//! Unix only: the check resolves the Claude directory through the home
|
||||
//! directory, and only Unix takes that from `$HOME`.
|
||||
#![cfg(unix)]
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
const REMINDER: &str = "No hook installed";
|
||||
|
||||
/// Runs `rtk <args>` against a home directory whose Claude config directory
|
||||
/// exists but registers no hook, and returns stderr.
|
||||
fn run(home: &Path, args: &[&str]) -> String {
|
||||
let out = Command::new(env!("CARGO_BIN_EXE_rtk"))
|
||||
.args(args)
|
||||
.env("HOME", home)
|
||||
.env("RTK_DB_PATH", home.join("rtk.db"))
|
||||
.output()
|
||||
.expect("run rtk");
|
||||
String::from_utf8_lossy(&out.stderr).into_owned()
|
||||
}
|
||||
|
||||
fn fresh_home() -> tempfile::TempDir {
|
||||
let home = tempfile::tempdir().expect("tempdir");
|
||||
// Absent, the status check reports "not applicable"; present-but-empty is
|
||||
// what makes a missing hook detectable.
|
||||
std::fs::create_dir_all(home.path().join(".claude")).expect("claude dir");
|
||||
home
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_that_report_hook_state_do_not_repeat_the_reminder() {
|
||||
for args in [
|
||||
vec!["init", "-g"],
|
||||
vec!["verify"],
|
||||
vec!["verify", "--filter", "cargo"],
|
||||
vec!["gain"],
|
||||
] {
|
||||
let home = fresh_home();
|
||||
let stderr = run(home.path(), &args);
|
||||
assert!(
|
||||
!stderr.contains(&format!("[rtk] /!\\ {REMINDER}")),
|
||||
"rtk {} must not print the daily reminder: {stderr}",
|
||||
args.join(" ")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filtered_commands_still_get_the_reminder() {
|
||||
for args in [vec!["ls"], vec!["git", "status"]] {
|
||||
let home = fresh_home();
|
||||
let stderr = run(home.path(), &args);
|
||||
assert!(
|
||||
stderr.contains(REMINDER),
|
||||
"rtk {} must still warn: {stderr}",
|
||||
args.join(" ")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_meta_command_leaves_the_daily_reminder_for_the_next_filtered_command() {
|
||||
// The regression this guards: `maybe_warn` touches the once-a-day marker,
|
||||
// so warning on a meta command would spend the reminder there and leave
|
||||
// the next filtered command — the one that should have been hooked —
|
||||
// silent for 24 hours.
|
||||
let home = fresh_home();
|
||||
run(home.path(), &["verify", "--filter", "cargo"]);
|
||||
let stderr = run(home.path(), &["ls"]);
|
||||
assert!(
|
||||
stderr.contains(REMINDER),
|
||||
"the reminder must survive a preceding meta command: {stderr}"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::process::{Command, Output, Stdio};
|
||||
|
||||
fn read_stdin(input: &[u8], args: &[&str]) -> Output {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_rtk"))
|
||||
.args(["read", "-"])
|
||||
.args(args)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("run rtk read from stdin");
|
||||
child
|
||||
.stdin
|
||||
.take()
|
||||
.expect("piped stdin")
|
||||
.write_all(input)
|
||||
.expect("write stdin");
|
||||
child.wait_with_output().expect("wait for rtk read")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_windows_preserve_non_utf8_files() {
|
||||
let dir = tempfile::tempdir().expect("create test directory");
|
||||
let file = dir.path().join("binary.log");
|
||||
fs::write(&file, b"\xff\xfe bad\nline2\nline3\n").expect("write binary file");
|
||||
|
||||
for (flag, expected) in [
|
||||
("--head-lines", b"\xff\xfe bad\nline2\n".as_slice()),
|
||||
("--tail-lines", b"line2\nline3\n".as_slice()),
|
||||
] {
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_rtk"))
|
||||
.arg("read")
|
||||
.arg(&file)
|
||||
.args([flag, "2"])
|
||||
.output()
|
||||
.expect("run rtk read");
|
||||
|
||||
assert!(output.status.success(), "{flag}: {:?}", output.stderr);
|
||||
assert_eq!(output.stdout, expected, "{flag}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_windows_preserve_binary_boundaries_for_files_and_stdin() {
|
||||
let dir = tempfile::tempdir().expect("create test directory");
|
||||
let file = dir.path().join("binary.log");
|
||||
for input in [
|
||||
b"\xff\r\nvalid\n\0\xfe".as_slice(),
|
||||
b"\xff\r\nvalid\n\0\xfe\n".as_slice(),
|
||||
] {
|
||||
fs::write(&file, input).expect("write binary file");
|
||||
let last = if input.ends_with(b"\n") {
|
||||
b"\0\xfe\n".as_slice()
|
||||
} else {
|
||||
b"\0\xfe".as_slice()
|
||||
};
|
||||
for (flag, count, expected) in [
|
||||
("--head-lines", "0", b"".as_slice()),
|
||||
("--tail-lines", "0", b"".as_slice()),
|
||||
("--head-lines", "1", b"\xff\r\n".as_slice()),
|
||||
("--tail-lines", "1", last),
|
||||
("--head-lines", "99", input),
|
||||
("--tail-lines", "99", input),
|
||||
] {
|
||||
let from_file = Command::new(env!("CARGO_BIN_EXE_rtk"))
|
||||
.arg("read")
|
||||
.arg(&file)
|
||||
.args([flag, count])
|
||||
.output()
|
||||
.expect("run rtk read");
|
||||
let from_stdin = read_stdin(input, &[flag, count]);
|
||||
for output in [from_file, from_stdin] {
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{flag} {count}: {:?}",
|
||||
output.stderr
|
||||
);
|
||||
assert_eq!(output.stdout, expected, "{flag} {count}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_windows_accept_invalid_bytes_outside_the_selected_window() {
|
||||
for (input, flag) in [
|
||||
(b"valid\n\xff\n".as_slice(), "--head-lines"),
|
||||
(b"\xff\nvalid\n".as_slice(), "--tail-lines"),
|
||||
] {
|
||||
let output = read_stdin(input, &[flag, "1"]);
|
||||
assert!(output.status.success(), "{flag}: {:?}", output.stderr);
|
||||
assert_eq!(output.stdout, b"valid\n");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_windows_still_apply_text_filtering_and_line_numbers() {
|
||||
let input = b"// comment\nfn alpha() {}\nfn beta() {}\nfn gamma() {}\n";
|
||||
for (args, expected) in [
|
||||
(
|
||||
["--head-lines", "1", "--level", "minimal"].as_slice(),
|
||||
"fn alpha() {}\n",
|
||||
),
|
||||
(
|
||||
["--tail-lines", "1", "--level", "minimal"].as_slice(),
|
||||
"fn gamma() {}",
|
||||
),
|
||||
(
|
||||
["--head-lines", "1", "--line-numbers"].as_slice(),
|
||||
"1 │ // comment\n",
|
||||
),
|
||||
(
|
||||
["--tail-lines", "1", "--line-numbers"].as_slice(),
|
||||
"1 │ fn gamma() {}\n",
|
||||
),
|
||||
] {
|
||||
let output = read_stdin(input, args);
|
||||
assert!(output.status.success(), "{args:?}: {:?}", output.stderr);
|
||||
assert_eq!(output.stdout, expected.as_bytes(), "{args:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn rewritten_head_spellings_match_native_on_non_utf8_files() {
|
||||
let dir = tempfile::tempdir().expect("create test directory");
|
||||
let claude_dir = dir.path().join(".claude");
|
||||
fs::create_dir(&claude_dir).expect("create isolated Claude config directory");
|
||||
let config_dir = dir.path().join("config");
|
||||
fs::create_dir(&config_dir).expect("create isolated rtk config directory");
|
||||
let file = dir.path().join("binary.log");
|
||||
fs::write(&file, b"\xff\xfe bad\nline2\nline3\n").expect("write binary file");
|
||||
for flags in ["-2", "-n 2", "--lines 2", "--lines=2", ""] {
|
||||
let command = format!("head {flags} {}", file.display());
|
||||
let rewrite = Command::new(env!("CARGO_BIN_EXE_rtk"))
|
||||
.current_dir(dir.path())
|
||||
.env("CLAUDE_CONFIG_DIR", &claude_dir)
|
||||
.env("XDG_CONFIG_HOME", &config_dir)
|
||||
.args(["rewrite", &command])
|
||||
.output()
|
||||
.expect("rewrite head command");
|
||||
assert_eq!(
|
||||
rewrite.status.code(),
|
||||
Some(3),
|
||||
"{command}: {:?}",
|
||||
rewrite.stderr
|
||||
);
|
||||
let rewritten = String::from_utf8(rewrite.stdout).expect("UTF-8 command");
|
||||
let count = if flags.is_empty() { "10" } else { "2" };
|
||||
assert_eq!(
|
||||
rewritten.trim(),
|
||||
format!("rtk read {} --head-lines {count}", file.display())
|
||||
);
|
||||
let actual = Command::new(env!("CARGO_BIN_EXE_rtk"))
|
||||
.args(
|
||||
rewritten
|
||||
.trim()
|
||||
.strip_prefix("rtk ")
|
||||
.expect("rtk rewrite prefix")
|
||||
.split_whitespace(),
|
||||
)
|
||||
.output()
|
||||
.expect("execute rewritten head");
|
||||
let native = Command::new("head")
|
||||
.args(flags.split_whitespace())
|
||||
.arg(&file)
|
||||
.output()
|
||||
.expect("run native head");
|
||||
assert!(native.status.success(), "{command}: {:?}", native.stderr);
|
||||
assert_eq!(actual.status.code(), native.status.code(), "{command}");
|
||||
assert_eq!(actual.stdout, native.stdout, "{command}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
#![cfg(unix)]
|
||||
//! Which stdin the engines actually read. These run in CI as integration tests rather than
|
||||
//! `#[ignore]`d unit tests: `CARGO_BIN_EXE_rtk` guarantees a built binary, so the fix they
|
||||
//! cover is exercised by `cargo test --all` instead of only by a flag nobody passes.
|
||||
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
fn rtk() -> Command {
|
||||
let mut cmd = Command::new(env!("CARGO_BIN_EXE_rtk"));
|
||||
cmd.env("LC_ALL", "C");
|
||||
cmd
|
||||
}
|
||||
|
||||
/// Each test guards on the engine it actually drives -- guarding an rg test on grep (or the
|
||||
/// reverse) turns a missing tool into a silent pass rather than a skip.
|
||||
fn engine_available(engine: &str) -> bool {
|
||||
Command::new(engine)
|
||||
.arg("--version")
|
||||
.output()
|
||||
.map(|o| o.status.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rg_shows_filenames_when_stdin_is_not_a_pipe() {
|
||||
if !engine_available("rg") {
|
||||
return;
|
||||
}
|
||||
// `rtk rg -z foo < /dev/null` in a multi-file dir used to drop filenames: stdin being a
|
||||
// non-terminal, non-pipe redirect was misread as "the engine reads stdin," routing into the
|
||||
// streaming path, which can't discover "multiple files" the way the buffered path does.
|
||||
// Real rg searches the cwd here, not stdin.
|
||||
let dir = tempfile::tempdir().expect("test setup");
|
||||
std::fs::write(dir.path().join("a.txt"), "foo one\n").expect("test setup");
|
||||
std::fs::write(dir.path().join("b.txt"), "foo two\n").expect("test setup");
|
||||
|
||||
let output = rtk()
|
||||
.args(["rg", "-z", "foo"])
|
||||
.current_dir(dir.path())
|
||||
.stdin(Stdio::null())
|
||||
.output()
|
||||
.expect("failed to run rtk rg");
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(stdout.contains("a.txt"), "filename missing: {stdout}");
|
||||
assert!(stdout.contains("b.txt"), "filename missing: {stdout}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_single_matching_file_still_gets_its_name() {
|
||||
if !engine_available("rg") {
|
||||
return;
|
||||
}
|
||||
// The engine walked the cwd itself, so the filename is the only way to place the match --
|
||||
// real rg prints it even when exactly one file matched.
|
||||
let dir = tempfile::tempdir().expect("test setup");
|
||||
std::fs::write(dir.path().join("only.txt"), "foo here\n").expect("test setup");
|
||||
std::fs::write(dir.path().join("other.txt"), "nothing\n").expect("test setup");
|
||||
|
||||
let output = rtk()
|
||||
.args(["rg", "foo"])
|
||||
.current_dir(dir.path())
|
||||
.stdin(Stdio::null())
|
||||
.output()
|
||||
.expect("failed to run rtk rg");
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(stdout.contains("only.txt"), "filename missing: {stdout}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_engines_read_a_redirected_file_on_stdin() {
|
||||
// A regular file on stdin *is* read by both engines (rg's own is_readable_stdin counts
|
||||
// files and sockets, not just FIFOs), so the search must return that file's match rather
|
||||
// than the cwd's.
|
||||
let dir = tempfile::tempdir().expect("test setup");
|
||||
std::fs::write(dir.path().join("a.txt"), "foo from the cwd\n").expect("test setup");
|
||||
// The fixture lives outside the searched directory: inside it, an engine that ignored
|
||||
// stdin and walked the cwd would still print "foo from stdin" and the test would pass.
|
||||
let elsewhere = tempfile::tempdir().expect("test setup");
|
||||
let piped = elsewhere.path().join("piped.log");
|
||||
std::fs::write(&piped, "foo from stdin\n").expect("test setup");
|
||||
|
||||
for engine in ["grep", "rg"] {
|
||||
if !engine_available(engine) {
|
||||
continue;
|
||||
}
|
||||
let output = rtk()
|
||||
.args([engine, "foo"])
|
||||
.current_dir(dir.path())
|
||||
.stdin(std::fs::File::open(&piped).expect("test setup"))
|
||||
.output()
|
||||
.expect("failed to run rtk");
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(
|
||||
stdout.contains("foo from stdin"),
|
||||
"{engine} did not read stdin: {stdout}"
|
||||
);
|
||||
assert!(
|
||||
!stdout.contains("foo from the cwd"),
|
||||
"{engine} walked the cwd instead of reading stdin: {stdout}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
//! Stdout-only filters parse structured stdout, but a tool's diagnostics often go to
|
||||
//! stderr. Dropping that stream leaves a failing command looking silent; inventing a
|
||||
//! stdout message in its place is just as wrong. These pin both halves.
|
||||
|
||||
#![cfg(unix)]
|
||||
|
||||
use std::fs;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Output};
|
||||
|
||||
/// Writes an executable `name` in `dir` that runs `body`.
|
||||
fn fake_tool(dir: &Path, name: &str, body: &str) {
|
||||
let path = dir.join(name);
|
||||
fs::write(&path, format!("#!/bin/sh\n{}\n", body)).expect("write fake tool");
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).expect("chmod fake tool");
|
||||
}
|
||||
|
||||
/// Runs rtk with `dir` first on PATH, so the fake tool shadows any real one.
|
||||
fn rtk_with(dir: &Path, args: &[&str]) -> Output {
|
||||
let path = format!(
|
||||
"{}:{}",
|
||||
dir.display(),
|
||||
std::env::var("PATH").unwrap_or_default()
|
||||
);
|
||||
Command::new(env!("CARGO_BIN_EXE_rtk"))
|
||||
.args(args)
|
||||
.env("PATH", path)
|
||||
.output()
|
||||
.expect("run rtk")
|
||||
}
|
||||
|
||||
/// A golangci-lint that answers `--version`, then fails the way a config or build
|
||||
/// error does: everything on stderr, stdout empty, non-zero exit.
|
||||
fn fake_golangci(dir: &Path, failure: &str) {
|
||||
fake_tool(
|
||||
dir,
|
||||
"golangci-lint",
|
||||
&format!(
|
||||
r#"if [ "$1" = "--version" ]; then
|
||||
echo "golangci-lint has version 1.64.8"
|
||||
exit 0
|
||||
fi
|
||||
{failure}"#
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn golangci_lint_stderr_only_failure_reaches_the_user() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
fake_golangci(
|
||||
dir.path(),
|
||||
r#"echo 'level=error msg="context loading failed: failed to load packages"' >&2
|
||||
exit 3"#,
|
||||
);
|
||||
|
||||
let out = rtk_with(dir.path(), &["golangci-lint", "run"]);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
|
||||
assert!(
|
||||
stderr.contains("context loading failed"),
|
||||
"the tool's own error must reach the user; got stderr: {stderr}"
|
||||
);
|
||||
assert_eq!(out.status.code(), Some(3), "exit code must propagate");
|
||||
}
|
||||
|
||||
/// The command said nothing on stdout, so neither does rtk. A filter's "I got nothing"
|
||||
/// placeholder is not a diagnostic — the real one is on stderr.
|
||||
#[test]
|
||||
fn no_invented_stdout_diagnostic_when_the_tool_used_stderr() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
fake_tool(
|
||||
dir.path(),
|
||||
"prettier",
|
||||
r#"echo "Checking formatting..." >&2
|
||||
echo "[warn] src/a.js" >&2
|
||||
echo "Code style issues found in the above file(s)." >&2
|
||||
exit 1"#,
|
||||
);
|
||||
|
||||
let out = rtk_with(dir.path(), &["prettier", "--check", "."]);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
|
||||
assert!(
|
||||
stdout.trim().is_empty(),
|
||||
"prettier ran fine and reported on stderr; stdout must not claim otherwise, got: {stdout}"
|
||||
);
|
||||
assert!(
|
||||
stderr.contains("[warn] src/a.js"),
|
||||
"prettier's report must reach the user; got stderr: {stderr}"
|
||||
);
|
||||
}
|
||||
|
||||
/// stderr goes out on its own stream, so it must not also be replayed on stdout.
|
||||
#[test]
|
||||
fn stderr_is_not_duplicated_onto_stdout() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
fake_tool(
|
||||
dir.path(),
|
||||
"ruff",
|
||||
r#"echo "stdout line"
|
||||
echo "stderr diagnostic" >&2
|
||||
exit 1"#,
|
||||
);
|
||||
|
||||
let out = rtk_with(dir.path(), &["ruff", "check", "."]);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
|
||||
assert!(
|
||||
!stdout.contains("stderr diagnostic"),
|
||||
"stderr must not be replayed on stdout; got stdout: {stdout}"
|
||||
);
|
||||
assert!(
|
||||
stderr.contains("stderr diagnostic"),
|
||||
"stderr must still reach the user; got stderr: {stderr}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A command that genuinely says nothing must stay silent.
|
||||
#[test]
|
||||
fn silent_command_stays_silent() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
fake_tool(dir.path(), "ruff", "exit 0");
|
||||
|
||||
let out = rtk_with(dir.path(), &["ruff", "check", "."]);
|
||||
|
||||
assert!(
|
||||
String::from_utf8_lossy(&out.stdout).trim().is_empty(),
|
||||
"a silent command must not gain output"
|
||||
);
|
||||
assert!(String::from_utf8_lossy(&out.stderr).trim().is_empty());
|
||||
assert_eq!(out.status.code(), Some(0));
|
||||
}
|
||||
|
||||
/// Not a golangci-lint quirk: every stdout-only filter forwards stderr.
|
||||
#[test]
|
||||
fn stderr_forwarding_is_not_golangci_specific() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
fake_tool(
|
||||
dir.path(),
|
||||
"ruff",
|
||||
r#"echo "ruff failed hard" >&2
|
||||
exit 2"#,
|
||||
);
|
||||
|
||||
let out = rtk_with(dir.path(), &["ruff", "check", "."]);
|
||||
|
||||
assert!(
|
||||
String::from_utf8_lossy(&out.stderr).contains("ruff failed hard"),
|
||||
"stderr must reach the user for any stdout-only filter"
|
||||
);
|
||||
assert_eq!(out.status.code(), Some(2), "exit code must propagate");
|
||||
}
|
||||
|
||||
/// golangci-lint exits 1 when it merely found lint issues. RTK reports them and
|
||||
/// returns 0, so the linter running successfully does not fail a build.
|
||||
#[test]
|
||||
fn lint_issues_are_summarised_and_exit_zero() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let issues = r#"{"Issues":[{"FromLinter":"errcheck","Text":"unchecked","Pos":{"Filename":"main.go","Line":1,"Column":1},"SourceLines":["x()"],"Severity":""}]}"#;
|
||||
fake_golangci(dir.path(), &format!("echo '{issues}'\nexit 1"));
|
||||
|
||||
let out = rtk_with(dir.path(), &["golangci-lint", "run"]);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
|
||||
assert!(
|
||||
stdout.contains("1 issues in 1 files") && stdout.contains("errcheck"),
|
||||
"expected an issue summary; got: {stdout}"
|
||||
);
|
||||
assert_eq!(
|
||||
out.status.code(),
|
||||
Some(0),
|
||||
"exit 1 means issues found, which RTK reports without failing"
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user