Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c8e5618e6a |
No files matched your search
@@ -1,12 +0,0 @@
|
||||
name: DCO Check
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
pull_request:
|
||||
branches:
|
||||
- develop
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: KineticCafe/actions-dco@v1
|
||||
@@ -201,39 +201,6 @@ jobs:
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
notify-discord:
|
||||
name: Notify Discord
|
||||
needs: [release]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Get version
|
||||
id: version
|
||||
run: |
|
||||
TAG="${{ inputs.tag }}"
|
||||
if [ -z "$TAG" ]; then
|
||||
TAG="${{ github.event.release.tag_name }}"
|
||||
fi
|
||||
echo "tag=$TAG" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Send Discord notification
|
||||
env:
|
||||
DISCORD_WEBHOOK: ${{ secrets.RTK_DISCORD_RELEASE }}
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
TAG="${{ steps.version.outputs.tag }}"
|
||||
RELEASE_URL="https://github.com/rtk-ai/rtk/releases/tag/${TAG}"
|
||||
|
||||
# Fetch release notes from GitHub API
|
||||
NOTES=$(gh api "repos/rtk-ai/rtk/releases/tags/${TAG}" --jq '.body' 2>/dev/null | head -c 1800 || echo "")
|
||||
DESC=$(echo "${NOTES:-No release notes}" | jq -Rs .)
|
||||
|
||||
jq -n \
|
||||
--arg title "RTK ${TAG} released" \
|
||||
--arg url "$RELEASE_URL" \
|
||||
--argjson desc "$DESC" \
|
||||
'{embeds: [{title: $title, url: $url, description: $desc, color: 5814783, footer: {text: "Rust Token Killer"}}]}' \
|
||||
| curl -sf -H "Content-Type: application/json" -d @- "$DISCORD_WEBHOOK"
|
||||
|
||||
homebrew:
|
||||
name: Update Homebrew formula
|
||||
needs: [release]
|
||||
|
||||
+1
-10
@@ -19,8 +19,6 @@ secrets.json
|
||||
*.swo
|
||||
*~
|
||||
|
||||
.next
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
@@ -37,11 +35,4 @@ benchmark-report.md
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
rtk_tracking.db
|
||||
claudedocs
|
||||
|
||||
# Vitals provenance data
|
||||
.vitals/
|
||||
.worktrees/
|
||||
|
||||
# icm
|
||||
.fastembed_cache/
|
||||
claudedocs
|
||||
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "0.28.2"
|
||||
".": "0.27.1"
|
||||
}
|
||||
+3
-3
@@ -293,12 +293,12 @@ SHARED utils.rs Helpers N/A ✓
|
||||
tee.rs Full output recovery N/A ✓
|
||||
```
|
||||
|
||||
**Total: 60 modules** (38 command modules + 22 infrastructure modules)
|
||||
**Total: 57 modules** (38 command modules + 19 infrastructure modules)
|
||||
|
||||
### Module Count Breakdown
|
||||
|
||||
- **Command Modules**: 34 (directly exposed to users)
|
||||
- **Infrastructure Modules**: 20 (utils, filter, tracking, tee, config, init, gain, toml_filter, verify_cmd, etc.)
|
||||
- **Infrastructure Modules**: 18 (utils, filter, tracking, tee, config, init, gain, etc.)
|
||||
- **Git Commands**: 7 operations (status, diff, log, add, commit, push, branch/checkout)
|
||||
- **JS/TS Tooling**: 8 modules (modern frontend/fullstack development)
|
||||
- **Python Tooling**: 3 modules (ruff, pytest, pip)
|
||||
@@ -1488,4 +1488,4 @@ When implementing a new command, consider:
|
||||
|
||||
**Last Updated**: 2026-02-22
|
||||
**Architecture Version**: 2.2
|
||||
**rtk Version**: 0.28.0
|
||||
**rtk Version**: 0.26.0
|
||||
@@ -5,41 +5,6 @@ All notable changes to rtk (Rust Token Killer) will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [0.28.2](https://github.com/rtk-ai/rtk/compare/v0.28.1...v0.28.2) (2026-03-10)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add tokens_saved to telemetry payload ([#471](https://github.com/rtk-ai/rtk/issues/471)) ([#472](https://github.com/rtk-ai/rtk/issues/472)) ([f8b7d52](https://github.com/rtk-ai/rtk/commit/f8b7d52d2d25d09a44f391576bad6a7b271f1f8c))
|
||||
|
||||
## [0.28.1](https://github.com/rtk-ai/rtk/compare/v0.28.0...v0.28.1) (2026-03-10)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* 4 critical bugs + telemetry enrichment ([#462](https://github.com/rtk-ai/rtk/issues/462)) ([7d76af8](https://github.com/rtk-ai/rtk/commit/7d76af84b95e0f040e8b91a154edb89f80e5c380))
|
||||
* restore lost telemetry install_method enrichment ([#469](https://github.com/rtk-ai/rtk/issues/469)) ([0c5cde9](https://github.com/rtk-ai/rtk/commit/0c5cde9ec234a2b7b0376adbcb78f2be48a98e86))
|
||||
|
||||
## [0.28.0](https://github.com/rtk-ai/rtk/compare/v0.27.2...v0.28.0) (2026-03-10)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **gt:** add Graphite CLI support ([#290](https://github.com/rtk-ai/rtk/issues/290)) ([7fbc4ef](https://github.com/rtk-ai/rtk/commit/7fbc4ef4b553d5e61feeb6e73d8f6a96b6df3dd9))
|
||||
* TOML Part 1 — filter DSL engine + 14 built-in filters ([#349](https://github.com/rtk-ai/rtk/issues/349)) ([adda253](https://github.com/rtk-ai/rtk/commit/adda2537be1fe69625ac280f15e8c8067d08c711))
|
||||
* TOML Part 2 — user-global config, shadow warning, rtk init templates, 4 new built-in filters ([#351](https://github.com/rtk-ai/rtk/issues/351)) ([926e6a0](https://github.com/rtk-ai/rtk/commit/926e6a0dd4512c4cbb0f5ac133e60cb6134a3174))
|
||||
* TOML Part 3 — 15 additional built-in filters (ping, rsync, dotnet, swift, shellcheck, hadolint, poetry, composer, brew, df, ps, systemctl, yamllint, markdownlint, uv) ([#386](https://github.com/rtk-ai/rtk/issues/386)) ([b71a8d2](https://github.com/rtk-ai/rtk/commit/b71a8d24e2dbd3ff9bb423c849638bfa23830c0b))
|
||||
|
||||
## [0.27.2](https://github.com/rtk-ai/rtk/compare/v0.27.1...v0.27.2) (2026-03-06)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* gh pr edit/comment pass correct subcommand to gh ([#332](https://github.com/rtk-ai/rtk/issues/332)) ([799f085](https://github.com/rtk-ai/rtk/commit/799f0856e4547318230fe150a43f50ab82e1cf03))
|
||||
* pass through -R/--repo flag in gh view commands ([#328](https://github.com/rtk-ai/rtk/issues/328)) ([0a1bcb0](https://github.com/rtk-ai/rtk/commit/0a1bcb05e5737311211369dcb92b3f756a6230c6)), closes [#223](https://github.com/rtk-ai/rtk/issues/223)
|
||||
* reduce gh diff / git diff / gh api truncation ([#354](https://github.com/rtk-ai/rtk/issues/354)) ([#370](https://github.com/rtk-ai/rtk/issues/370)) ([e356c12](https://github.com/rtk-ai/rtk/commit/e356c1280da9896195d0dff91e152c5f20347a65))
|
||||
* strip npx/bunx/pnpm prefixes in lint linter detection ([#186](https://github.com/rtk-ai/rtk/issues/186)) ([#366](https://github.com/rtk-ai/rtk/issues/366)) ([27b35d8](https://github.com/rtk-ai/rtk/commit/27b35d84a341622aa4bf686c2ce8867f8feeb742))
|
||||
|
||||
## [0.27.1](https://github.com/rtk-ai/rtk/compare/v0.27.0...v0.27.1) (2026-03-06)
|
||||
|
||||
|
||||
@@ -81,25 +46,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
### Features
|
||||
|
||||
* **toml-dsl:** declarative TOML filter engine — add command filters without writing Rust ([#299](https://github.com/rtk-ai/rtk/issues/299))
|
||||
* 8 primitives: `strip_ansi`, `replace`, `match_output`, `strip/keep_lines_matching`, `truncate_lines_at`, `head/tail_lines`, `max_lines`, `on_empty`
|
||||
* lookup chain: `.rtk/filters.toml` (project-local) → `~/.config/rtk/filters.toml` (user-global) → built-in filters
|
||||
* `RTK_NO_TOML=1` bypass, `RTK_TOML_DEBUG=1` debug mode
|
||||
* shadow warning when a TOML filter's match_command overlaps a Rust-handled command
|
||||
* `rtk init` generates commented filter templates at both project and global level
|
||||
* `rtk verify` command with `--require-all` for inline test validation
|
||||
* 18 built-in filters: `tofu-plan/init/validate/fmt` ([#240](https://github.com/rtk-ai/rtk/issues/240)), `du` ([#284](https://github.com/rtk-ai/rtk/issues/284)), `fail2ban-client` ([#281](https://github.com/rtk-ai/rtk/issues/281)), `iptables` ([#282](https://github.com/rtk-ai/rtk/issues/282)), `mix-format/compile` ([#310](https://github.com/rtk-ai/rtk/issues/310)), `shopify-theme` ([#280](https://github.com/rtk-ai/rtk/issues/280)), `pio-run` ([#231](https://github.com/rtk-ai/rtk/issues/231)), `mvn-build` ([#338](https://github.com/rtk-ai/rtk/issues/338)), `pre-commit`, `helm`, `gcloud`, `ansible-playbook`
|
||||
* **hooks:** `exclude_commands` config — exclude specific commands from auto-rewrite ([#243](https://github.com/rtk-ai/rtk/issues/243))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **curl:** skip JSON schema replacement when schema is larger than original payload ([#297](https://github.com/rtk-ai/rtk/issues/297))
|
||||
* **toml-dsl:** fix regex overmatch on `tofu-plan/init/validate/fmt` and `mix-format/compile` — add `(\s|$)` word boundary to prevent matching subcommands (e.g. `tofu planet`, `mix formats`) ([#349](https://github.com/rtk-ai/rtk/issues/349))
|
||||
* **toml-dsl:** remove 3 dead built-in filters (`docker-inspect`, `docker-compose-ps`, `pnpm-build`) — Clap routes these commands before `run_fallback`, so the TOML filters never fire ([#351](https://github.com/rtk-ai/rtk/issues/351))
|
||||
* **toml-dsl:** `uv-sync` — remove `Resolved` short-circuit; it fires before the package list is printed, hiding installed packages ([#386](https://github.com/rtk-ai/rtk/issues/386))
|
||||
* **toml-dsl:** `dotnet-build` — short-circuit only when both warning and error counts are zero; builds with warnings now pass through ([#386](https://github.com/rtk-ai/rtk/issues/386))
|
||||
* **toml-dsl:** `poetry-install` — support Poetry 2.x bullet syntax (`•`) and `No changes.` up-to-date message ([#386](https://github.com/rtk-ai/rtk/issues/386))
|
||||
* **toml-dsl:** `ping` — add Windows format support (`Pinging` header, `Reply from` per-packet lines) ([#386](https://github.com/rtk-ai/rtk/issues/386))
|
||||
|
||||
## [0.25.0](https://github.com/rtk-ai/rtk/compare/v0.24.0...v0.25.0) (2026-03-05)
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ This is a fork with critical fixes for git argument parsing and modern JavaScrip
|
||||
|
||||
**Verify correct installation:**
|
||||
```bash
|
||||
rtk --version # Should show "rtk 0.28.0" (or newer)
|
||||
rtk --version # Should show "rtk 0.26.0" (or newer)
|
||||
rtk gain # Should show token savings stats (NOT "command not found")
|
||||
```
|
||||
|
||||
|
||||
-199
@@ -1,199 +0,0 @@
|
||||
# Contributing to rtk
|
||||
|
||||
**Welcome!** We appreciate your interest in contributing to rtk.
|
||||
|
||||
## Quick Links
|
||||
|
||||
- [Report an Issue](../../issues/new)
|
||||
- [Open Pull Requests](../../pulls)
|
||||
- [Start a Discussion](../../discussions)
|
||||
|
||||
---
|
||||
|
||||
## What is rtk?
|
||||
|
||||
**rtk (Rust Token Killer)** is a coding agent proxy that cuts noise from command outputs. It filters and compresses CLI output before it reaches your LLM context, saving 60-90% of tokens on common operations. The vision is to make AI-assisted development faster and cheaper by eliminating unnecessary token consumption.
|
||||
|
||||
---
|
||||
|
||||
## Ways to Contribute
|
||||
|
||||
| Type | Examples |
|
||||
|------|----------|
|
||||
| **Report** | File a clear issue with steps to reproduce, expected vs actual behavior |
|
||||
| **Fix** | Bug fixes, broken filter repairs |
|
||||
| **Build** | New filters, new command support, performance improvements |
|
||||
| **Review** | Review open PRs, test changes locally, leave constructive feedback |
|
||||
| **Document** | Improve docs, add usage examples, clarify existing docs |
|
||||
---
|
||||
|
||||
## Branch Naming Convention
|
||||
|
||||
Every branch **must** follow one of these prefixes to identify the level of change:
|
||||
|
||||
| Prefix | Semver Impact | When to Use |
|
||||
|--------|---------------|-------------|
|
||||
| `fix(scope): ...` | Patch | Bug fixes, corrections, minor adjustments |
|
||||
| `feat(scope): ...` | Minor | New features, new filters, new command support |
|
||||
| `chore(scope): ...` | Major | Breaking changes, API changes, removed functionality |
|
||||
|
||||
The **scope** in parentheses indicates which part of the project is concerned (e.g. `git`, `kubectl`, `filter`, `tracking`, `config`).
|
||||
|
||||
**Branch title must clearly describe what is affected and the goal.**
|
||||
|
||||
Examples:
|
||||
```
|
||||
fix(git): log-filter-drops-merge-commits
|
||||
feat(kubectl): add-pod-list-filter
|
||||
chore(proxy): remove-deprecated-flags
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Pull Request Process
|
||||
|
||||
### 1. Create Your Branch
|
||||
|
||||
```bash
|
||||
git checkout develop
|
||||
git pull origin develop
|
||||
git checkout -b "feat(scope): your-clear-description"
|
||||
```
|
||||
|
||||
### 2. Make Your Changes
|
||||
|
||||
**Respect the existing folder structure.** Place new files where similar files already live. Do not reorganize without prior discussion.
|
||||
|
||||
**Keep functions short and focused.** Each function should do one thing. If it needs a comment to explain what it does, it's probably too long -- split it.
|
||||
|
||||
**No obvious comments.** Don't comment what the code already says. Comments should explain *why*, never *what* to avoid noise.
|
||||
|
||||
**Large command files are expected.** Command modules (`*_cmd.rs`) contain the implementation, tests, and fixture in the same file. A big file is fine when it's self-contained for one command.
|
||||
|
||||
### 3. Add Tests
|
||||
|
||||
Every change **must** include tests. See [Testing](#testing) below.
|
||||
|
||||
### 4. Add Documentation
|
||||
|
||||
Every change **must** include documentation updates. See [Documentation](#documentation) below.
|
||||
|
||||
### Developer Certificate of Origin (DCO)
|
||||
|
||||
All contributions must be signed off (git commit -s) to certify
|
||||
you have the right to submit the code under the project's license.
|
||||
|
||||
Expected format: Signed-off-by: Your Name your@email.com
|
||||
https://developercertificate.org/
|
||||
|
||||
By signing off, you agree to the DCO.
|
||||
|
||||
### 5. Merge into `develop`
|
||||
|
||||
Once your work is ready, open a Pull Request targeting the **`develop`** branch.
|
||||
|
||||
### 6. Review Process
|
||||
|
||||
1. **Maintainer review** -- A maintainer reviews your code for quality and alignment with the project
|
||||
2. **CI/CD checks** -- Automated tests and linting must pass
|
||||
3. **Resolution** -- Address any feedback from review or CI failures
|
||||
|
||||
### 7. Integration & Release
|
||||
|
||||
Once merged, your changes are tested on the `develop` branch alongside other features. When the maintainer is satisfied with the state of `develop`, they release to `master` under a specific version.
|
||||
|
||||
```
|
||||
your branch --> develop (review + CI + integration testing) --> version branch --> master (versioned release)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Testing
|
||||
|
||||
Every change **must** include tests. We follow **TDD (Red-Green-Refactor)**: write a failing test first, implement the minimum to pass, then refactor.
|
||||
|
||||
### Test Types
|
||||
|
||||
| Type | Where | Run With |
|
||||
|------|-------|----------|
|
||||
| **Unit tests** | `#[cfg(test)] mod tests` in each module | `cargo test` |
|
||||
| **Snapshot tests** | `assert_snapshot!()` via `insta` crate | `cargo test` + `cargo insta review` |
|
||||
| **Smoke tests** | `scripts/test-all.sh` (69 assertions) | `bash scripts/test-all.sh` |
|
||||
| **Integration tests** | `#[ignore]` tests requiring installed binary | `cargo test --ignored` |
|
||||
|
||||
### How to Write Tests
|
||||
|
||||
Tests for new commands live **in the module file itself** inside a `#[cfg(test)] mod tests` block (e.g. tests for `src/kubectl_cmd.rs` go at the bottom of that same file).
|
||||
|
||||
**1. Create a fixture from real command output** (not synthetic data):
|
||||
```bash
|
||||
kubectl get pods > tests/fixtures/kubectl_pods_raw.txt
|
||||
```
|
||||
|
||||
**2. Write your test in the same module file** (`#[cfg(test)] mod tests`):
|
||||
```rust
|
||||
#[test]
|
||||
fn test_my_filter() {
|
||||
let input = include_str!("../tests/fixtures/my_cmd_raw.txt");
|
||||
let output = filter_my_cmd(input);
|
||||
assert_snapshot!(output);
|
||||
}
|
||||
```
|
||||
|
||||
**3. Verify token savings**:
|
||||
```rust
|
||||
#[test]
|
||||
fn test_my_filter_savings() {
|
||||
let input = include_str!("../tests/fixtures/my_cmd_raw.txt");
|
||||
let output = filter_my_cmd(input);
|
||||
let savings = 100.0 - (count_tokens(&output) as f64 / count_tokens(input) as f64 * 100.0);
|
||||
assert!(savings >= 60.0, "Expected >=60% savings, got {:.1}%", savings);
|
||||
}
|
||||
```
|
||||
|
||||
### Pre-Commit Gate (mandatory)
|
||||
|
||||
All three must pass before any PR:
|
||||
|
||||
```bash
|
||||
cargo fmt --all --check && cargo clippy --all-targets && cargo test
|
||||
```
|
||||
|
||||
### PR Testing Checklist
|
||||
|
||||
- [ ] Unit tests added/updated for changed code
|
||||
- [ ] Snapshot tests reviewed (`cargo insta review`)
|
||||
- [ ] Token savings >=60% verified
|
||||
- [ ] Edge cases covered
|
||||
- [ ] `cargo fmt --all --check && cargo clippy --all-targets && cargo test` passes
|
||||
- [ ] Manual test: run `rtk <cmd>` and inspect output
|
||||
|
||||
---
|
||||
|
||||
## Documentation
|
||||
|
||||
Every change **must** include documentation updates. Update the relevant file(s) depending on what you changed:
|
||||
|
||||
| What you changed | Update |
|
||||
|------------------|--------|
|
||||
| New command or filter | [README.md](README.md) (command list + examples) and [CHANGELOG.md](CHANGELOG.md) |
|
||||
| Architecture or internal design | [ARCHITECTURE.md](ARCHITECTURE.md) |
|
||||
| Installation or setup | [INSTALL.md](INSTALL.md) |
|
||||
| Bug fix or breaking change | [CHANGELOG.md](CHANGELOG.md) |
|
||||
| Tracking / analytics | [docs/tracking.md](docs/tracking.md) |
|
||||
|
||||
Keep documentation concise and practical -- examples over explanations.
|
||||
|
||||
---
|
||||
|
||||
## Questions?
|
||||
|
||||
- **Bug reports & features**: [Issues](../../issues)
|
||||
- **Discussions**: [GitHub Discussions](../../discussions)
|
||||
|
||||
**For external contributors**: Your PR will undergo automated security review (see [SECURITY.md](SECURITY.md)).
|
||||
This protects RTK's shell execution capabilities against injection attacks and supply chain vulnerabilities.
|
||||
|
||||
---
|
||||
|
||||
**Thank you for contributing to rtk!**
|
||||
Generated
+1
-1
@@ -838,7 +838,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rtk"
|
||||
version = "0.28.2"
|
||||
version = "0.27.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
|
||||
+1
-4
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "rtk"
|
||||
version = "0.28.2"
|
||||
version = "0.27.1"
|
||||
edition = "2021"
|
||||
authors = ["Patrick Szymkowiak"]
|
||||
description = "Rust Token Killer - High-performance CLI proxy to minimize LLM token consumption"
|
||||
@@ -31,9 +31,6 @@ sha2 = "0.10"
|
||||
ureq = "2"
|
||||
hostname = "0.4"
|
||||
|
||||
[build-dependencies]
|
||||
toml = "0.8"
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
[profile.release]
|
||||
|
||||
-159
@@ -1,159 +0,0 @@
|
||||
<p align="center">
|
||||
<img src="https://avatars.githubusercontent.com/u/258253854?v=4" alt="RTK - Rust Token Killer" width="500">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<strong>Proxy CLI de alto rendimiento que reduce el consumo de tokens LLM en un 60-90%</strong>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/rtk-ai/rtk/actions"><img src="https://github.com/rtk-ai/rtk/workflows/Security%20Check/badge.svg" alt="CI"></a>
|
||||
<a href="https://github.com/rtk-ai/rtk/releases"><img src="https://img.shields.io/github/v/release/rtk-ai/rtk" alt="Release"></a>
|
||||
<a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT"></a>
|
||||
<a href="https://discord.gg/gFwRPEKq4p"><img src="https://img.shields.io/discord/1478373640461488159?label=Discord&logo=discord" alt="Discord"></a>
|
||||
<a href="https://formulae.brew.sh/formula/rtk"><img src="https://img.shields.io/homebrew/v/rtk" alt="Homebrew"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://www.rtk-ai.app">Sitio web</a> •
|
||||
<a href="#instalacion">Instalar</a> •
|
||||
<a href="docs/TROUBLESHOOTING.md">Solucion de problemas</a> •
|
||||
<a href="ARCHITECTURE.md">Arquitectura</a> •
|
||||
<a href="https://discord.gg/gFwRPEKq4p">Discord</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md">English</a> •
|
||||
<a href="README_fr.md">Francais</a> •
|
||||
<a href="README_zh.md">中文</a> •
|
||||
<a href="README_ja.md">日本語</a> •
|
||||
<a href="README_ko.md">한국어</a> •
|
||||
<a href="README_es.md">Espanol</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
rtk filtra y comprime las salidas de comandos antes de que lleguen al contexto de tu LLM. Binario Rust unico, cero dependencias, <10ms de overhead.
|
||||
|
||||
## Ahorro de tokens (sesion de 30 min en Claude Code)
|
||||
|
||||
| Operacion | Frecuencia | Estandar | rtk | Ahorro |
|
||||
|-----------|------------|----------|-----|--------|
|
||||
| `ls` / `tree` | 10x | 2,000 | 400 | -80% |
|
||||
| `cat` / `read` | 20x | 40,000 | 12,000 | -70% |
|
||||
| `grep` / `rg` | 8x | 16,000 | 3,200 | -80% |
|
||||
| `git status` | 10x | 3,000 | 600 | -80% |
|
||||
| `cargo test` / `npm test` | 5x | 25,000 | 2,500 | -90% |
|
||||
| **Total** | | **~118,000** | **~23,900** | **-80%** |
|
||||
|
||||
## Instalacion
|
||||
|
||||
### Homebrew (recomendado)
|
||||
|
||||
```bash
|
||||
brew install rtk
|
||||
```
|
||||
|
||||
### Instalacion rapida (Linux/macOS)
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/refs/heads/master/install.sh | sh
|
||||
```
|
||||
|
||||
### Cargo
|
||||
|
||||
```bash
|
||||
cargo install --git https://github.com/rtk-ai/rtk
|
||||
```
|
||||
|
||||
### Verificacion
|
||||
|
||||
```bash
|
||||
rtk --version # Debe mostrar "rtk 0.27.x"
|
||||
rtk gain # Debe mostrar estadisticas de ahorro
|
||||
```
|
||||
|
||||
## Inicio rapido
|
||||
|
||||
```bash
|
||||
# 1. Instalar hook para Claude Code (recomendado)
|
||||
rtk init --global
|
||||
|
||||
# 2. Reiniciar Claude Code, luego probar
|
||||
git status # Automaticamente reescrito a rtk git status
|
||||
```
|
||||
|
||||
## Como funciona
|
||||
|
||||
```
|
||||
Sin rtk: Con rtk:
|
||||
|
||||
Claude --git status--> shell --> git Claude --git status--> RTK --> git
|
||||
^ | ^ | |
|
||||
| ~2,000 tokens (crudo) | | ~200 tokens | filtro |
|
||||
+-----------------------------------+ +------- (filtrado) ---+----------+
|
||||
```
|
||||
|
||||
Cuatro estrategias:
|
||||
|
||||
1. **Filtrado inteligente** - Elimina ruido (comentarios, espacios, boilerplate)
|
||||
2. **Agrupacion** - Agrega elementos similares (archivos por directorio, errores por tipo)
|
||||
3. **Truncamiento** - Mantiene contexto relevante, elimina redundancia
|
||||
4. **Deduplicacion** - Colapsa lineas de log repetidas con contadores
|
||||
|
||||
## Comandos
|
||||
|
||||
### Archivos
|
||||
```bash
|
||||
rtk ls . # Arbol de directorios optimizado
|
||||
rtk read file.rs # Lectura inteligente
|
||||
rtk find "*.rs" . # Resultados compactos
|
||||
rtk grep "pattern" . # Busqueda agrupada por archivo
|
||||
```
|
||||
|
||||
### Git
|
||||
```bash
|
||||
rtk git status # Estado compacto
|
||||
rtk git log -n 10 # Commits en una linea
|
||||
rtk git diff # Diff condensado
|
||||
rtk git push # -> "ok main"
|
||||
```
|
||||
|
||||
### Tests
|
||||
```bash
|
||||
rtk test cargo test # Solo fallos (-90%)
|
||||
rtk vitest run # Vitest compacto
|
||||
rtk pytest # Tests Python (-90%)
|
||||
rtk go test # Tests Go (-90%)
|
||||
```
|
||||
|
||||
### Build & Lint
|
||||
```bash
|
||||
rtk lint # ESLint agrupado por regla
|
||||
rtk tsc # Errores TypeScript agrupados
|
||||
rtk cargo build # Build Cargo (-80%)
|
||||
rtk ruff check # Lint Python (-80%)
|
||||
```
|
||||
|
||||
### Analiticas
|
||||
```bash
|
||||
rtk gain # Estadisticas de ahorro
|
||||
rtk gain --graph # Grafico ASCII (30 dias)
|
||||
rtk discover # Descubrir ahorros perdidos
|
||||
```
|
||||
|
||||
## Documentacion
|
||||
|
||||
- **[TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md)** - Resolver problemas comunes
|
||||
- **[INSTALL.md](INSTALL.md)** - Guia de instalacion detallada
|
||||
- **[ARCHITECTURE.md](ARCHITECTURE.md)** - Arquitectura tecnica
|
||||
|
||||
## Contribuir
|
||||
|
||||
Las contribuciones son bienvenidas. Abre un issue o PR en [GitHub](https://github.com/rtk-ai/rtk).
|
||||
|
||||
Unete a la comunidad en [Discord](https://discord.gg/pvHdzAec).
|
||||
|
||||
## Licencia
|
||||
|
||||
Licencia MIT - ver [LICENSE](LICENSE) para detalles.
|
||||
-197
@@ -1,197 +0,0 @@
|
||||
<p align="center">
|
||||
<img src="https://avatars.githubusercontent.com/u/258253854?v=4" alt="RTK - Rust Token Killer" width="500">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<strong>Proxy CLI haute performance qui reduit la consommation de tokens LLM de 60-90%</strong>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/rtk-ai/rtk/actions"><img src="https://github.com/rtk-ai/rtk/workflows/Security%20Check/badge.svg" alt="CI"></a>
|
||||
<a href="https://github.com/rtk-ai/rtk/releases"><img src="https://img.shields.io/github/v/release/rtk-ai/rtk" alt="Release"></a>
|
||||
<a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT"></a>
|
||||
<a href="https://discord.gg/gFwRPEKq4p"><img src="https://img.shields.io/discord/1478373640461488159?label=Discord&logo=discord" alt="Discord"></a>
|
||||
<a href="https://formulae.brew.sh/formula/rtk"><img src="https://img.shields.io/homebrew/v/rtk" alt="Homebrew"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://www.rtk-ai.app">Site web</a> •
|
||||
<a href="#installation">Installer</a> •
|
||||
<a href="docs/TROUBLESHOOTING.md">Depannage</a> •
|
||||
<a href="ARCHITECTURE.md">Architecture</a> •
|
||||
<a href="https://discord.gg/gFwRPEKq4p">Discord</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md">English</a> •
|
||||
<a href="README_fr.md">Francais</a> •
|
||||
<a href="README_zh.md">中文</a> •
|
||||
<a href="README_ja.md">日本語</a> •
|
||||
<a href="README_ko.md">한국어</a> •
|
||||
<a href="README_es.md">Espanol</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
rtk filtre et compresse les sorties de commandes avant qu'elles n'atteignent le contexte de votre LLM. Binaire Rust unique, zero dependance, <10ms d'overhead.
|
||||
|
||||
## Economies de tokens (session Claude Code de 30 min)
|
||||
|
||||
| Operation | Frequence | Standard | rtk | Economies |
|
||||
|-----------|-----------|----------|-----|-----------|
|
||||
| `ls` / `tree` | 10x | 2 000 | 400 | -80% |
|
||||
| `cat` / `read` | 20x | 40 000 | 12 000 | -70% |
|
||||
| `grep` / `rg` | 8x | 16 000 | 3 200 | -80% |
|
||||
| `git status` | 10x | 3 000 | 600 | -80% |
|
||||
| `git diff` | 5x | 10 000 | 2 500 | -75% |
|
||||
| `git log` | 5x | 2 500 | 500 | -80% |
|
||||
| `git add/commit/push` | 8x | 1 600 | 120 | -92% |
|
||||
| `cargo test` / `npm test` | 5x | 25 000 | 2 500 | -90% |
|
||||
| **Total** | | **~118 000** | **~23 900** | **-80%** |
|
||||
|
||||
> Estimations basees sur des projets TypeScript/Rust de taille moyenne.
|
||||
|
||||
## Installation
|
||||
|
||||
### Homebrew (recommande)
|
||||
|
||||
```bash
|
||||
brew install rtk
|
||||
```
|
||||
|
||||
### Installation rapide (Linux/macOS)
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/refs/heads/master/install.sh | sh
|
||||
```
|
||||
|
||||
### Cargo
|
||||
|
||||
```bash
|
||||
cargo install --git https://github.com/rtk-ai/rtk
|
||||
```
|
||||
|
||||
### Verification
|
||||
|
||||
```bash
|
||||
rtk --version # Doit afficher "rtk 0.27.x"
|
||||
rtk gain # Doit afficher les statistiques d'economies
|
||||
```
|
||||
|
||||
> **Attention** : Un autre projet "rtk" (Rust Type Kit) existe sur crates.io. Si `rtk gain` echoue, vous avez le mauvais package.
|
||||
|
||||
## Demarrage rapide
|
||||
|
||||
```bash
|
||||
# 1. Installer le hook pour Claude Code (recommande)
|
||||
rtk init --global
|
||||
# Suivre les instructions pour enregistrer dans ~/.claude/settings.json
|
||||
|
||||
# 2. Redemarrer Claude Code, puis tester
|
||||
git status # Automatiquement reecrit en rtk git status
|
||||
```
|
||||
|
||||
Le hook reecrit de maniere transparente les commandes (ex: `git status` -> `rtk git status`) avant execution.
|
||||
|
||||
## Comment ca marche
|
||||
|
||||
```
|
||||
Sans rtk : Avec rtk :
|
||||
|
||||
Claude --git status--> shell --> git Claude --git status--> RTK --> git
|
||||
^ | ^ | |
|
||||
| ~2 000 tokens (brut) | | ~200 tokens | filtre |
|
||||
+-----------------------------------+ +------- (filtre) -----+----------+
|
||||
```
|
||||
|
||||
Quatre strategies appliquees par type de commande :
|
||||
|
||||
1. **Filtrage intelligent** - Supprime le bruit (commentaires, espaces, boilerplate)
|
||||
2. **Regroupement** - Agregat d'elements similaires (fichiers par dossier, erreurs par type)
|
||||
3. **Troncature** - Conserve le contexte pertinent, coupe la redondance
|
||||
4. **Deduplication** - Fusionne les lignes de log repetees avec compteurs
|
||||
|
||||
## Commandes
|
||||
|
||||
### Fichiers
|
||||
```bash
|
||||
rtk ls . # Arbre de repertoires optimise
|
||||
rtk read file.rs # Lecture intelligente
|
||||
rtk read file.rs -l aggressive # Signatures uniquement
|
||||
rtk find "*.rs" . # Resultats compacts
|
||||
rtk grep "pattern" . # Resultats groupes par fichier
|
||||
rtk diff file1 file2 # Diff condense
|
||||
```
|
||||
|
||||
### Git
|
||||
```bash
|
||||
rtk git status # Status compact
|
||||
rtk git log -n 10 # Commits sur une ligne
|
||||
rtk git diff # Diff condense
|
||||
rtk git add # -> "ok"
|
||||
rtk git commit -m "msg" # -> "ok abc1234"
|
||||
rtk git push # -> "ok main"
|
||||
```
|
||||
|
||||
### Tests
|
||||
```bash
|
||||
rtk test cargo test # Echecs uniquement (-90%)
|
||||
rtk vitest run # Vitest compact
|
||||
rtk pytest # Tests Python (-90%)
|
||||
rtk go test # Tests Go (-90%)
|
||||
rtk cargo test # Tests Cargo (-90%)
|
||||
```
|
||||
|
||||
### Build & Lint
|
||||
```bash
|
||||
rtk lint # ESLint groupe par regle
|
||||
rtk tsc # Erreurs TypeScript groupees
|
||||
rtk cargo build # Build Cargo (-80%)
|
||||
rtk cargo clippy # Clippy (-80%)
|
||||
rtk ruff check # Linting Python (-80%)
|
||||
```
|
||||
|
||||
### Conteneurs
|
||||
```bash
|
||||
rtk docker ps # Liste compacte
|
||||
rtk docker logs <container> # Logs dedupliques
|
||||
rtk kubectl pods # Pods compacts
|
||||
```
|
||||
|
||||
### Analytics
|
||||
```bash
|
||||
rtk gain # Statistiques d'economies
|
||||
rtk gain --graph # Graphique ASCII (30 jours)
|
||||
rtk discover # Trouver les economies manquees
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
```toml
|
||||
# ~/.config/rtk/config.toml
|
||||
[tracking]
|
||||
database_path = "/chemin/custom.db"
|
||||
|
||||
[hooks]
|
||||
exclude_commands = ["curl", "playwright"]
|
||||
|
||||
[tee]
|
||||
enabled = true
|
||||
mode = "failures"
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
- **[TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md)** - Resoudre les problemes courants
|
||||
- **[INSTALL.md](INSTALL.md)** - Guide d'installation detaille
|
||||
- **[ARCHITECTURE.md](ARCHITECTURE.md)** - Architecture technique
|
||||
|
||||
## Contribuer
|
||||
|
||||
Les contributions sont les bienvenues ! Ouvrez une issue ou une PR sur [GitHub](https://github.com/rtk-ai/rtk).
|
||||
|
||||
Rejoignez la communaute sur [Discord](https://discord.gg/pvHdzAec).
|
||||
|
||||
## Licence
|
||||
|
||||
Licence MIT - voir [LICENSE](LICENSE) pour les details.
|
||||
-159
@@ -1,159 +0,0 @@
|
||||
<p align="center">
|
||||
<img src="https://avatars.githubusercontent.com/u/258253854?v=4" alt="RTK - Rust Token Killer" width="500">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<strong>LLM トークン消費を 60-90% 削減する高性能 CLI プロキシ</strong>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/rtk-ai/rtk/actions"><img src="https://github.com/rtk-ai/rtk/workflows/Security%20Check/badge.svg" alt="CI"></a>
|
||||
<a href="https://github.com/rtk-ai/rtk/releases"><img src="https://img.shields.io/github/v/release/rtk-ai/rtk" alt="Release"></a>
|
||||
<a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT"></a>
|
||||
<a href="https://discord.gg/gFwRPEKq4p"><img src="https://img.shields.io/discord/1478373640461488159?label=Discord&logo=discord" alt="Discord"></a>
|
||||
<a href="https://formulae.brew.sh/formula/rtk"><img src="https://img.shields.io/homebrew/v/rtk" alt="Homebrew"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://www.rtk-ai.app">ウェブサイト</a> •
|
||||
<a href="#インストール">インストール</a> •
|
||||
<a href="docs/TROUBLESHOOTING.md">トラブルシューティング</a> •
|
||||
<a href="ARCHITECTURE.md">アーキテクチャ</a> •
|
||||
<a href="https://discord.gg/gFwRPEKq4p">Discord</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md">English</a> •
|
||||
<a href="README_fr.md">Francais</a> •
|
||||
<a href="README_zh.md">中文</a> •
|
||||
<a href="README_ja.md">日本語</a> •
|
||||
<a href="README_ko.md">한국어</a> •
|
||||
<a href="README_es.md">Espanol</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
rtk はコマンド出力を LLM コンテキストに届く前にフィルタリング・圧縮します。単一の Rust バイナリ、依存関係ゼロ、オーバーヘッド 10ms 未満。
|
||||
|
||||
## トークン節約(30分の Claude Code セッション)
|
||||
|
||||
| 操作 | 頻度 | 標準 | rtk | 節約 |
|
||||
|------|------|------|-----|------|
|
||||
| `ls` / `tree` | 10x | 2,000 | 400 | -80% |
|
||||
| `cat` / `read` | 20x | 40,000 | 12,000 | -70% |
|
||||
| `grep` / `rg` | 8x | 16,000 | 3,200 | -80% |
|
||||
| `git status` | 10x | 3,000 | 600 | -80% |
|
||||
| `cargo test` / `npm test` | 5x | 25,000 | 2,500 | -90% |
|
||||
| **合計** | | **~118,000** | **~23,900** | **-80%** |
|
||||
|
||||
## インストール
|
||||
|
||||
### Homebrew(推奨)
|
||||
|
||||
```bash
|
||||
brew install rtk
|
||||
```
|
||||
|
||||
### クイックインストール(Linux/macOS)
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/refs/heads/master/install.sh | sh
|
||||
```
|
||||
|
||||
### Cargo
|
||||
|
||||
```bash
|
||||
cargo install --git https://github.com/rtk-ai/rtk
|
||||
```
|
||||
|
||||
### 確認
|
||||
|
||||
```bash
|
||||
rtk --version # "rtk 0.27.x" と表示されるはず
|
||||
rtk gain # トークン節約統計が表示されるはず
|
||||
```
|
||||
|
||||
## クイックスタート
|
||||
|
||||
```bash
|
||||
# 1. Claude Code 用フックをインストール(推奨)
|
||||
rtk init --global
|
||||
|
||||
# 2. Claude Code を再起動してテスト
|
||||
git status # 自動的に rtk git status に書き換え
|
||||
```
|
||||
|
||||
## 仕組み
|
||||
|
||||
```
|
||||
rtk なし: rtk あり:
|
||||
|
||||
Claude --git status--> shell --> git Claude --git status--> RTK --> git
|
||||
^ | ^ | |
|
||||
| ~2,000 tokens(生出力) | | ~200 tokens | フィルタ |
|
||||
+-----------------------------------+ +------- (圧縮済)----+----------+
|
||||
```
|
||||
|
||||
4つの戦略:
|
||||
|
||||
1. **スマートフィルタリング** - ノイズを除去(コメント、空白、ボイラープレート)
|
||||
2. **グルーピング** - 類似項目を集約(ディレクトリ別ファイル、タイプ別エラー)
|
||||
3. **トランケーション** - 関連コンテキストを保持、冗長性をカット
|
||||
4. **重複排除** - 繰り返しログ行をカウント付きで統合
|
||||
|
||||
## コマンド
|
||||
|
||||
### ファイル
|
||||
```bash
|
||||
rtk ls . # 最適化されたディレクトリツリー
|
||||
rtk read file.rs # スマートファイル読み取り
|
||||
rtk find "*.rs" . # コンパクトな検索結果
|
||||
rtk grep "pattern" . # ファイル別グループ化検索
|
||||
```
|
||||
|
||||
### Git
|
||||
```bash
|
||||
rtk git status # コンパクトなステータス
|
||||
rtk git log -n 10 # 1行コミット
|
||||
rtk git diff # 圧縮された diff
|
||||
rtk git push # -> "ok main"
|
||||
```
|
||||
|
||||
### テスト
|
||||
```bash
|
||||
rtk test cargo test # 失敗のみ表示(-90%)
|
||||
rtk vitest run # Vitest コンパクト
|
||||
rtk pytest # Python テスト(-90%)
|
||||
rtk go test # Go テスト(-90%)
|
||||
```
|
||||
|
||||
### ビルド & リント
|
||||
```bash
|
||||
rtk lint # ESLint ルール別グループ化
|
||||
rtk tsc # TypeScript エラーグループ化
|
||||
rtk cargo build # Cargo ビルド(-80%)
|
||||
rtk ruff check # Python リント(-80%)
|
||||
```
|
||||
|
||||
### 分析
|
||||
```bash
|
||||
rtk gain # 節約統計
|
||||
rtk gain --graph # ASCII グラフ(30日間)
|
||||
rtk discover # 見逃した節約機会を発見
|
||||
```
|
||||
|
||||
## ドキュメント
|
||||
|
||||
- **[TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md)** - よくある問題の解決
|
||||
- **[INSTALL.md](INSTALL.md)** - 詳細インストールガイド
|
||||
- **[ARCHITECTURE.md](ARCHITECTURE.md)** - 技術アーキテクチャ
|
||||
|
||||
## コントリビュート
|
||||
|
||||
コントリビューション歓迎 で issue または PR を作成してください。
|
||||
|
||||
[Discord](https://discord.gg/pvHdzAec) コミュニティに参加。
|
||||
|
||||
## ライセンス
|
||||
|
||||
MIT ライセンス - 詳細は [LICENSE](LICENSE) を参照。
|
||||
-159
@@ -1,159 +0,0 @@
|
||||
<p align="center">
|
||||
<img src="https://avatars.githubusercontent.com/u/258253854?v=4" alt="RTK - Rust Token Killer" width="500">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<strong>LLM 토큰 소비를 60-90% 줄이는 고성능 CLI 프록시</strong>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/rtk-ai/rtk/actions"><img src="https://github.com/rtk-ai/rtk/workflows/Security%20Check/badge.svg" alt="CI"></a>
|
||||
<a href="https://github.com/rtk-ai/rtk/releases"><img src="https://img.shields.io/github/v/release/rtk-ai/rtk" alt="Release"></a>
|
||||
<a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT"></a>
|
||||
<a href="https://discord.gg/gFwRPEKq4p"><img src="https://img.shields.io/discord/1478373640461488159?label=Discord&logo=discord" alt="Discord"></a>
|
||||
<a href="https://formulae.brew.sh/formula/rtk"><img src="https://img.shields.io/homebrew/v/rtk" alt="Homebrew"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://www.rtk-ai.app">웹사이트</a> •
|
||||
<a href="#설치">설치</a> •
|
||||
<a href="docs/TROUBLESHOOTING.md">문제 해결</a> •
|
||||
<a href="ARCHITECTURE.md">아키텍처</a> •
|
||||
<a href="https://discord.gg/gFwRPEKq4p">Discord</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md">English</a> •
|
||||
<a href="README_fr.md">Francais</a> •
|
||||
<a href="README_zh.md">中文</a> •
|
||||
<a href="README_ja.md">日本語</a> •
|
||||
<a href="README_ko.md">한국어</a> •
|
||||
<a href="README_es.md">Espanol</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
rtk는 명령 출력이 LLM 컨텍스트에 도달하기 전에 필터링하고 압축합니다. 단일 Rust 바이너리, 의존성 없음, 10ms 미만의 오버헤드.
|
||||
|
||||
## 토큰 절약 (30분 Claude Code 세션)
|
||||
|
||||
| 작업 | 빈도 | 표준 | rtk | 절약 |
|
||||
|------|------|------|-----|------|
|
||||
| `ls` / `tree` | 10x | 2,000 | 400 | -80% |
|
||||
| `cat` / `read` | 20x | 40,000 | 12,000 | -70% |
|
||||
| `grep` / `rg` | 8x | 16,000 | 3,200 | -80% |
|
||||
| `git status` | 10x | 3,000 | 600 | -80% |
|
||||
| `cargo test` / `npm test` | 5x | 25,000 | 2,500 | -90% |
|
||||
| **합계** | | **~118,000** | **~23,900** | **-80%** |
|
||||
|
||||
## 설치
|
||||
|
||||
### Homebrew (권장)
|
||||
|
||||
```bash
|
||||
brew install rtk
|
||||
```
|
||||
|
||||
### 빠른 설치 (Linux/macOS)
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/refs/heads/master/install.sh | sh
|
||||
```
|
||||
|
||||
### Cargo
|
||||
|
||||
```bash
|
||||
cargo install --git https://github.com/rtk-ai/rtk
|
||||
```
|
||||
|
||||
### 확인
|
||||
|
||||
```bash
|
||||
rtk --version # "rtk 0.27.x" 표시되어야 함
|
||||
rtk gain # 토큰 절약 통계 표시되어야 함
|
||||
```
|
||||
|
||||
## 빠른 시작
|
||||
|
||||
```bash
|
||||
# 1. Claude Code용 hook 설치 (권장)
|
||||
rtk init --global
|
||||
|
||||
# 2. Claude Code 재시작 후 테스트
|
||||
git status # 자동으로 rtk git status로 재작성
|
||||
```
|
||||
|
||||
## 작동 원리
|
||||
|
||||
```
|
||||
rtk 없이: rtk 사용:
|
||||
|
||||
Claude --git status--> shell --> git Claude --git status--> RTK --> git
|
||||
^ | ^ | |
|
||||
| ~2,000 tokens (원본) | | ~200 tokens | 필터 |
|
||||
+-----------------------------------+ +------- (필터링) -----+----------+
|
||||
```
|
||||
|
||||
네 가지 전략:
|
||||
|
||||
1. **스마트 필터링** - 노이즈 제거 (주석, 공백, 보일러플레이트)
|
||||
2. **그룹화** - 유사 항목 집계 (디렉토리별 파일, 유형별 에러)
|
||||
3. **잘라내기** - 관련 컨텍스트 유지, 중복 제거
|
||||
4. **중복 제거** - 반복 로그 라인을 카운트와 함께 통합
|
||||
|
||||
## 명령어
|
||||
|
||||
### 파일
|
||||
```bash
|
||||
rtk ls . # 최적화된 디렉토리 트리
|
||||
rtk read file.rs # 스마트 파일 읽기
|
||||
rtk find "*.rs" . # 컴팩트한 검색 결과
|
||||
rtk grep "pattern" . # 파일별 그룹화 검색
|
||||
```
|
||||
|
||||
### Git
|
||||
```bash
|
||||
rtk git status # 컴팩트 상태
|
||||
rtk git log -n 10 # 한 줄 커밋
|
||||
rtk git diff # 압축된 diff
|
||||
rtk git push # -> "ok main"
|
||||
```
|
||||
|
||||
### 테스트
|
||||
```bash
|
||||
rtk test cargo test # 실패만 표시 (-90%)
|
||||
rtk vitest run # Vitest 컴팩트
|
||||
rtk pytest # Python 테스트 (-90%)
|
||||
rtk go test # Go 테스트 (-90%)
|
||||
```
|
||||
|
||||
### 빌드 & 린트
|
||||
```bash
|
||||
rtk lint # ESLint 규칙별 그룹화
|
||||
rtk tsc # TypeScript 에러 그룹화
|
||||
rtk cargo build # Cargo 빌드 (-80%)
|
||||
rtk ruff check # Python 린트 (-80%)
|
||||
```
|
||||
|
||||
### 분석
|
||||
```bash
|
||||
rtk gain # 절약 통계
|
||||
rtk gain --graph # ASCII 그래프 (30일)
|
||||
rtk discover # 놓친 절약 기회 발견
|
||||
```
|
||||
|
||||
## 문서
|
||||
|
||||
- **[TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md)** - 일반적인 문제 해결
|
||||
- **[INSTALL.md](INSTALL.md)** - 상세 설치 가이드
|
||||
- **[ARCHITECTURE.md](ARCHITECTURE.md)** - 기술 아키텍처
|
||||
|
||||
## 기여
|
||||
|
||||
기여를 환영합니다! [GitHub](https://github.com/rtk-ai/rtk)에서 issue 또는 PR을 생성해 주세요.
|
||||
|
||||
[Discord](https://discord.gg/pvHdzAec) 커뮤니티에 참여하세요.
|
||||
|
||||
## 라이선스
|
||||
|
||||
MIT 라이선스 - 자세한 내용은 [LICENSE](LICENSE)를 참조하세요.
|
||||
-167
@@ -1,167 +0,0 @@
|
||||
<p align="center">
|
||||
<img src="https://avatars.githubusercontent.com/u/258253854?v=4" alt="RTK - Rust Token Killer" width="500">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<strong>高性能 CLI 代理,将 LLM token 消耗降低 60-90%</strong>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/rtk-ai/rtk/actions"><img src="https://github.com/rtk-ai/rtk/workflows/Security%20Check/badge.svg" alt="CI"></a>
|
||||
<a href="https://github.com/rtk-ai/rtk/releases"><img src="https://img.shields.io/github/v/release/rtk-ai/rtk" alt="Release"></a>
|
||||
<a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT"></a>
|
||||
<a href="https://discord.gg/gFwRPEKq4p"><img src="https://img.shields.io/discord/1478373640461488159?label=Discord&logo=discord" alt="Discord"></a>
|
||||
<a href="https://formulae.brew.sh/formula/rtk"><img src="https://img.shields.io/homebrew/v/rtk" alt="Homebrew"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://www.rtk-ai.app">官网</a> •
|
||||
<a href="#安装">安装</a> •
|
||||
<a href="docs/TROUBLESHOOTING.md">故障排除</a> •
|
||||
<a href="ARCHITECTURE.md">架构</a> •
|
||||
<a href="https://discord.gg/gFwRPEKq4p">Discord</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md">English</a> •
|
||||
<a href="README_fr.md">Francais</a> •
|
||||
<a href="README_zh.md">中文</a> •
|
||||
<a href="README_ja.md">日本語</a> •
|
||||
<a href="README_ko.md">한국어</a> •
|
||||
<a href="README_es.md">Espanol</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
rtk 在命令输出到达 LLM 上下文之前进行过滤和压缩。单一 Rust 二进制文件,零依赖,<10ms 开销。
|
||||
|
||||
## Token 节省(30 分钟 Claude Code 会话)
|
||||
|
||||
| 操作 | 频率 | 标准 | rtk | 节省 |
|
||||
|------|------|------|-----|------|
|
||||
| `ls` / `tree` | 10x | 2,000 | 400 | -80% |
|
||||
| `cat` / `read` | 20x | 40,000 | 12,000 | -70% |
|
||||
| `grep` / `rg` | 8x | 16,000 | 3,200 | -80% |
|
||||
| `git status` | 10x | 3,000 | 600 | -80% |
|
||||
| `git diff` | 5x | 10,000 | 2,500 | -75% |
|
||||
| `cargo test` / `npm test` | 5x | 25,000 | 2,500 | -90% |
|
||||
| **总计** | | **~118,000** | **~23,900** | **-80%** |
|
||||
|
||||
## 安装
|
||||
|
||||
### Homebrew(推荐)
|
||||
|
||||
```bash
|
||||
brew install rtk
|
||||
```
|
||||
|
||||
### 快速安装(Linux/macOS)
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/refs/heads/master/install.sh | sh
|
||||
```
|
||||
|
||||
### Cargo
|
||||
|
||||
```bash
|
||||
cargo install --git https://github.com/rtk-ai/rtk
|
||||
```
|
||||
|
||||
### 验证
|
||||
|
||||
```bash
|
||||
rtk --version # 应显示 "rtk 0.27.x"
|
||||
rtk gain # 应显示 token 节省统计
|
||||
```
|
||||
|
||||
## 快速开始
|
||||
|
||||
```bash
|
||||
# 1. 为 Claude Code 安装 hook(推荐)
|
||||
rtk init --global
|
||||
|
||||
# 2. 重启 Claude Code,然后测试
|
||||
git status # 自动重写为 rtk git status
|
||||
```
|
||||
|
||||
## 工作原理
|
||||
|
||||
```
|
||||
没有 rtk: 使用 rtk:
|
||||
|
||||
Claude --git status--> shell --> git Claude --git status--> RTK --> git
|
||||
^ | ^ | |
|
||||
| ~2,000 tokens(原始) | | ~200 tokens | 过滤 |
|
||||
+-----------------------------------+ +------- (已过滤)-----+----------+
|
||||
```
|
||||
|
||||
四种策略:
|
||||
|
||||
1. **智能过滤** - 去除噪音(注释、空白、样板代码)
|
||||
2. **分组** - 聚合相似项(按目录分文件,按类型分错误)
|
||||
3. **截断** - 保留相关上下文,删除冗余
|
||||
4. **去重** - 合并重复日志行并计数
|
||||
|
||||
## 命令
|
||||
|
||||
### 文件
|
||||
```bash
|
||||
rtk ls . # 优化的目录树
|
||||
rtk read file.rs # 智能文件读取
|
||||
rtk find "*.rs" . # 紧凑的查找结果
|
||||
rtk grep "pattern" . # 按文件分组的搜索结果
|
||||
```
|
||||
|
||||
### Git
|
||||
```bash
|
||||
rtk git status # 紧凑状态
|
||||
rtk git log -n 10 # 单行提交
|
||||
rtk git diff # 精简 diff
|
||||
rtk git push # -> "ok main"
|
||||
```
|
||||
|
||||
### 测试
|
||||
```bash
|
||||
rtk test cargo test # 仅显示失败(-90%)
|
||||
rtk vitest run # Vitest 紧凑输出
|
||||
rtk pytest # Python 测试(-90%)
|
||||
rtk go test # Go 测试(-90%)
|
||||
```
|
||||
|
||||
### 构建 & 检查
|
||||
```bash
|
||||
rtk lint # ESLint 按规则分组
|
||||
rtk tsc # TypeScript 错误分组
|
||||
rtk cargo build # Cargo 构建(-80%)
|
||||
rtk ruff check # Python lint(-80%)
|
||||
```
|
||||
|
||||
### 容器
|
||||
```bash
|
||||
rtk docker ps # 紧凑容器列表
|
||||
rtk docker logs <container> # 去重日志
|
||||
rtk kubectl pods # 紧凑 Pod 列表
|
||||
```
|
||||
|
||||
### 分析
|
||||
```bash
|
||||
rtk gain # 节省统计
|
||||
rtk gain --graph # ASCII 图表(30 天)
|
||||
rtk discover # 发现遗漏的节省机会
|
||||
```
|
||||
|
||||
## 文档
|
||||
|
||||
- **[TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md)** - 解决常见问题
|
||||
- **[INSTALL.md](INSTALL.md)** - 详细安装指南
|
||||
- **[ARCHITECTURE.md](ARCHITECTURE.md)** - 技术架构
|
||||
|
||||
## 贡献
|
||||
|
||||
欢迎贡献!请在 [GitHub](https://github.com/rtk-ai/rtk) 上提交 issue 或 PR。
|
||||
|
||||
加入 [Discord](https://discord.gg/pvHdzAec) 社区。
|
||||
|
||||
## 许可证
|
||||
|
||||
MIT 许可证 - 详见 [LICENSE](LICENSE)。
|
||||
@@ -1,57 +0,0 @@
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
fn main() {
|
||||
let filters_dir = Path::new("src/filters");
|
||||
let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR must be set by Cargo");
|
||||
let dest = Path::new(&out_dir).join("builtin_filters.toml");
|
||||
|
||||
// Rebuild when any file in src/filters/ changes
|
||||
println!("cargo:rerun-if-changed=src/filters");
|
||||
|
||||
let mut files: Vec<_> = fs::read_dir(filters_dir)
|
||||
.expect("src/filters/ directory must exist")
|
||||
.filter_map(|e| e.ok())
|
||||
.filter(|e| e.path().extension().is_some_and(|ext| ext == "toml"))
|
||||
.collect();
|
||||
|
||||
// Sort alphabetically for deterministic filter ordering
|
||||
files.sort_by_key(|e| e.file_name());
|
||||
|
||||
let mut combined = String::from("schema_version = 1\n\n");
|
||||
|
||||
for entry in &files {
|
||||
let content = fs::read_to_string(entry.path())
|
||||
.unwrap_or_else(|e| panic!("Failed to read {:?}: {}", entry.path(), e));
|
||||
combined.push_str(&format!(
|
||||
"# --- {} ---\n",
|
||||
entry.file_name().to_string_lossy()
|
||||
));
|
||||
combined.push_str(&content);
|
||||
combined.push_str("\n\n");
|
||||
}
|
||||
|
||||
// Validate: parse the combined TOML to catch errors at build time
|
||||
let parsed: toml::Value = combined.parse().unwrap_or_else(|e| {
|
||||
panic!(
|
||||
"TOML validation failed for combined filters:\n{}\n\nCheck src/filters/*.toml files",
|
||||
e
|
||||
)
|
||||
});
|
||||
|
||||
// Detect duplicate filter names across files
|
||||
if let Some(filters) = parsed.get("filters").and_then(|f| f.as_table()) {
|
||||
let mut seen: HashSet<String> = HashSet::new();
|
||||
for key in filters.keys() {
|
||||
if !seen.insert(key.clone()) {
|
||||
panic!(
|
||||
"Duplicate filter name '{}' found across src/filters/*.toml files",
|
||||
key
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fs::write(&dest, combined).expect("Failed to write combined builtin_filters.toml");
|
||||
}
|
||||
-1410
File diff suppressed because it is too large.
Load diff
@@ -1,102 +0,0 @@
|
||||
# How a TOML filter goes from file to execution
|
||||
|
||||
This document explains what happens between "I created `src/filters/my-tool.toml`" and "RTK filters the output of `my-tool`".
|
||||
|
||||
## Build pipeline
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[["📄 src/filters/my-tool.toml\n(new file)"]] --> B
|
||||
|
||||
subgraph BUILD ["🔨 cargo build"]
|
||||
B["build.rs\n① ls src/filters/*.toml\n② sort alphabetically\n③ concat → schema_version = 1 + all files"] --> C
|
||||
C{"TOML valid?\nDuplicate names?"} -->|"❌ panic! (build fails)"| D[["🛑 Error message\npoints to bad file"]]
|
||||
C -->|"✅ ok"| E[["OUT_DIR/builtin_filters.toml\n(generated file)"]]
|
||||
E --> F["rustc\ninclude_str!(concat!(env!(OUT_DIR),\n'/builtin_filters.toml'))"]
|
||||
F --> G[["🦀 rtk binary\nBUILTIN_TOML embedded"]]
|
||||
end
|
||||
|
||||
subgraph TESTS ["🧪 cargo test"]
|
||||
H["test_builtin_filter_count\nassert_eq!(filters.len(), N)"] -->|"❌ count wrong"| I[["FAIL\n'Expected N, got N+1'\nUpdate the count'"]]
|
||||
J["test_builtin_all_expected_\nfilters_present\nassert!(names.contains('my-tool'))"] -->|"❌ name missing"| K[["FAIL\n'my-tool is missing—\nwas its .toml deleted?'"]]
|
||||
L["test_builtin_all_filters_\nhave_inline_tests\nassert!(tested.contains(name))"] -->|"❌ no tests"| M[["FAIL\n'Add tests.my-tool\nentries'"]]
|
||||
end
|
||||
|
||||
subgraph VERIFY ["✅ rtk verify"]
|
||||
N["runs [[tests.my-tool]]\ninput → filter → compare expected"]
|
||||
N -->|"❌ mismatch"| O[["FAIL\nshows actual vs expected"]]
|
||||
N -->|"✅ pass"| P[["60/60 tests passed"]]
|
||||
end
|
||||
|
||||
G --> H
|
||||
G --> J
|
||||
G --> L
|
||||
G --> N
|
||||
|
||||
subgraph RUNTIME ["⚡ rtk my-tool --verbose"]
|
||||
Q["Claude Code hook\nmy-tool ... → rtk my-tool ..."] --> R
|
||||
R["TomlFilterRegistry::load()\n① .rtk/filters.toml (project)\n② ~/.config/rtk/filters.toml (user)\n③ BUILTIN_TOML (binary)\n④ passthrough"] --> S
|
||||
S{"match_command\n'^my-tool\\b'\nmatches?"} -->|"No match"| T[["exec raw\n(passthrough)"]]
|
||||
S -->|"✅ match"| U["exec command\ncapture stdout"]
|
||||
U --> V
|
||||
|
||||
subgraph PIPELINE ["8-stage filter pipeline"]
|
||||
V["strip_ansi"] --> W["replace"]
|
||||
W --> X{"match_output\nshort-circuit?"}
|
||||
X -->|"✅ pattern matched"| Y[["emit message\nstop pipeline"]]
|
||||
X -->|"no match"| Z["strip/keep_lines"]
|
||||
Z --> AA["truncate_lines_at"]
|
||||
AA --> AB["tail_lines"]
|
||||
AB --> AC["max_lines"]
|
||||
AC --> AD{"output\nempty?"}
|
||||
AD -->|"yes"| AE[["emit on_empty"]]
|
||||
AD -->|"no"| AF[["print filtered\noutput + exit code"]]
|
||||
end
|
||||
end
|
||||
|
||||
G --> Q
|
||||
|
||||
style BUILD fill:#1e3a5f,color:#fff
|
||||
style TESTS fill:#1a3a1a,color:#fff
|
||||
style VERIFY fill:#2d1b69,color:#fff
|
||||
style RUNTIME fill:#3a1a1a,color:#fff
|
||||
style PIPELINE fill:#4a2a00,color:#fff
|
||||
style D fill:#8b0000,color:#fff
|
||||
style I fill:#8b0000,color:#fff
|
||||
style K fill:#8b0000,color:#fff
|
||||
style M fill:#8b0000,color:#fff
|
||||
style O fill:#8b0000,color:#fff
|
||||
```
|
||||
|
||||
## Step-by-step summary
|
||||
|
||||
| Step | Who | What happens | Fails if |
|
||||
|------|-----|--------------|----------|
|
||||
| 1 | Contributor | Creates `src/filters/my-tool.toml` | — |
|
||||
| 2 | `build.rs` | Concatenates all `.toml` files alphabetically | TOML syntax error, duplicate filter name |
|
||||
| 3 | `rustc` | Embeds result in binary via `BUILTIN_TOML` const | — |
|
||||
| 4 | `cargo test` | 3 guards check count, names, inline test presence | Count not updated, name not in list, no `[[tests.*]]` |
|
||||
| 5 | `rtk verify` | Runs each `[[tests.my-tool]]` entry | Filter logic doesn't match expected output |
|
||||
| 6 | Runtime | Hook rewrites command, registry looks up filter, pipeline runs | No match → passthrough (not an error) |
|
||||
|
||||
## Filter lookup priority at runtime
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
CMD["rtk my-tool args"] --> P1
|
||||
P1{"1. .rtk/filters.toml\n(project-local)"}
|
||||
P1 -->|"✅ match"| WIN["apply filter"]
|
||||
P1 -->|"no match"| P2
|
||||
P2{"2. ~/.config/rtk/filters.toml\n(user-global)\n(macOS alt: ~/Library/Application Support/rtk/filters.toml)"}
|
||||
P2 -->|"✅ match"| WIN
|
||||
P2 -->|"no match"| P3
|
||||
P3{"3. BUILTIN_TOML\n(binary)"}
|
||||
P3 -->|"✅ match"| WIN
|
||||
P3 -->|"no match"| P4[["exec raw\n(passthrough)"]]
|
||||
```
|
||||
|
||||
First match wins. A project filter with the same name as a built-in shadows the built-in and triggers a warning:
|
||||
|
||||
```
|
||||
[rtk] warning: filter 'make' is shadowing a built-in filter
|
||||
```
|
||||
@@ -8,12 +8,10 @@
|
||||
# To add or change rewrite rules, edit the Rust registry — not this file.
|
||||
|
||||
if ! command -v jq &>/dev/null; then
|
||||
echo "[rtk] WARNING: jq is not installed. Hook cannot rewrite commands. Install jq: https://jqlang.github.io/jq/download/" >&2
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if ! command -v rtk &>/dev/null; then
|
||||
echo "[rtk] WARNING: rtk is not installed or not in PATH. Hook cannot rewrite commands. Install: https://github.com/rtk-ai/rtk#installation" >&2
|
||||
exit 0
|
||||
fi
|
||||
|
||||
|
||||
+9
-60
@@ -174,7 +174,7 @@ section "git"
|
||||
bench "git status" "git status" "$RTK git status"
|
||||
bench "git log -n 10" "git log -10" "$RTK git log -n 10"
|
||||
bench "git log -n 5" "git log -5" "$RTK git log -n 5"
|
||||
bench "git diff" "git diff HEAD~1 2>/dev/null || echo ''" "$RTK git diff HEAD~1"
|
||||
bench "git diff" "git diff HEAD~1 2>/dev/null || echo ''" "$RTK git diff"
|
||||
|
||||
# ===================
|
||||
# grep
|
||||
@@ -228,21 +228,13 @@ bench "env --show-all" "env" "$RTK env --show-all"
|
||||
# err
|
||||
# ===================
|
||||
section "err"
|
||||
if command -v cargo &>/dev/null; then
|
||||
bench "err cargo build" "cargo build 2>&1 || true" "$RTK err cargo build"
|
||||
else
|
||||
echo "⏭️ err cargo build (cargo not in PATH, skipped)"
|
||||
fi
|
||||
bench "err cargo build" "cargo build 2>&1 || true" "$RTK err cargo build"
|
||||
|
||||
# ===================
|
||||
# test
|
||||
# ===================
|
||||
section "test"
|
||||
if command -v cargo &>/dev/null; then
|
||||
bench "test cargo test" "cargo test 2>&1 || true" "$RTK test cargo test"
|
||||
else
|
||||
echo "⏭️ test cargo test (cargo not in PATH, skipped)"
|
||||
fi
|
||||
bench "test cargo test" "cargo test 2>&1 || true" "$RTK test cargo test"
|
||||
|
||||
# ===================
|
||||
# log
|
||||
@@ -271,29 +263,17 @@ rm -f "$LOG_FILE"
|
||||
# summary
|
||||
# ===================
|
||||
section "summary"
|
||||
if command -v cargo &>/dev/null; then
|
||||
bench "summary cargo --help" "cargo --help" "$RTK summary cargo --help"
|
||||
else
|
||||
echo "⏭️ summary cargo --help (cargo not in PATH, skipped)"
|
||||
fi
|
||||
if command -v rustc &>/dev/null; then
|
||||
bench "summary rustc --help" "rustc --help 2>/dev/null || echo 'rustc not found'" "$RTK summary rustc --help"
|
||||
else
|
||||
echo "⏭️ summary rustc --help (rustc not in PATH, skipped)"
|
||||
fi
|
||||
bench "summary cargo --help" "cargo --help" "$RTK summary cargo --help"
|
||||
bench "summary rustc --help" "rustc --help 2>/dev/null || echo 'rustc not found'" "$RTK summary rustc --help"
|
||||
|
||||
# ===================
|
||||
# cargo
|
||||
# ===================
|
||||
section "cargo"
|
||||
if command -v cargo &>/dev/null; then
|
||||
bench "cargo build" "cargo build 2>&1 || true" "$RTK cargo build"
|
||||
bench "cargo test" "cargo test 2>&1 || true" "$RTK cargo test"
|
||||
bench "cargo clippy" "cargo clippy 2>&1 || true" "$RTK cargo clippy"
|
||||
bench "cargo check" "cargo check 2>&1 || true" "$RTK cargo check"
|
||||
else
|
||||
echo "⏭️ cargo build/test/clippy/check (cargo not in PATH, skipped)"
|
||||
fi
|
||||
bench "cargo build" "cargo build 2>&1 || true" "$RTK cargo build"
|
||||
bench "cargo test" "cargo test 2>&1 || true" "$RTK cargo test"
|
||||
bench "cargo clippy" "cargo clippy 2>&1 || true" "$RTK cargo clippy"
|
||||
bench "cargo check" "cargo check 2>&1 || true" "$RTK cargo check"
|
||||
|
||||
# ===================
|
||||
# diff
|
||||
@@ -526,37 +506,6 @@ GOEOF
|
||||
rm -rf "$GO_FIXTURE"
|
||||
fi
|
||||
|
||||
# ===================
|
||||
# rewrite (verify rewrite works with and without quotes)
|
||||
# ===================
|
||||
section "rewrite"
|
||||
|
||||
# bench_rewrite: verifies rewrite produces expected output (not token comparison)
|
||||
bench_rewrite() {
|
||||
local name="$1"
|
||||
local cmd="$2"
|
||||
local expected="$3"
|
||||
|
||||
result=$(eval "$cmd" 2>&1 || true)
|
||||
|
||||
TOTAL_TESTS=$((TOTAL_TESTS + 1))
|
||||
|
||||
if [ "$result" = "$expected" ]; then
|
||||
printf "✅ %-24s │ %-40s │ %s\n" "$name" "$cmd" "$result"
|
||||
GOOD_TESTS=$((GOOD_TESTS + 1))
|
||||
else
|
||||
printf "❌ %-24s │ %-40s │ got: %s (expected: %s)\n" "$name" "$cmd" "$result" "$expected"
|
||||
FAIL_TESTS=$((FAIL_TESTS + 1))
|
||||
fi
|
||||
}
|
||||
|
||||
bench_rewrite "rewrite quoted" "$RTK rewrite 'git status'" "rtk git status"
|
||||
bench_rewrite "rewrite unquoted" "$RTK rewrite git status" "rtk git status"
|
||||
bench_rewrite "rewrite ls -al" "$RTK rewrite ls -al" "rtk ls -al"
|
||||
bench_rewrite "rewrite npm exec" "$RTK rewrite npm exec" "rtk npm exec"
|
||||
bench_rewrite "rewrite cargo test" "$RTK rewrite cargo test" "rtk cargo test"
|
||||
bench_rewrite "rewrite compound" "$RTK rewrite 'cargo test && git push'" "rtk cargo test && rtk git push"
|
||||
|
||||
# ===================
|
||||
# Résumé global
|
||||
# ===================
|
||||
|
||||
+3
-14
@@ -426,31 +426,20 @@ else
|
||||
skip_test "rtk golangci-lint" "golangci-lint not installed"
|
||||
fi
|
||||
|
||||
# ── 29. Graphite (conditional) ─────────────────────
|
||||
|
||||
section "Graphite (conditional)"
|
||||
|
||||
if command -v gt &>/dev/null; then
|
||||
assert_help "rtk gt" rtk gt --help
|
||||
assert_ok "rtk gt log short" rtk gt log short
|
||||
else
|
||||
skip "gt not installed"
|
||||
fi
|
||||
|
||||
# ── 30. Global flags ────────────────────────────────
|
||||
# ── 29. Global flags ────────────────────────────────
|
||||
|
||||
section "Global flags"
|
||||
|
||||
assert_ok "rtk -u ls ." rtk -u ls .
|
||||
assert_ok "rtk --skip-env npm --help" rtk --skip-env npm --help
|
||||
|
||||
# ── 31. CcEconomics ─────────────────────────────────
|
||||
# ── 30. CcEconomics ─────────────────────────────────
|
||||
|
||||
section "CcEconomics"
|
||||
|
||||
assert_ok "rtk cc-economics" rtk cc-economics
|
||||
|
||||
# ── 32. Learn ───────────────────────────────────────
|
||||
# ── 31. Learn ───────────────────────────────────────
|
||||
|
||||
section "Learn"
|
||||
|
||||
|
||||
+1
-36
@@ -7,10 +7,7 @@ use anyhow::Result;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use provider::{ClaudeProvider, SessionProvider};
|
||||
use registry::{
|
||||
category_avg_tokens, classify_command, has_rtk_disabled_prefix, split_command_chain,
|
||||
strip_disabled_prefix, Classification,
|
||||
};
|
||||
use registry::{category_avg_tokens, classify_command, split_command_chain, Classification};
|
||||
use report::{DiscoverReport, SupportedEntry, UnsupportedEntry};
|
||||
|
||||
/// Aggregation bucket for supported commands.
|
||||
@@ -65,8 +62,6 @@ pub fn run(
|
||||
let mut total_commands: usize = 0;
|
||||
let mut already_rtk: usize = 0;
|
||||
let mut parse_errors: usize = 0;
|
||||
let mut rtk_disabled_count: usize = 0;
|
||||
let mut rtk_disabled_cmds: HashMap<String, usize> = HashMap::new();
|
||||
let mut supported_map: HashMap<&'static str, SupportedBucket> = HashMap::new();
|
||||
let mut unsupported_map: HashMap<String, UnsupportedBucket> = HashMap::new();
|
||||
|
||||
@@ -87,23 +82,6 @@ pub fn run(
|
||||
for part in parts {
|
||||
total_commands += 1;
|
||||
|
||||
// Detect RTK_DISABLED= bypass before classification
|
||||
if has_rtk_disabled_prefix(part) {
|
||||
let actual_cmd = strip_disabled_prefix(part);
|
||||
// Only count if the underlying command is one RTK supports
|
||||
match classify_command(actual_cmd) {
|
||||
Classification::Supported { .. } => {
|
||||
rtk_disabled_count += 1;
|
||||
let display = truncate_command(actual_cmd);
|
||||
*rtk_disabled_cmds.entry(display).or_insert(0) += 1;
|
||||
}
|
||||
_ => {
|
||||
// RTK_DISABLED on unsupported/ignored command — not interesting
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
match classify_command(part) {
|
||||
Classification::Supported {
|
||||
rtk_equivalent,
|
||||
@@ -220,17 +198,6 @@ pub fn run(
|
||||
// Sort by count descending
|
||||
unsupported.sort_by(|a, b| b.count.cmp(&a.count));
|
||||
|
||||
// Build RTK_DISABLED examples sorted by frequency (top 5)
|
||||
let rtk_disabled_examples: Vec<String> = {
|
||||
let mut sorted: Vec<_> = rtk_disabled_cmds.into_iter().collect();
|
||||
sorted.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
|
||||
sorted
|
||||
.into_iter()
|
||||
.take(5)
|
||||
.map(|(cmd, count)| format!("{} ({}x)", cmd, count))
|
||||
.collect()
|
||||
};
|
||||
|
||||
let report = DiscoverReport {
|
||||
sessions_scanned: sessions.len(),
|
||||
total_commands,
|
||||
@@ -239,8 +206,6 @@ pub fn run(
|
||||
supported,
|
||||
unsupported,
|
||||
parse_errors,
|
||||
rtk_disabled_count,
|
||||
rtk_disabled_examples,
|
||||
};
|
||||
|
||||
match format {
|
||||
|
||||
+13
-271
@@ -48,10 +48,6 @@ lazy_static! {
|
||||
.collect();
|
||||
static ref ENV_PREFIX: Regex =
|
||||
Regex::new(r"^(?:sudo\s+|env\s+|[A-Z_][A-Z0-9_]*=[^\s]*\s+)+").unwrap();
|
||||
// Git global options that appear before the subcommand: -C <path>, -c <key=val>,
|
||||
// --git-dir <dir>, --work-tree <dir>, and flag-only options (#163)
|
||||
static ref GIT_GLOBAL_OPT: Regex =
|
||||
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();
|
||||
}
|
||||
|
||||
/// Classify a single (already-split) command.
|
||||
@@ -80,32 +76,6 @@ pub fn classify_command(cmd: &str) -> Classification {
|
||||
return Classification::Ignored;
|
||||
}
|
||||
|
||||
// Normalize absolute binary paths: /usr/bin/grep → grep (#485)
|
||||
let cmd_normalized = strip_absolute_path(cmd_clean);
|
||||
// Strip git global options: git -C /tmp status → git status (#163)
|
||||
let cmd_normalized = strip_git_global_opts(&cmd_normalized);
|
||||
let cmd_clean = cmd_normalized.as_str();
|
||||
|
||||
// Exclude cat/head/tail with redirect operators — these are writes, not reads (#315)
|
||||
if cmd_clean.starts_with("cat ")
|
||||
|| cmd_clean.starts_with("head ")
|
||||
|| cmd_clean.starts_with("tail ")
|
||||
{
|
||||
let has_redirect = cmd_clean
|
||||
.split_whitespace()
|
||||
.skip(1)
|
||||
.any(|t| t.starts_with('>') || t == "<" || t.starts_with(">>"));
|
||||
if has_redirect {
|
||||
return Classification::Unsupported {
|
||||
base_command: cmd_clean
|
||||
.split_whitespace()
|
||||
.next()
|
||||
.unwrap_or("cat")
|
||||
.to_string(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Fast check with RegexSet — take the last (most specific) match
|
||||
let matches: Vec<usize> = REGEX_SET.matches(cmd_clean).into_iter().collect();
|
||||
if let Some(&idx) = matches.last() {
|
||||
@@ -272,61 +242,6 @@ pub fn split_command_chain(cmd: &str) -> Vec<&str> {
|
||||
results
|
||||
}
|
||||
|
||||
/// Strip git global options before the subcommand (#163).
|
||||
/// `git -C /tmp status` → `git status`, preserving the rest.
|
||||
/// Returns the original string unchanged if not a git command.
|
||||
fn strip_git_global_opts(cmd: &str) -> String {
|
||||
// Only applies to commands starting with "git "
|
||||
if !cmd.starts_with("git ") {
|
||||
return cmd.to_string();
|
||||
}
|
||||
let after_git = &cmd[4..]; // skip "git "
|
||||
let stripped = GIT_GLOBAL_OPT.replace(after_git, "");
|
||||
format!("git {}", stripped.trim())
|
||||
}
|
||||
|
||||
/// Normalize absolute binary paths: `/usr/bin/grep -rn foo` → `grep -rn foo` (#485)
|
||||
/// Only strips if the first word contains a `/` (Unix path).
|
||||
fn strip_absolute_path(cmd: &str) -> String {
|
||||
let first_space = cmd.find(' ');
|
||||
let first_word = match first_space {
|
||||
Some(pos) => &cmd[..pos],
|
||||
None => cmd,
|
||||
};
|
||||
if first_word.contains('/') {
|
||||
// Extract basename
|
||||
let basename = first_word.rsplit('/').next().unwrap_or(first_word);
|
||||
if basename.is_empty() {
|
||||
return cmd.to_string();
|
||||
}
|
||||
match first_space {
|
||||
Some(pos) => format!("{}{}", basename, &cmd[pos..]),
|
||||
None => basename.to_string(),
|
||||
}
|
||||
} else {
|
||||
cmd.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if a command has RTK_DISABLED= prefix in its env prefix portion.
|
||||
pub fn has_rtk_disabled_prefix(cmd: &str) -> bool {
|
||||
let trimmed = cmd.trim();
|
||||
let stripped = ENV_PREFIX.replace(trimmed, "");
|
||||
let prefix_len = trimmed.len() - stripped.len();
|
||||
let prefix_part = &trimmed[..prefix_len];
|
||||
prefix_part.contains("RTK_DISABLED=")
|
||||
}
|
||||
|
||||
/// Strip RTK_DISABLED=X and other env prefixes, return the actual command.
|
||||
pub fn strip_disabled_prefix(cmd: &str) -> &str {
|
||||
let trimmed = cmd.trim();
|
||||
let stripped = ENV_PREFIX.replace(trimmed, "");
|
||||
// stripped is a Cow<str> that borrows from trimmed when no replacement happens.
|
||||
// We need to return a &str into the original, so compute the offset.
|
||||
let prefix_len = trimmed.len() - stripped.len();
|
||||
trimmed[prefix_len..].trim_start()
|
||||
}
|
||||
|
||||
/// Rewrite a raw command to its RTK equivalent.
|
||||
///
|
||||
/// Returns `Some(rewritten)` if the command has an RTK equivalent or is already RTK.
|
||||
@@ -561,7 +476,7 @@ fn rewrite_segment(seg: &str, excluded: &[String]) -> Option<String> {
|
||||
let cmd_clean = stripped_cow.trim();
|
||||
|
||||
// #345: RTK_DISABLED=1 in env prefix → skip rewrite entirely
|
||||
if has_rtk_disabled_prefix(trimmed) {
|
||||
if env_prefix.contains("RTK_DISABLED=") {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -677,27 +592,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_cat_redirect_not_supported() {
|
||||
// cat > file and cat >> file are writes, not reads — should not be classified as supported
|
||||
let write_commands = [
|
||||
"cat > /tmp/output.txt",
|
||||
"cat >> /tmp/output.txt",
|
||||
"cat file.txt > output.txt",
|
||||
"cat -n file.txt >> log.txt",
|
||||
"head -10 README.md > output.txt",
|
||||
"tail -f app.log > /dev/null",
|
||||
];
|
||||
for cmd in &write_commands {
|
||||
match classify_command(cmd) {
|
||||
Classification::Supported { .. } => {
|
||||
panic!("{} should NOT be classified as Supported", cmd)
|
||||
}
|
||||
_ => {} // Unsupported or Ignored is fine
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_cd_ignored() {
|
||||
assert_eq!(classify_command("cd /tmp"), Classification::Ignored);
|
||||
@@ -717,10 +611,10 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_htop_unsupported() {
|
||||
match classify_command("htop -d 10") {
|
||||
fn test_classify_terraform_unsupported() {
|
||||
match classify_command("terraform plan -var-file=prod.tfvars") {
|
||||
Classification::Unsupported { base_command } => {
|
||||
assert_eq!(base_command, "htop");
|
||||
assert_eq!(base_command, "terraform plan");
|
||||
}
|
||||
other => panic!("expected Unsupported, got {:?}", other),
|
||||
}
|
||||
@@ -992,8 +886,8 @@ mod tests {
|
||||
#[test]
|
||||
fn test_rewrite_background_unsupported_right() {
|
||||
assert_eq!(
|
||||
rewrite_command("cargo test & htop", &[]),
|
||||
Some("rtk cargo test & htop".into())
|
||||
rewrite_command("cargo test & terraform plan", &[]),
|
||||
Some("rtk cargo test & terraform plan".into())
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1008,7 +902,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_unsupported_returns_none() {
|
||||
assert_eq!(rewrite_command("htop", &[]), None);
|
||||
assert_eq!(rewrite_command("terraform plan", &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1801,15 +1695,18 @@ mod tests {
|
||||
fn test_rewrite_compound_mixed_supported_unsupported() {
|
||||
// unsupported segments stay raw
|
||||
assert_eq!(
|
||||
rewrite_command("cargo test && htop", &[]),
|
||||
Some("rtk cargo test && htop".into())
|
||||
rewrite_command("cargo test && terraform plan", &[]),
|
||||
Some("rtk cargo test && terraform plan".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_compound_all_unsupported_returns_none() {
|
||||
// No rewrite at all: returns None
|
||||
assert_eq!(rewrite_command("htop && top", &[]), None);
|
||||
assert_eq!(
|
||||
rewrite_command("terraform plan && terraform apply", &[]),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
// --- sudo / env prefix + rewrite ---
|
||||
@@ -1960,159 +1857,4 @@ mod tests {
|
||||
Some("rtk gh pr list".into())
|
||||
);
|
||||
}
|
||||
|
||||
// --- #508: RTK_DISABLED detection helpers ---
|
||||
|
||||
#[test]
|
||||
fn test_has_rtk_disabled_prefix() {
|
||||
assert!(has_rtk_disabled_prefix("RTK_DISABLED=1 git status"));
|
||||
assert!(has_rtk_disabled_prefix("FOO=1 RTK_DISABLED=1 cargo test"));
|
||||
assert!(has_rtk_disabled_prefix(
|
||||
"RTK_DISABLED=true git log --oneline"
|
||||
));
|
||||
assert!(!has_rtk_disabled_prefix("git status"));
|
||||
assert!(!has_rtk_disabled_prefix("rtk git status"));
|
||||
assert!(!has_rtk_disabled_prefix("SOME_VAR=1 git status"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_disabled_prefix() {
|
||||
assert_eq!(
|
||||
strip_disabled_prefix("RTK_DISABLED=1 git status"),
|
||||
"git status"
|
||||
);
|
||||
assert_eq!(
|
||||
strip_disabled_prefix("FOO=1 RTK_DISABLED=1 cargo test"),
|
||||
"cargo test"
|
||||
);
|
||||
assert_eq!(strip_disabled_prefix("git status"), "git status");
|
||||
}
|
||||
|
||||
// --- #485: absolute path normalization ---
|
||||
|
||||
#[test]
|
||||
fn test_classify_absolute_path_grep() {
|
||||
assert_eq!(
|
||||
classify_command("/usr/bin/grep -rni pattern"),
|
||||
Classification::Supported {
|
||||
rtk_equivalent: "rtk grep",
|
||||
category: "Files",
|
||||
estimated_savings_pct: 75.0,
|
||||
status: RtkStatus::Existing,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_absolute_path_ls() {
|
||||
assert_eq!(
|
||||
classify_command("/bin/ls -la"),
|
||||
Classification::Supported {
|
||||
rtk_equivalent: "rtk ls",
|
||||
category: "Files",
|
||||
estimated_savings_pct: 65.0,
|
||||
status: RtkStatus::Existing,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_absolute_path_git() {
|
||||
assert_eq!(
|
||||
classify_command("/usr/local/bin/git status"),
|
||||
Classification::Supported {
|
||||
rtk_equivalent: "rtk git",
|
||||
category: "Git",
|
||||
estimated_savings_pct: 70.0,
|
||||
status: RtkStatus::Existing,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_absolute_path_no_args() {
|
||||
// /usr/bin/find alone → still classified
|
||||
assert_eq!(
|
||||
classify_command("/usr/bin/find ."),
|
||||
Classification::Supported {
|
||||
rtk_equivalent: "rtk find",
|
||||
category: "Files",
|
||||
estimated_savings_pct: 70.0,
|
||||
status: RtkStatus::Existing,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_absolute_path_helper() {
|
||||
assert_eq!(strip_absolute_path("/usr/bin/grep -rn foo"), "grep -rn foo");
|
||||
assert_eq!(strip_absolute_path("/bin/ls -la"), "ls -la");
|
||||
assert_eq!(strip_absolute_path("grep -rn foo"), "grep -rn foo");
|
||||
assert_eq!(strip_absolute_path("/usr/local/bin/git"), "git");
|
||||
}
|
||||
|
||||
// --- #163: git global options ---
|
||||
|
||||
#[test]
|
||||
fn test_classify_git_with_dash_c_path() {
|
||||
assert_eq!(
|
||||
classify_command("git -C /tmp status"),
|
||||
Classification::Supported {
|
||||
rtk_equivalent: "rtk git",
|
||||
category: "Git",
|
||||
estimated_savings_pct: 70.0,
|
||||
status: RtkStatus::Existing,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_git_no_pager_log() {
|
||||
assert_eq!(
|
||||
classify_command("git --no-pager log -5"),
|
||||
Classification::Supported {
|
||||
rtk_equivalent: "rtk git",
|
||||
category: "Git",
|
||||
estimated_savings_pct: 70.0,
|
||||
status: RtkStatus::Existing,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_git_git_dir() {
|
||||
assert_eq!(
|
||||
classify_command("git --git-dir /tmp/.git status"),
|
||||
Classification::Supported {
|
||||
rtk_equivalent: "rtk git",
|
||||
category: "Git",
|
||||
estimated_savings_pct: 70.0,
|
||||
status: RtkStatus::Existing,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_git_dash_c() {
|
||||
assert_eq!(
|
||||
rewrite_command("git -C /tmp status", &[]),
|
||||
Some("rtk git -C /tmp status".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_git_no_pager() {
|
||||
assert_eq!(
|
||||
rewrite_command("git --no-pager log -5", &[]),
|
||||
Some("rtk git --no-pager log -5".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_git_global_opts_helper() {
|
||||
assert_eq!(strip_git_global_opts("git -C /tmp status"), "git status");
|
||||
assert_eq!(strip_git_global_opts("git --no-pager log"), "git log");
|
||||
assert_eq!(strip_git_global_opts("git status"), "git status");
|
||||
assert_eq!(strip_git_global_opts("cargo test"), "cargo test");
|
||||
}
|
||||
}
|
||||
@@ -51,8 +51,6 @@ pub struct DiscoverReport {
|
||||
pub supported: Vec<SupportedEntry>,
|
||||
pub unsupported: Vec<UnsupportedEntry>,
|
||||
pub parse_errors: usize,
|
||||
pub rtk_disabled_count: usize,
|
||||
pub rtk_disabled_examples: Vec<String>,
|
||||
}
|
||||
|
||||
impl DiscoverReport {
|
||||
@@ -148,21 +146,6 @@ pub fn format_text(report: &DiscoverReport, limit: usize, verbose: bool) -> Stri
|
||||
out.push_str("-> github.com/rtk-ai/rtk/issues\n");
|
||||
}
|
||||
|
||||
// RTK_DISABLED bypass warning
|
||||
if report.rtk_disabled_count > 0 {
|
||||
out.push_str(&format!(
|
||||
"\nRTK_DISABLED BYPASS -- {} commands ran without filtering\n",
|
||||
report.rtk_disabled_count
|
||||
));
|
||||
out.push_str(&"-".repeat(72));
|
||||
out.push('\n');
|
||||
out.push_str("These commands used RTK_DISABLED=1 unnecessarily:\n");
|
||||
if !report.rtk_disabled_examples.is_empty() {
|
||||
out.push_str(&format!(" {}\n", report.rtk_disabled_examples.join(", ")));
|
||||
}
|
||||
out.push_str("-> Remove RTK_DISABLED=1 to recover token savings\n");
|
||||
}
|
||||
|
||||
out.push_str("\n~estimated from tool_result output sizes\n");
|
||||
|
||||
if verbose && report.parse_errors > 0 {
|
||||
|
||||
@@ -48,39 +48,6 @@ pub const PATTERNS: &[&str] = &[
|
||||
r"^aws\s+",
|
||||
// PostgreSQL
|
||||
r"^psql(\s|$)",
|
||||
// TOML-filtered commands
|
||||
r"^ansible-playbook\b",
|
||||
r"^brew\s+(install|upgrade)\b",
|
||||
r"^composer\s+(install|update|require)\b",
|
||||
r"^df(\s|$)",
|
||||
r"^dotnet\s+build\b",
|
||||
r"^du\b",
|
||||
r"^fail2ban-client\b",
|
||||
r"^gcloud\b",
|
||||
r"^hadolint\b",
|
||||
r"^helm\b",
|
||||
r"^iptables\b",
|
||||
r"^make\b",
|
||||
r"^markdownlint\b",
|
||||
r"^mix\s+(compile|format)(\s|$)",
|
||||
r"^mvn\s+(compile|package|clean|install)\b",
|
||||
r"^ping\b",
|
||||
r"^pio\s+run",
|
||||
r"^poetry\s+(install|lock|update)\b",
|
||||
r"^pre-commit\b",
|
||||
r"^ps(\s|$)",
|
||||
r"^quarto\s+render",
|
||||
r"^rsync\b",
|
||||
r"^shellcheck\b",
|
||||
r"^shopify\s+theme\s+(push|pull)",
|
||||
r"^sops\b",
|
||||
r"^swift\s+build\b",
|
||||
r"^systemctl\s+status\b",
|
||||
r"^terraform\s+plan",
|
||||
r"^tofu\s+(fmt|init|plan|validate)(\s|$)",
|
||||
r"^trunk\s+build",
|
||||
r"^uv\s+(sync|pip\s+install)\b",
|
||||
r"^yamllint\b",
|
||||
];
|
||||
|
||||
pub const RULES: &[RtkRule] = &[
|
||||
@@ -350,263 +317,6 @@ pub const RULES: &[RtkRule] = &[
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
// TOML-filtered commands
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk ansible-playbook",
|
||||
rewrite_prefixes: &["ansible-playbook"],
|
||||
category: "Infra",
|
||||
savings_pct: 70.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk brew",
|
||||
rewrite_prefixes: &["brew"],
|
||||
category: "PackageManager",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk composer",
|
||||
rewrite_prefixes: &["composer"],
|
||||
category: "PackageManager",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk df",
|
||||
rewrite_prefixes: &["df"],
|
||||
category: "System",
|
||||
savings_pct: 60.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk dotnet",
|
||||
rewrite_prefixes: &["dotnet"],
|
||||
category: "Build",
|
||||
savings_pct: 70.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk du",
|
||||
rewrite_prefixes: &["du"],
|
||||
category: "System",
|
||||
savings_pct: 60.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk fail2ban-client",
|
||||
rewrite_prefixes: &["fail2ban-client"],
|
||||
category: "Infra",
|
||||
savings_pct: 60.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk gcloud",
|
||||
rewrite_prefixes: &["gcloud"],
|
||||
category: "Infra",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk hadolint",
|
||||
rewrite_prefixes: &["hadolint"],
|
||||
category: "Build",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk helm",
|
||||
rewrite_prefixes: &["helm"],
|
||||
category: "Infra",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk iptables",
|
||||
rewrite_prefixes: &["iptables"],
|
||||
category: "Infra",
|
||||
savings_pct: 60.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk make",
|
||||
rewrite_prefixes: &["make"],
|
||||
category: "Build",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk markdownlint",
|
||||
rewrite_prefixes: &["markdownlint"],
|
||||
category: "Build",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk mix",
|
||||
rewrite_prefixes: &["mix"],
|
||||
category: "Build",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk mvn",
|
||||
rewrite_prefixes: &["mvn"],
|
||||
category: "Build",
|
||||
savings_pct: 70.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk ping",
|
||||
rewrite_prefixes: &["ping"],
|
||||
category: "Network",
|
||||
savings_pct: 60.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk pio",
|
||||
rewrite_prefixes: &["pio"],
|
||||
category: "Build",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk poetry",
|
||||
rewrite_prefixes: &["poetry"],
|
||||
category: "Python",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk pre-commit",
|
||||
rewrite_prefixes: &["pre-commit"],
|
||||
category: "Build",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk ps",
|
||||
rewrite_prefixes: &["ps"],
|
||||
category: "System",
|
||||
savings_pct: 60.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk quarto",
|
||||
rewrite_prefixes: &["quarto"],
|
||||
category: "Build",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk rsync",
|
||||
rewrite_prefixes: &["rsync"],
|
||||
category: "Network",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk shellcheck",
|
||||
rewrite_prefixes: &["shellcheck"],
|
||||
category: "Build",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk shopify",
|
||||
rewrite_prefixes: &["shopify"],
|
||||
category: "Build",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk sops",
|
||||
rewrite_prefixes: &["sops"],
|
||||
category: "Infra",
|
||||
savings_pct: 60.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk swift",
|
||||
rewrite_prefixes: &["swift"],
|
||||
category: "Build",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk systemctl",
|
||||
rewrite_prefixes: &["systemctl"],
|
||||
category: "System",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk terraform",
|
||||
rewrite_prefixes: &["terraform"],
|
||||
category: "Infra",
|
||||
savings_pct: 70.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk tofu",
|
||||
rewrite_prefixes: &["tofu"],
|
||||
category: "Infra",
|
||||
savings_pct: 70.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk trunk",
|
||||
rewrite_prefixes: &["trunk"],
|
||||
category: "Build",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk uv",
|
||||
rewrite_prefixes: &["uv"],
|
||||
category: "Python",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
rtk_cmd: "rtk yamllint",
|
||||
rewrite_prefixes: &["yamllint"],
|
||||
category: "Build",
|
||||
savings_pct: 65.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
];
|
||||
|
||||
/// Commands to ignore (shell builtins, trivial, already rtk).
|
||||
|
||||
@@ -50,7 +50,6 @@ pub enum Language {
|
||||
Java,
|
||||
Ruby,
|
||||
Shell,
|
||||
Data,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
@@ -67,9 +66,6 @@ impl Language {
|
||||
"java" => Language::Java,
|
||||
"rb" => Language::Ruby,
|
||||
"sh" | "bash" | "zsh" => Language::Shell,
|
||||
"json" | "jsonc" | "json5" | "yaml" | "yml" | "toml" | "xml" | "html" | "htm"
|
||||
| "css" | "scss" | "svg" | "md" | "markdown" | "txt" | "csv" | "tsv" | "env"
|
||||
| "ini" | "cfg" | "conf" | "lock" => Language::Data,
|
||||
_ => Language::Unknown,
|
||||
}
|
||||
}
|
||||
@@ -116,13 +112,6 @@ impl Language {
|
||||
doc_line: None,
|
||||
doc_block_start: None,
|
||||
},
|
||||
Language::Data => CommentPatterns {
|
||||
line: None,
|
||||
block_start: None,
|
||||
block_end: None,
|
||||
doc_line: None,
|
||||
doc_block_start: None,
|
||||
},
|
||||
Language::Unknown => CommentPatterns {
|
||||
line: Some("//"),
|
||||
block_start: Some("/*"),
|
||||
@@ -400,52 +389,6 @@ mod tests {
|
||||
assert_eq!(Language::from_extension("js"), Language::JavaScript);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_language_detection_data_formats() {
|
||||
assert_eq!(Language::from_extension("json"), Language::Data);
|
||||
assert_eq!(Language::from_extension("yaml"), Language::Data);
|
||||
assert_eq!(Language::from_extension("yml"), Language::Data);
|
||||
assert_eq!(Language::from_extension("toml"), Language::Data);
|
||||
assert_eq!(Language::from_extension("xml"), Language::Data);
|
||||
assert_eq!(Language::from_extension("md"), Language::Data);
|
||||
assert_eq!(Language::from_extension("csv"), Language::Data);
|
||||
assert_eq!(Language::from_extension("lock"), Language::Data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_data_files_no_comment_stripping() {
|
||||
// Regression test for #464: package.json with `/*` in strings
|
||||
let json = r#"{
|
||||
"workspaces": {
|
||||
"packages": [
|
||||
"packages/*"
|
||||
]
|
||||
},
|
||||
"scripts": {
|
||||
"build": "bun run --workspaces build"
|
||||
},
|
||||
"lint-staged": {
|
||||
"**/package.json": [
|
||||
"sort-package-json"
|
||||
]
|
||||
}
|
||||
}"#;
|
||||
let filter = MinimalFilter;
|
||||
let result = filter.filter(json, &Language::Data);
|
||||
assert!(
|
||||
result.contains("scripts"),
|
||||
"scripts section must be preserved"
|
||||
);
|
||||
assert!(
|
||||
result.contains("packages/*"),
|
||||
"glob pattern must be preserved"
|
||||
);
|
||||
assert!(
|
||||
result.contains("**/package.json"),
|
||||
"glob pattern must be preserved"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_minimal_filter_removes_comments() {
|
||||
let code = r#"
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
# Built-in Filters
|
||||
|
||||
Each `.toml` file in this directory defines one filter and its inline tests.
|
||||
Files are concatenated alphabetically by `build.rs` into a single TOML blob embedded in the binary.
|
||||
|
||||
## Adding a filter
|
||||
|
||||
1. Copy any existing `.toml` file and rename it (e.g. `my-tool.toml`)
|
||||
2. Update the three required fields: `description`, `match_command`, and at least one action field
|
||||
3. Add `[[tests.my-tool]]` entries to verify the filter behaves correctly
|
||||
4. Run `cargo test` — the build step validates TOML syntax and runs inline tests
|
||||
|
||||
## File format
|
||||
|
||||
```toml
|
||||
[filters.my-tool]
|
||||
description = "Short description of what this filter does"
|
||||
match_command = "^my-tool\\b" # regex matched against the full command string
|
||||
strip_ansi = true # optional: strip ANSI escape codes first
|
||||
strip_lines_matching = [ # optional: drop lines matching any of these regexes
|
||||
"^\\s*$",
|
||||
"^noise pattern",
|
||||
]
|
||||
max_lines = 40 # optional: keep only the first N lines after filtering
|
||||
on_empty = "my-tool: ok" # optional: message to emit when output is empty after filtering
|
||||
|
||||
[[tests.my-tool]]
|
||||
name = "descriptive test name"
|
||||
input = "raw command output here"
|
||||
expected = "expected filtered output"
|
||||
```
|
||||
|
||||
## Available filter fields
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `description` | string | Human-readable description |
|
||||
| `match_command` | regex | Matches the command string (e.g. `"^docker\\s+inspect"`) |
|
||||
| `strip_ansi` | bool | Strip ANSI escape codes before processing |
|
||||
| `strip_lines_matching` | regex[] | Drop lines matching any regex |
|
||||
| `keep_lines_matching` | regex[] | Keep only lines matching at least one regex |
|
||||
| `replace` | array | Regex substitutions (`{ pattern, replacement }`) |
|
||||
| `match_output` | array | Short-circuit rules (`{ pattern, message }`) |
|
||||
| `truncate_lines_at` | int | Truncate lines longer than N characters |
|
||||
| `max_lines` | int | Keep only the first N lines |
|
||||
| `tail_lines` | int | Keep only the last N lines (applied after other filters) |
|
||||
| `on_empty` | string | Fallback message when filtered output is empty |
|
||||
|
||||
## Naming convention
|
||||
|
||||
Use the command name as the filename: `terraform-plan.toml`, `docker-inspect.toml`, `mix-compile.toml`.
|
||||
For commands with subcommands, prefer `<cmd>-<subcommand>.toml` over grouping multiple filters in one file.
|
||||
@@ -1,34 +0,0 @@
|
||||
[filters.ansible-playbook]
|
||||
description = "Compact ansible-playbook output"
|
||||
match_command = "^ansible-playbook\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^ok: \\[",
|
||||
"^skipping: \\[",
|
||||
]
|
||||
max_lines = 60
|
||||
|
||||
[[tests.ansible-playbook]]
|
||||
name = "strips ok and skipping lines, keeps changed and failures"
|
||||
input = """
|
||||
PLAY [all] *********************************************************************
|
||||
|
||||
TASK [Gathering Facts] *********************************************************
|
||||
ok: [web01]
|
||||
ok: [web02]
|
||||
|
||||
TASK [Install nginx] ***********************************************************
|
||||
changed: [web01]
|
||||
skipping: [web02]
|
||||
|
||||
PLAY RECAP *********************************************************************
|
||||
web01 : ok=2 changed=1 unreachable=0 failed=0
|
||||
web02 : ok=1 changed=0 unreachable=0 failed=0
|
||||
"""
|
||||
expected = "PLAY [all] *********************************************************************\nTASK [Gathering Facts] *********************************************************\nTASK [Install nginx] ***********************************************************\nchanged: [web01]\nPLAY RECAP *********************************************************************\nweb01 : ok=2 changed=1 unreachable=0 failed=0\nweb02 : ok=1 changed=0 unreachable=0 failed=0"
|
||||
|
||||
[[tests.ansible-playbook]]
|
||||
name = "failed task preserved"
|
||||
input = "TASK [Start service] ***\nfailed: [web01] => {\"msg\": \"Service not found\"}\nPLAY RECAP ***\nweb01 : ok=1 failed=1"
|
||||
expected = "TASK [Start service] ***\nfailed: [web01] => {\"msg\": \"Service not found\"}\nPLAY RECAP ***\nweb01 : ok=1 failed=1"
|
||||
@@ -1,47 +0,0 @@
|
||||
[filters.basedpyright]
|
||||
description = "Compact basedpyright type checker output — strip blank lines, keep errors"
|
||||
match_command = "^basedpyright\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^Searching for source files",
|
||||
"^Found \\d+ source file",
|
||||
"^Pyright \\d+\\.\\d+",
|
||||
"^basedpyright \\d+\\.\\d+",
|
||||
]
|
||||
max_lines = 50
|
||||
on_empty = "basedpyright: ok"
|
||||
|
||||
[[tests.basedpyright]]
|
||||
name = "strips noise, keeps errors and summary"
|
||||
input = """
|
||||
basedpyright 1.22.0
|
||||
Searching for source files
|
||||
Found 42 source files
|
||||
|
||||
/home/user/app/main.py
|
||||
/home/user/app/main.py:10:5 - error: "foo" is not defined (reportUndefinedVariable)
|
||||
/home/user/app/main.py:25:1 - error: Type "str" is not assignable to type "int" (reportAssignmentType)
|
||||
|
||||
/home/user/app/utils.py
|
||||
/home/user/app/utils.py:8:9 - warning: Variable "x" is not accessed (reportUnusedVariable)
|
||||
|
||||
3 errors, 1 warning, 0 informations
|
||||
"""
|
||||
expected = "/home/user/app/main.py\n /home/user/app/main.py:10:5 - error: \"foo\" is not defined (reportUndefinedVariable)\n /home/user/app/main.py:25:1 - error: Type \"str\" is not assignable to type \"int\" (reportAssignmentType)\n/home/user/app/utils.py\n /home/user/app/utils.py:8:9 - warning: Variable \"x\" is not accessed (reportUnusedVariable)\n3 errors, 1 warning, 0 informations"
|
||||
|
||||
[[tests.basedpyright]]
|
||||
name = "clean output"
|
||||
input = """
|
||||
basedpyright 1.22.0
|
||||
Searching for source files
|
||||
Found 10 source files
|
||||
|
||||
0 errors, 0 warnings, 0 informations
|
||||
"""
|
||||
expected = "0 errors, 0 warnings, 0 informations"
|
||||
|
||||
[[tests.basedpyright]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -1,45 +0,0 @@
|
||||
[filters.biome]
|
||||
description = "Compact Biome lint/format output — strip blank lines, keep diagnostics"
|
||||
match_command = "^biome\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^Checked \\d+ file",
|
||||
"^Fixed \\d+ file",
|
||||
"^The following command",
|
||||
"^Run it with",
|
||||
]
|
||||
max_lines = 50
|
||||
on_empty = "biome: ok"
|
||||
|
||||
[[tests.biome]]
|
||||
name = "lint strips noise, keeps diagnostics"
|
||||
input = """
|
||||
Checked 42 files in 0.5s
|
||||
|
||||
src/app.tsx:5:3 lint/suspicious/noExplicitAny ━━━━━━━━━━━━━━━━━━━━
|
||||
× Unexpected any. Specify a different type.
|
||||
3 │ interface Props {
|
||||
4 │ data: any;
|
||||
5 │ ^^^
|
||||
|
||||
src/utils.ts:12:1 lint/complexity/noForEach ━━━━━━━━━━━━━━━━━━━━
|
||||
× Prefer for...of instead of forEach.
|
||||
12 │ items.forEach(item => process(item));
|
||||
│ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Found 2 errors.
|
||||
"""
|
||||
expected = "src/app.tsx:5:3 lint/suspicious/noExplicitAny ━━━━━━━━━━━━━━━━━━━━\n × Unexpected any. Specify a different type.\n 3 │ interface Props {\n 4 │ data: any;\n 5 │ ^^^\nsrc/utils.ts:12:1 lint/complexity/noForEach ━━━━━━━━━━━━━━━━━━━━\n × Prefer for...of instead of forEach.\n 12 │ items.forEach(item => process(item));\n │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nFound 2 errors."
|
||||
|
||||
[[tests.biome]]
|
||||
name = "clean check"
|
||||
input = """
|
||||
Checked 42 files in 0.3s
|
||||
"""
|
||||
expected = "biome: ok"
|
||||
|
||||
[[tests.biome]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -1,37 +0,0 @@
|
||||
[filters.brew-install]
|
||||
description = "Compact brew install/upgrade output — strip downloads, short-circuit when already installed"
|
||||
match_command = "^brew\\s+(install|upgrade)\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^==> Downloading",
|
||||
"^==> Pouring",
|
||||
"^Already downloaded:",
|
||||
"^###",
|
||||
"^==> Fetching",
|
||||
]
|
||||
match_output = [
|
||||
{ pattern = "already installed", message = "ok (already installed)" },
|
||||
]
|
||||
max_lines = 20
|
||||
|
||||
[[tests.brew-install]]
|
||||
name = "already installed short-circuits"
|
||||
input = """
|
||||
Warning: rtk 0.27.1 is already installed and up-to-date.
|
||||
To reinstall 0.27.1, run:
|
||||
brew reinstall rtk
|
||||
"""
|
||||
expected = "ok (already installed)"
|
||||
|
||||
[[tests.brew-install]]
|
||||
name = "install strips download lines"
|
||||
input = """
|
||||
==> Fetching jq
|
||||
==> Downloading https://homebrew.bintray.com/bottles/jq-1.7.1.arm64_sonoma.bottle.tar.gz
|
||||
######################################################################## 100.0%
|
||||
==> Pouring jq-1.7.1.arm64_sonoma.bottle.tar.gz
|
||||
==> Summary
|
||||
/opt/homebrew/Cellar/jq/1.7.1: 18 files, 1.2MB
|
||||
"""
|
||||
expected = "==> Summary\n/opt/homebrew/Cellar/jq/1.7.1: 18 files, 1.2MB"
|
||||
@@ -1,40 +0,0 @@
|
||||
[filters.composer-install]
|
||||
description = "Compact composer install/update/require output — strip downloads, short-circuit when up-to-date"
|
||||
match_command = "^composer\\s+(install|update|require)\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^ - Downloading ",
|
||||
"^ - Installing ",
|
||||
"^Loading composer",
|
||||
"^Updating dependencies",
|
||||
]
|
||||
match_output = [
|
||||
{ pattern = "Nothing to install, update or remove", message = "ok (up to date)" },
|
||||
]
|
||||
max_lines = 30
|
||||
|
||||
[[tests.composer-install]]
|
||||
name = "nothing to do short-circuits"
|
||||
input = """
|
||||
Loading composer repositories with package information
|
||||
Updating dependencies
|
||||
Lock file operations: 0 installs, 0 updates, 0 removals
|
||||
Nothing to install, update or remove
|
||||
Generating autoload files
|
||||
"""
|
||||
expected = "ok (up to date)"
|
||||
|
||||
[[tests.composer-install]]
|
||||
name = "install strips download lines"
|
||||
input = """
|
||||
Loading composer repositories with package information
|
||||
Updating dependencies
|
||||
- Downloading symfony/console (v6.4.0)
|
||||
- Installing symfony/console (v6.4.0): Extracting archive
|
||||
- Downloading psr/log (3.0.0)
|
||||
- Installing psr/log (3.0.0): Extracting archive
|
||||
Writing lock file
|
||||
Generating autoload files
|
||||
"""
|
||||
expected = "Writing lock file\nGenerating autoload files"
|
||||
@@ -1,16 +0,0 @@
|
||||
[filters.df]
|
||||
description = "Compact df output — truncate wide columns, limit rows"
|
||||
match_command = "^df(\\s|$)"
|
||||
strip_ansi = true
|
||||
truncate_lines_at = 80
|
||||
max_lines = 20
|
||||
|
||||
[[tests.df]]
|
||||
name = "short output passes through unchanged"
|
||||
input = "Filesystem 1K-blocks Used Available Use% Mounted on\n/dev/sda1 4096000 123456 3972544 4% /"
|
||||
expected = "Filesystem 1K-blocks Used Available Use% Mounted on\n/dev/sda1 4096000 123456 3972544 4% /"
|
||||
|
||||
[[tests.df]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -1,64 +0,0 @@
|
||||
[filters.dotnet-build]
|
||||
description = "Compact dotnet build output — short-circuit on success, strip banners"
|
||||
match_command = "^dotnet\\s+build\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^Microsoft \\(R\\)",
|
||||
"^Copyright \\(C\\)",
|
||||
"^ Determining projects",
|
||||
]
|
||||
match_output = [
|
||||
{ pattern = "0 Warning\\(s\\)\\n\\s+0 Error\\(s\\)", message = "ok (build succeeded)" },
|
||||
]
|
||||
max_lines = 40
|
||||
|
||||
[[tests.dotnet-build]]
|
||||
name = "successful build short-circuits to ok"
|
||||
input = """
|
||||
Microsoft (R) Build Engine version 17.8.3+195e7f5a3
|
||||
Copyright (C) Microsoft Corporation. All rights reserved.
|
||||
|
||||
Determining projects to restore...
|
||||
All projects are up-to-date for restore.
|
||||
MyApp -> /home/user/MyApp/bin/Debug/net8.0/MyApp.dll
|
||||
|
||||
Build succeeded.
|
||||
0 Warning(s)
|
||||
0 Error(s)
|
||||
|
||||
Time Elapsed 00:00:02.34
|
||||
"""
|
||||
expected = "ok (build succeeded)"
|
||||
|
||||
[[tests.dotnet-build]]
|
||||
name = "build with warnings not short-circuited"
|
||||
input = """
|
||||
Microsoft (R) Build Engine version 17.8.3+195e7f5a3
|
||||
Copyright (C) Microsoft Corporation. All rights reserved.
|
||||
|
||||
Determining projects to restore...
|
||||
MyApp -> /home/user/MyApp/bin/Debug/net8.0/MyApp.dll
|
||||
|
||||
Build succeeded.
|
||||
3 Warning(s)
|
||||
0 Error(s)
|
||||
|
||||
Time Elapsed 00:00:01.87
|
||||
"""
|
||||
expected = " MyApp -> /home/user/MyApp/bin/Debug/net8.0/MyApp.dll\nBuild succeeded.\n 3 Warning(s)\n 0 Error(s)\nTime Elapsed 00:00:01.87"
|
||||
|
||||
[[tests.dotnet-build]]
|
||||
name = "build errors pass through"
|
||||
input = """
|
||||
Microsoft (R) Build Engine version 17.8.3+195e7f5a3
|
||||
Copyright (C) Microsoft Corporation. All rights reserved.
|
||||
|
||||
Determining projects to restore...
|
||||
src/Program.cs(10,5): error CS1002: ; expected [/home/user/MyApp/MyApp.csproj]
|
||||
|
||||
Build FAILED.
|
||||
0 Warning(s)
|
||||
1 Error(s)
|
||||
"""
|
||||
expected = "src/Program.cs(10,5): error CS1002: ; expected [/home/user/MyApp/MyApp.csproj]\nBuild FAILED.\n 0 Warning(s)\n 1 Error(s)"
|
||||
@@ -1,16 +0,0 @@
|
||||
[filters.du]
|
||||
description = "Compact du output"
|
||||
match_command = "^du\\b"
|
||||
strip_lines_matching = ["^\\s*$"]
|
||||
truncate_lines_at = 120
|
||||
max_lines = 40
|
||||
|
||||
[[tests.du]]
|
||||
name = "preserves sizes, strips blank lines"
|
||||
input = "4.0K\t./src\n\n8.0K\t./tests\n16K\t."
|
||||
expected = "4.0K\t./src\n8.0K\t./tests\n16K\t."
|
||||
|
||||
[[tests.du]]
|
||||
name = "single line passthrough"
|
||||
input = "128K\t."
|
||||
expected = "128K\t."
|
||||
@@ -1,15 +0,0 @@
|
||||
[filters.fail2ban-client]
|
||||
description = "Compact fail2ban-client output"
|
||||
match_command = "^fail2ban-client\\b"
|
||||
strip_lines_matching = ["^\\s*$"]
|
||||
max_lines = 30
|
||||
|
||||
[[tests.fail2ban-client]]
|
||||
name = "strips blank lines"
|
||||
input = "Status for the jail: sshd\n|- Filter\n| |- Currently failed: 3\n\n|- Actions\n `- Total banned: 42"
|
||||
expected = "Status for the jail: sshd\n|- Filter\n| |- Currently failed: 3\n|- Actions\n `- Total banned: 42"
|
||||
|
||||
[[tests.fail2ban-client]]
|
||||
name = "single line passthrough"
|
||||
input = "Shutdown successful"
|
||||
expected = "Shutdown successful"
|
||||
@@ -1,49 +0,0 @@
|
||||
[filters.gcc]
|
||||
description = "Compact gcc/g++ compiler output — strip notes, keep errors and warnings"
|
||||
match_command = "^g(cc|\\+\\+)\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^\\s+\\|\\s*$",
|
||||
"^In file included from",
|
||||
"^\\s+from\\s",
|
||||
"^\\d+ warnings? generated",
|
||||
"^\\d+ errors? generated",
|
||||
]
|
||||
max_lines = 50
|
||||
on_empty = "gcc: ok"
|
||||
|
||||
[[tests.gcc]]
|
||||
name = "strips include chain, keeps errors and warnings"
|
||||
input = """
|
||||
In file included from /usr/include/stdio.h:42:
|
||||
from main.c:1:
|
||||
main.c:10:5: error: use of undeclared identifier 'foo'
|
||||
foo();
|
||||
^
|
||||
main.c:15:12: warning: unused variable 'x' [-Wunused-variable]
|
||||
int x = 42;
|
||||
^
|
||||
2 warnings generated.
|
||||
1 error generated.
|
||||
"""
|
||||
expected = "main.c:10:5: error: use of undeclared identifier 'foo'\n foo();\n ^\nmain.c:15:12: warning: unused variable 'x' [-Wunused-variable]\n int x = 42;\n ^"
|
||||
|
||||
[[tests.gcc]]
|
||||
name = "clean compilation"
|
||||
input = """
|
||||
"""
|
||||
expected = "gcc: ok"
|
||||
|
||||
[[tests.gcc]]
|
||||
name = "linker error kept"
|
||||
input = """
|
||||
/usr/bin/ld: /tmp/main.o: undefined reference to 'missing_func'
|
||||
collect2: error: ld returned 1 exit status
|
||||
"""
|
||||
expected = "/usr/bin/ld: /tmp/main.o: undefined reference to 'missing_func'\ncollect2: error: ld returned 1 exit status"
|
||||
|
||||
[[tests.gcc]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -1,22 +0,0 @@
|
||||
[filters.gcloud]
|
||||
description = "Compact gcloud output"
|
||||
match_command = "^gcloud\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = ["^\\s*$"]
|
||||
truncate_lines_at = 120
|
||||
max_lines = 30
|
||||
|
||||
[[tests.gcloud]]
|
||||
name = "strips blank lines, preserves output"
|
||||
input = """
|
||||
Updated property [core/project].
|
||||
|
||||
NAME REGION STATUS
|
||||
my-cluster us-central1 RUNNING
|
||||
"""
|
||||
expected = "Updated property [core/project].\nNAME REGION STATUS\nmy-cluster us-central1 RUNNING"
|
||||
|
||||
[[tests.gcloud]]
|
||||
name = "single line passthrough"
|
||||
input = "Listed 0 items."
|
||||
expected = "Listed 0 items."
|
||||
@@ -1,24 +0,0 @@
|
||||
[filters.hadolint]
|
||||
description = "Compact hadolint Dockerfile linting output"
|
||||
match_command = "^hadolint\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
]
|
||||
truncate_lines_at = 120
|
||||
max_lines = 40
|
||||
|
||||
[[tests.hadolint]]
|
||||
name = "Dockerfile warnings kept, blank lines stripped"
|
||||
input = """
|
||||
Dockerfile:3 DL3008 warning: Pin versions in apt-get install
|
||||
Dockerfile:5 DL3009 info: Delete apt-get lists after installing
|
||||
|
||||
Dockerfile:8 DL4006 warning: Set SHELL option -o pipefail before RUN with pipe
|
||||
"""
|
||||
expected = "Dockerfile:3 DL3008 warning: Pin versions in apt-get install\nDockerfile:5 DL3009 info: Delete apt-get lists after installing\nDockerfile:8 DL4006 warning: Set SHELL option -o pipefail before RUN with pipe"
|
||||
|
||||
[[tests.hadolint]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -1,29 +0,0 @@
|
||||
[filters.helm]
|
||||
description = "Compact helm output"
|
||||
match_command = "^helm\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^W\\d{4}",
|
||||
]
|
||||
truncate_lines_at = 120
|
||||
max_lines = 40
|
||||
|
||||
[[tests.helm]]
|
||||
name = "strips blank lines, preserves release info"
|
||||
input = """
|
||||
NAME: my-release
|
||||
LAST DEPLOYED: Mon Jan 15 10:30:00 2024
|
||||
NAMESPACE: default
|
||||
STATUS: deployed
|
||||
REVISION: 3
|
||||
|
||||
NOTES:
|
||||
Application is running.
|
||||
"""
|
||||
expected = "NAME: my-release\nLAST DEPLOYED: Mon Jan 15 10:30:00 2024\nNAMESPACE: default\nSTATUS: deployed\nREVISION: 3\nNOTES:\nApplication is running."
|
||||
|
||||
[[tests.helm]]
|
||||
name = "strips glog W-prefix warnings"
|
||||
input = "W0115 10:30:00 warning message from internal\nNAME: my-chart\nSTATUS: deployed"
|
||||
expected = "NAME: my-chart\nSTATUS: deployed"
|
||||
@@ -1,27 +0,0 @@
|
||||
[filters.iptables]
|
||||
description = "Compact iptables output"
|
||||
match_command = "^iptables\\b"
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^Chain DOCKER",
|
||||
"^Chain BR-",
|
||||
]
|
||||
max_lines = 50
|
||||
truncate_lines_at = 120
|
||||
|
||||
[[tests.iptables]]
|
||||
name = "strips Docker chains, preserves real rules"
|
||||
input = """
|
||||
Chain INPUT (policy ACCEPT)
|
||||
num target prot opt source destination
|
||||
1 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0
|
||||
Chain DOCKER (1 references)
|
||||
DOCKER all -- 0.0.0.0/0 0.0.0.0/0
|
||||
Chain BR-abcdef (0 references)
|
||||
"""
|
||||
expected = "Chain INPUT (policy ACCEPT)\nnum target prot opt source destination\n1 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0\n DOCKER all -- 0.0.0.0/0 0.0.0.0/0"
|
||||
|
||||
[[tests.iptables]]
|
||||
name = "preserves FORWARD and OUTPUT chains"
|
||||
input = "Chain FORWARD (policy DROP)\n1 ACCEPT tcp\nChain OUTPUT (policy ACCEPT)\n1 ACCEPT all"
|
||||
expected = "Chain FORWARD (policy DROP)\n1 ACCEPT tcp\nChain OUTPUT (policy ACCEPT)\n1 ACCEPT all"
|
||||
@@ -1,28 +0,0 @@
|
||||
[filters.jj]
|
||||
description = "Compact Jujutsu (jj) output — strip blank lines, truncate"
|
||||
match_command = "^jj\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^Hint:",
|
||||
"^Working copy now at:",
|
||||
]
|
||||
max_lines = 30
|
||||
truncate_lines_at = 120
|
||||
|
||||
[[tests.jj]]
|
||||
name = "log output stripped of hints"
|
||||
input = """
|
||||
@ qpvuntsm patrick@example.com 2026-03-10 12:00 abc123
|
||||
│ feat: add new feature
|
||||
◉ zzzzzzzz root()
|
||||
|
||||
Working copy now at: qpvuntsm abc123 feat: add new feature
|
||||
Hint: use `jj log` to see the full history
|
||||
"""
|
||||
expected = "@ qpvuntsm patrick@example.com 2026-03-10 12:00 abc123\n│ feat: add new feature\n◉ zzzzzzzz root()"
|
||||
|
||||
[[tests.jj]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -1,24 +0,0 @@
|
||||
[filters.jq]
|
||||
description = "Compact jq output — truncate large JSON results"
|
||||
match_command = "^jq\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
]
|
||||
max_lines = 40
|
||||
truncate_lines_at = 120
|
||||
|
||||
[[tests.jq]]
|
||||
name = "short output passes through"
|
||||
input = """
|
||||
{
|
||||
"name": "test",
|
||||
"version": "1.0"
|
||||
}
|
||||
"""
|
||||
expected = "{\n \"name\": \"test\",\n \"version\": \"1.0\"\n}"
|
||||
|
||||
[[tests.jq]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -1,41 +0,0 @@
|
||||
[filters.make]
|
||||
description = "Compact make output"
|
||||
match_command = "^make\\b"
|
||||
strip_lines_matching = [
|
||||
"^make\\[\\d+\\]:",
|
||||
"^\\s*$",
|
||||
"^Nothing to be done",
|
||||
]
|
||||
max_lines = 50
|
||||
on_empty = "make: ok"
|
||||
|
||||
[[tests.make]]
|
||||
name = "strips entering/leaving lines"
|
||||
input = """
|
||||
make[1]: Entering directory '/home/user'
|
||||
gcc -O2 foo.c
|
||||
make[1]: Leaving directory '/home/user'
|
||||
"""
|
||||
expected = """
|
||||
gcc -O2 foo.c
|
||||
"""
|
||||
|
||||
[[tests.make]]
|
||||
name = "strips blank lines"
|
||||
input = """
|
||||
gcc -O2 foo.c
|
||||
|
||||
gcc -O2 bar.c
|
||||
"""
|
||||
expected = """
|
||||
gcc -O2 foo.c
|
||||
gcc -O2 bar.c
|
||||
"""
|
||||
|
||||
[[tests.make]]
|
||||
name = "on_empty when all stripped"
|
||||
input = """
|
||||
make[1]: Entering directory '/home/user'
|
||||
make[1]: Leaving directory '/home/user'
|
||||
"""
|
||||
expected = "make: ok"
|
||||
@@ -1,24 +0,0 @@
|
||||
[filters.markdownlint]
|
||||
description = "Compact markdownlint output — strip blank lines, limit rows"
|
||||
match_command = "^markdownlint\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
]
|
||||
max_lines = 50
|
||||
truncate_lines_at = 120
|
||||
|
||||
[[tests.markdownlint]]
|
||||
name = "linting errors stripped of blank lines"
|
||||
input = """
|
||||
README.md:1:1 MD041/first-line-heading/first-line-h1 First line in file should be a top level heading
|
||||
README.md:10:1 MD022/blanks-around-headings Headings should be surrounded by blank lines
|
||||
|
||||
README.md:15:80 MD013/line-length Line length [Expected: 80; Actual: 95]
|
||||
"""
|
||||
expected = "README.md:1:1 MD041/first-line-heading/first-line-h1 First line in file should be a top level heading\nREADME.md:10:1 MD022/blanks-around-headings Headings should be surrounded by blank lines\nREADME.md:15:80 MD013/line-length Line length [Expected: 80; Actual: 95]"
|
||||
|
||||
[[tests.markdownlint]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -1,27 +0,0 @@
|
||||
[filters.mix-compile]
|
||||
description = "Compact mix compile output"
|
||||
match_command = "^mix\\s+compile(\\s|$)"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^Compiling \\d+ file",
|
||||
"^\\s*$",
|
||||
"^Generated\\s",
|
||||
]
|
||||
max_lines = 40
|
||||
on_empty = "mix compile: ok"
|
||||
|
||||
[[tests.mix-compile]]
|
||||
name = "strips compile noise, preserves warnings"
|
||||
input = """
|
||||
Compiling 12 files (.ex)
|
||||
Generated my_app app
|
||||
|
||||
warning: variable "conn" is unused
|
||||
lib/router.ex:42
|
||||
"""
|
||||
expected = "warning: variable \"conn\" is unused\n lib/router.ex:42"
|
||||
|
||||
[[tests.mix-compile]]
|
||||
name = "on_empty when only noise"
|
||||
input = "Compiling 3 files (.ex)\nGenerated my_app app\n"
|
||||
expected = "mix compile: ok"
|
||||
@@ -1,15 +0,0 @@
|
||||
[filters.mix-format]
|
||||
description = "Compact mix format output"
|
||||
match_command = "^mix\\s+format(\\s|$)"
|
||||
on_empty = "mix format: ok"
|
||||
max_lines = 20
|
||||
|
||||
[[tests.mix-format]]
|
||||
name = "empty output returns ok"
|
||||
input = ""
|
||||
expected = "mix format: ok"
|
||||
|
||||
[[tests.mix-format]]
|
||||
name = "changed files pass through"
|
||||
input = "lib/my_app.ex\ntest/my_app_test.exs"
|
||||
expected = "lib/my_app.ex\ntest/my_app_test.exs"
|
||||
@@ -1,44 +0,0 @@
|
||||
[filters.mvn-build]
|
||||
description = "Compact Maven build output"
|
||||
match_command = "^mvn\\s+(compile|package|clean|install)\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\[INFO\\] ---",
|
||||
"^\\[INFO\\] Building\\s",
|
||||
"^\\[INFO\\] Downloading\\s",
|
||||
"^\\[INFO\\] Downloaded\\s",
|
||||
"^\\[INFO\\]\\s*$",
|
||||
"^\\s*$",
|
||||
"^Downloading:",
|
||||
"^Downloaded:",
|
||||
"^Progress",
|
||||
]
|
||||
max_lines = 50
|
||||
on_empty = "mvn: ok"
|
||||
|
||||
[[tests.mvn-build]]
|
||||
name = "strips INFO noise, preserves errors and summary"
|
||||
input = """
|
||||
[INFO] ---
|
||||
[INFO] Building myapp 1.0-SNAPSHOT
|
||||
[INFO] Downloading org.apache.maven.plugins:maven-compiler-plugin:3.11.0
|
||||
[INFO] Downloaded org.apache.maven.plugins:maven-compiler-plugin:3.11.0
|
||||
[INFO]
|
||||
[ERROR] /src/main/java/Main.java:[10,5] cannot find symbol
|
||||
symbol: method foo()
|
||||
[INFO] BUILD FAILURE
|
||||
[INFO] Total time: 2.543 s
|
||||
"""
|
||||
expected = "[ERROR] /src/main/java/Main.java:[10,5] cannot find symbol\n symbol: method foo()\n[INFO] BUILD FAILURE\n[INFO] Total time: 2.543 s"
|
||||
|
||||
[[tests.mvn-build]]
|
||||
name = "successful build keeps BUILD SUCCESS line"
|
||||
input = """
|
||||
[INFO] ---
|
||||
[INFO] Building myapp 1.0-SNAPSHOT
|
||||
[INFO]
|
||||
[INFO] BUILD SUCCESS
|
||||
[INFO] Total time: 4.123 s
|
||||
[INFO] Finished at: 2024-01-15T10:30:00Z
|
||||
"""
|
||||
expected = "[INFO] BUILD SUCCESS\n[INFO] Total time: 4.123 s\n[INFO] Finished at: 2024-01-15T10:30:00Z"
|
||||
@@ -1,43 +0,0 @@
|
||||
[filters.oxlint]
|
||||
description = "Compact oxlint output — strip blank lines, keep diagnostics"
|
||||
match_command = "^oxlint\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^Finished in \\d+",
|
||||
"^Found \\d+ warning",
|
||||
]
|
||||
max_lines = 50
|
||||
on_empty = "oxlint: ok"
|
||||
|
||||
[[tests.oxlint]]
|
||||
name = "strips noise, keeps diagnostics"
|
||||
input = """
|
||||
× eslint(no-console): Unexpected console statement.
|
||||
╭─[src/app.ts:5:3]
|
||||
5 │ console.log("debug");
|
||||
│ ^^^^^^^^^^^
|
||||
╰────
|
||||
|
||||
× eslint(no-unused-vars): 'x' is defined but never used.
|
||||
╭─[src/utils.ts:2:7]
|
||||
2 │ let x = 42;
|
||||
│ ^
|
||||
╰────
|
||||
|
||||
Found 2 warnings on 2 files.
|
||||
Finished in 12ms on 100 files.
|
||||
"""
|
||||
expected = " × eslint(no-console): Unexpected console statement.\n ╭─[src/app.ts:5:3]\n 5 │ console.log(\"debug\");\n │ ^^^^^^^^^^^\n ╰────\n × eslint(no-unused-vars): 'x' is defined but never used.\n ╭─[src/utils.ts:2:7]\n 2 │ let x = 42;\n │ ^\n ╰────"
|
||||
|
||||
[[tests.oxlint]]
|
||||
name = "clean output"
|
||||
input = """
|
||||
Finished in 5ms on 100 files.
|
||||
"""
|
||||
expected = "oxlint: ok"
|
||||
|
||||
[[tests.oxlint]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -1,63 +0,0 @@
|
||||
[filters.ping]
|
||||
description = "Compact ping output — strip per-packet lines, keep summary"
|
||||
match_command = "^ping\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^PING ",
|
||||
"^Pinging ",
|
||||
"^\\d+ bytes from ",
|
||||
"^Reply from .+: bytes=",
|
||||
"^\\s*$",
|
||||
]
|
||||
tail_lines = 4
|
||||
|
||||
[[tests.ping]]
|
||||
name = "success keeps summary only"
|
||||
input = """
|
||||
PING example.com (93.184.216.34): 56 data bytes
|
||||
64 bytes from 93.184.216.34: icmp_seq=0 ttl=56 time=14.2 ms
|
||||
64 bytes from 93.184.216.34: icmp_seq=1 ttl=56 time=13.8 ms
|
||||
64 bytes from 93.184.216.34: icmp_seq=2 ttl=56 time=14.1 ms
|
||||
64 bytes from 93.184.216.34: icmp_seq=3 ttl=56 time=13.9 ms
|
||||
|
||||
--- example.com ping statistics ---
|
||||
4 packets transmitted, 4 packets received, 0.0% packet loss
|
||||
round-trip min/avg/max/stddev = 13.8/14.0/14.2/0.2 ms
|
||||
"""
|
||||
expected = """--- example.com ping statistics ---
|
||||
4 packets transmitted, 4 packets received, 0.0% packet loss
|
||||
round-trip min/avg/max/stddev = 13.8/14.0/14.2/0.2 ms"""
|
||||
|
||||
[[tests.ping]]
|
||||
name = "windows format keeps stats block only"
|
||||
input = """
|
||||
Pinging 192.0.2.1 with 32 bytes of data:
|
||||
Reply from 192.0.2.1: bytes=32 time=14ms TTL=56
|
||||
Reply from 192.0.2.1: bytes=32 time=13ms TTL=56
|
||||
Reply from 192.0.2.1: bytes=32 time=14ms TTL=56
|
||||
Reply from 192.0.2.1: bytes=32 time=13ms TTL=56
|
||||
|
||||
Ping statistics for 192.0.2.1:
|
||||
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
|
||||
Approximate round trip times in milli-seconds:
|
||||
Minimum = 13ms, Maximum = 14ms, Average = 13ms
|
||||
"""
|
||||
expected = """Ping statistics for 192.0.2.1:
|
||||
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
|
||||
Approximate round trip times in milli-seconds:
|
||||
Minimum = 13ms, Maximum = 14ms, Average = 13ms"""
|
||||
|
||||
[[tests.ping]]
|
||||
name = "unreachable host passes error through"
|
||||
input = """
|
||||
PING unreachable.example.com (192.0.2.1): 56 data bytes
|
||||
Request timeout for icmp_seq 0
|
||||
Request timeout for icmp_seq 1
|
||||
|
||||
--- unreachable.example.com ping statistics ---
|
||||
2 packets transmitted, 0 packets received, 100.0% packet loss
|
||||
"""
|
||||
expected = """Request timeout for icmp_seq 0
|
||||
Request timeout for icmp_seq 1
|
||||
--- unreachable.example.com ping statistics ---
|
||||
2 packets transmitted, 0 packets received, 100.0% packet loss"""
|
||||
@@ -1,40 +0,0 @@
|
||||
[filters.pio-run]
|
||||
description = "Compact PlatformIO build output"
|
||||
match_command = "^pio\\s+run"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^Verbose mode",
|
||||
"^CONFIGURATION:",
|
||||
"^LDF:",
|
||||
"^Library Manager:",
|
||||
"^Compiling\\s",
|
||||
"^Linking\\s",
|
||||
"^Building\\s",
|
||||
"^Checking size",
|
||||
]
|
||||
max_lines = 30
|
||||
on_empty = "pio run: ok"
|
||||
|
||||
[[tests.pio-run]]
|
||||
name = "strips build noise, preserves errors"
|
||||
input = """
|
||||
Verbose mode can be enabled via `-v, --verbose` option
|
||||
CONFIGURATION: https://docs.platformio.org/page/boards/espressif32/esp32dev.html
|
||||
LDF: Library Dependency Finder -> https://bit.ly/configure-pio-ldf
|
||||
Compiling .pio/build/esp32dev/src/main.cpp.o
|
||||
Building .pio/build/esp32dev/firmware.elf
|
||||
Linking .pio/build/esp32dev/firmware.elf
|
||||
Checking size .pio/build/esp32dev/firmware.elf
|
||||
src/main.cpp:10:3: error: 'LED_BUILTINN' was not declared
|
||||
"""
|
||||
expected = "src/main.cpp:10:3: error: 'LED_BUILTINN' was not declared"
|
||||
|
||||
[[tests.pio-run]]
|
||||
name = "on_empty when clean build with only noise"
|
||||
input = """
|
||||
Verbose mode can be enabled via `-v, --verbose` option
|
||||
Compiling .pio/build/esp32dev/src/main.cpp.o
|
||||
Linking .pio/build/esp32dev/firmware.elf
|
||||
"""
|
||||
expected = "pio run: ok"
|
||||
@@ -1,50 +0,0 @@
|
||||
[filters.poetry-install]
|
||||
description = "Compact poetry install/lock/update output — strip downloads, short-circuit when up-to-date"
|
||||
match_command = "^poetry\\s+(install|lock|update)\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^ [-•] Downloading ",
|
||||
"^ [-•] Installing .* \\(",
|
||||
"^Creating virtualenv",
|
||||
"^Using virtualenv",
|
||||
]
|
||||
match_output = [
|
||||
{ pattern = "No dependencies to install or update|No changes\\.", message = "ok (up to date)" },
|
||||
]
|
||||
max_lines = 30
|
||||
|
||||
[[tests.poetry-install]]
|
||||
name = "up to date short-circuits"
|
||||
input = """
|
||||
Installing dependencies from lock file
|
||||
|
||||
No dependencies to install or update
|
||||
"""
|
||||
expected = "ok (up to date)"
|
||||
|
||||
[[tests.poetry-install]]
|
||||
name = "poetry 2.x bullet syntax short-circuits to ok"
|
||||
input = """
|
||||
• Installing requests (2.31.0)
|
||||
• Installing certifi (2023.11.17)
|
||||
|
||||
No changes.
|
||||
"""
|
||||
expected = "ok (up to date)"
|
||||
|
||||
[[tests.poetry-install]]
|
||||
name = "install strips download lines"
|
||||
input = """
|
||||
Installing dependencies from lock file
|
||||
|
||||
- Downloading requests-2.31.0-py3-none-any.whl (62.6 kB)
|
||||
- Installing certifi (2023.11.17)
|
||||
- Installing charset-normalizer (3.3.2)
|
||||
- Installing idna (3.6)
|
||||
- Installing urllib3 (2.1.0)
|
||||
- Installing requests (2.31.0)
|
||||
|
||||
Writing lock file
|
||||
"""
|
||||
expected = "Installing dependencies from lock file\nWriting lock file"
|
||||
@@ -1,35 +0,0 @@
|
||||
[filters.pre-commit]
|
||||
description = "Compact pre-commit output"
|
||||
match_command = "^pre-commit\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\[INFO\\] Installing environment",
|
||||
"^\\[INFO\\] Once installed this environment will be reused",
|
||||
"^\\[INFO\\] This may take a few minutes",
|
||||
"^\\s*$",
|
||||
]
|
||||
max_lines = 40
|
||||
|
||||
[[tests.pre-commit]]
|
||||
name = "strips INFO install noise, keeps hook results"
|
||||
input = """
|
||||
[INFO] Installing environment for https://github.com/psf/black.
|
||||
[INFO] Once installed this environment will be reused.
|
||||
[INFO] This may take a few minutes...
|
||||
Trim Trailing Whitespace.................................................Passed
|
||||
Fix End of Files.........................................................Passed
|
||||
Check Yaml...............................................................Failed
|
||||
- hook id: check-yaml
|
||||
- exit code: 1
|
||||
"""
|
||||
expected = "Trim Trailing Whitespace.................................................Passed\nFix End of Files.........................................................Passed\nCheck Yaml...............................................................Failed\n- hook id: check-yaml\n- exit code: 1"
|
||||
|
||||
[[tests.pre-commit]]
|
||||
name = "all passed — no INFO noise"
|
||||
input = """
|
||||
[INFO] Installing environment for https://github.com/pre-commit/mirrors-isort.
|
||||
[INFO] Once installed this environment will be reused.
|
||||
isort....................................................................Passed
|
||||
black....................................................................Passed
|
||||
"""
|
||||
expected = "isort....................................................................Passed\nblack....................................................................Passed"
|
||||
@@ -1,16 +0,0 @@
|
||||
[filters.ps]
|
||||
description = "Compact ps output — truncate wide lines, limit rows"
|
||||
match_command = "^ps(\\s|$)"
|
||||
strip_ansi = true
|
||||
truncate_lines_at = 120
|
||||
max_lines = 30
|
||||
|
||||
[[tests.ps]]
|
||||
name = "short process list passes through unchanged"
|
||||
input = "USER PID %CPU %MEM COMMAND\nroot 1 0.0 0.0 /sbin/launchd\nflorian 42 0.1 0.2 bash"
|
||||
expected = "USER PID %CPU %MEM COMMAND\nroot 1 0.0 0.0 /sbin/launchd\nflorian 42 0.1 0.2 bash"
|
||||
|
||||
[[tests.ps]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -1,41 +0,0 @@
|
||||
[filters.quarto-render]
|
||||
description = "Compact quarto render output"
|
||||
match_command = "^quarto\\s+render"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^\\s*processing file:",
|
||||
"^\\s*\\d+/\\d+\\s",
|
||||
"^\\s*running",
|
||||
"^\\s*Rendering",
|
||||
"^pandoc ",
|
||||
"^ Validating",
|
||||
"^ Resolving",
|
||||
]
|
||||
match_output = [
|
||||
{ pattern = "Output created:", message = "ok (output created)" },
|
||||
]
|
||||
max_lines = 20
|
||||
|
||||
[[tests.quarto-render]]
|
||||
name = "success short-circuits to ok"
|
||||
input = """
|
||||
processing file: index.qmd
|
||||
Validating schema
|
||||
Resolving resources
|
||||
pandoc to html5
|
||||
Output created: _site/index.html
|
||||
"""
|
||||
expected = "ok (output created)"
|
||||
|
||||
[[tests.quarto-render]]
|
||||
name = "error passes through"
|
||||
input = """
|
||||
processing file: broken.qmd
|
||||
Validating schema
|
||||
ERROR: Render failed
|
||||
|
||||
caused by:
|
||||
syntax error at line 10
|
||||
"""
|
||||
expected = "ERROR: Render failed\ncaused by:\n syntax error at line 10"
|
||||
@@ -1,48 +0,0 @@
|
||||
[filters.rsync]
|
||||
description = "Compact rsync output — short-circuit on success, strip progress"
|
||||
match_command = "^rsync\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^sending incremental file list",
|
||||
"^sent \\d",
|
||||
]
|
||||
match_output = [
|
||||
{ pattern = "total size is", message = "ok (synced)", unless = "error|failed|No such file" },
|
||||
]
|
||||
max_lines = 20
|
||||
|
||||
[[tests.rsync]]
|
||||
name = "successful sync short-circuits to ok"
|
||||
input = """
|
||||
sending incremental file list
|
||||
./
|
||||
file1.txt
|
||||
file2.txt
|
||||
|
||||
sent 1,234 bytes received 42 bytes 2,552.00 bytes/sec
|
||||
total size is 98,765 speedup is 77.31
|
||||
"""
|
||||
expected = "ok (synced)"
|
||||
|
||||
[[tests.rsync]]
|
||||
name = "error lines pass through"
|
||||
input = """
|
||||
sending incremental file list
|
||||
rsync: [Receiver] mkdir "/remote/path" failed: Permission denied (13)
|
||||
rsync error: error in file system (code 11) at receiver.c(741) [Receiver=3.2.7]
|
||||
"""
|
||||
expected = """rsync: [Receiver] mkdir "/remote/path" failed: Permission denied (13)
|
||||
rsync error: error in file system (code 11) at receiver.c(741) [Receiver=3.2.7]"""
|
||||
|
||||
[[tests.rsync]]
|
||||
name = "errors not swallowed when total size present"
|
||||
input = """
|
||||
rsync: [sender] error
|
||||
error in rsync protocol data stream (code 12)
|
||||
sent 100 bytes received 200 bytes 60.00 bytes/sec
|
||||
total size is 1000 speedup is 3.33
|
||||
"""
|
||||
expected = """rsync: [sender] error
|
||||
error in rsync protocol data stream (code 12)
|
||||
total size is 1000 speedup is 3.33"""
|
||||
@@ -1,27 +0,0 @@
|
||||
[filters.shellcheck]
|
||||
description = "Compact shellcheck output — strip blank lines, keep caret indicators for error position"
|
||||
match_command = "^shellcheck\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
]
|
||||
max_lines = 50
|
||||
|
||||
[[tests.shellcheck]]
|
||||
name = "multi-warning output stripped of blank lines only"
|
||||
input = """
|
||||
In script.sh line 3:
|
||||
if [[ $1 == "" ]]
|
||||
^-- SC2236: Use -z instead of ! -n.
|
||||
|
||||
In script.sh line 7:
|
||||
echo $var
|
||||
^-- SC2086: Double quote to prevent globbing.
|
||||
|
||||
"""
|
||||
expected = "In script.sh line 3:\nif [[ $1 == \"\" ]]\n ^-- SC2236: Use -z instead of ! -n.\nIn script.sh line 7:\necho $var\n ^-- SC2086: Double quote to prevent globbing."
|
||||
|
||||
[[tests.shellcheck]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -1,29 +0,0 @@
|
||||
[filters.shopify-theme]
|
||||
description = "Compact shopify theme push/pull output"
|
||||
match_command = "^shopify\\s+theme\\s+(push|pull)"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^\\s*Uploading",
|
||||
"^\\s*Downloading",
|
||||
]
|
||||
tail_lines = 5
|
||||
max_lines = 15
|
||||
on_empty = "shopify theme: ok"
|
||||
|
||||
[[tests.shopify-theme]]
|
||||
name = "strips upload/download lines, keeps tail"
|
||||
input = """
|
||||
Uploading assets/app.css
|
||||
Uploading assets/app.js
|
||||
Uploading templates/index.liquid
|
||||
Downloading assets/old.css
|
||||
|
||||
Theme 'Development' (id: 12345) pushed to store.example.myshopify.com
|
||||
"""
|
||||
expected = "Theme 'Development' (id: 12345) pushed to store.example.myshopify.com"
|
||||
|
||||
[[tests.shopify-theme]]
|
||||
name = "on_empty when all stripped"
|
||||
input = "Uploading assets/app.css\nDownloading assets/base.css\n"
|
||||
expected = "shopify theme: ok"
|
||||
@@ -1,45 +0,0 @@
|
||||
[filters.skopeo]
|
||||
description = "Compact skopeo output — truncate large manifests, strip verbosity"
|
||||
match_command = "^skopeo\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^Getting image source signatures",
|
||||
"^Copying blob",
|
||||
"^Copying config",
|
||||
"^Writing manifest",
|
||||
"^Storing signatures",
|
||||
]
|
||||
max_lines = 30
|
||||
truncate_lines_at = 120
|
||||
on_empty = "skopeo: ok"
|
||||
|
||||
[[tests.skopeo]]
|
||||
name = "copy strips progress, keeps result"
|
||||
input = """
|
||||
Getting image source signatures
|
||||
Copying blob sha256:abc123 done
|
||||
Copying blob sha256:def456 done
|
||||
Copying config sha256:789ghi done
|
||||
Writing manifest to image destination
|
||||
Storing signatures
|
||||
"""
|
||||
expected = "skopeo: ok"
|
||||
|
||||
[[tests.skopeo]]
|
||||
name = "inspect keeps output"
|
||||
input = """
|
||||
{
|
||||
"Name": "docker.io/library/nginx",
|
||||
"Tag": "latest",
|
||||
"Digest": "sha256:abc123",
|
||||
"RepoTags": ["latest", "1.25"],
|
||||
"Created": "2026-01-01T00:00:00Z"
|
||||
}
|
||||
"""
|
||||
expected = "{\n \"Name\": \"docker.io/library/nginx\",\n \"Tag\": \"latest\",\n \"Digest\": \"sha256:abc123\",\n \"RepoTags\": [\"latest\", \"1.25\"],\n \"Created\": \"2026-01-01T00:00:00Z\"\n}"
|
||||
|
||||
[[tests.skopeo]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -1,16 +0,0 @@
|
||||
[filters.sops]
|
||||
description = "Compact sops output"
|
||||
match_command = "^sops\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = ["^\\s*$"]
|
||||
max_lines = 40
|
||||
|
||||
[[tests.sops]]
|
||||
name = "strips blank lines"
|
||||
input = "mac: xyz123\n\nversion: 3.8.1"
|
||||
expected = "mac: xyz123\nversion: 3.8.1"
|
||||
|
||||
[[tests.sops]]
|
||||
name = "preserves non-blank output unchanged"
|
||||
input = "mac: abc123\nversion: 3.8.1"
|
||||
expected = "mac: abc123\nversion: 3.8.1"
|
||||
@@ -1,44 +0,0 @@
|
||||
[filters.ssh]
|
||||
description = "Compact ssh output — strip connection banners, keep command output"
|
||||
match_command = "^ssh\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^Warning: Permanently added",
|
||||
"^Connection to .+ closed",
|
||||
"^Authenticated to",
|
||||
"^debug1:",
|
||||
"^OpenSSH_",
|
||||
"^Pseudo-terminal",
|
||||
]
|
||||
max_lines = 200
|
||||
truncate_lines_at = 120
|
||||
|
||||
[[tests.ssh]]
|
||||
name = "strips connection banners, keeps command output"
|
||||
input = """
|
||||
Warning: Permanently added '192.168.1.10' (ED25519) to the list of known hosts.
|
||||
|
||||
total 32
|
||||
drwxr-xr-x 4 user user 4096 Mar 10 12:00 app
|
||||
-rw-r--r-- 1 user user 1234 Mar 10 11:00 config.yaml
|
||||
|
||||
Connection to 192.168.1.10 closed.
|
||||
"""
|
||||
expected = "total 32\ndrwxr-xr-x 4 user user 4096 Mar 10 12:00 app\n-rw-r--r-- 1 user user 1234 Mar 10 11:00 config.yaml"
|
||||
|
||||
[[tests.ssh]]
|
||||
name = "verbose debug lines stripped"
|
||||
input = """
|
||||
debug1: Connecting to host.example.com port 22.
|
||||
debug1: Connection established.
|
||||
Authenticated to host.example.com ([1.2.3.4]:22).
|
||||
uptime: 12:00:00 up 42 days, load average: 0.10, 0.15, 0.12
|
||||
Connection to host.example.com closed.
|
||||
"""
|
||||
expected = "uptime: 12:00:00 up 42 days, load average: 0.10, 0.15, 0.12"
|
||||
|
||||
[[tests.ssh]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -1,34 +0,0 @@
|
||||
[filters.stat]
|
||||
description = "Compact stat output — strip blank lines"
|
||||
match_command = "^stat\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
]
|
||||
max_lines = 30
|
||||
|
||||
[[tests.stat]]
|
||||
name = "macOS stat output kept"
|
||||
input = """
|
||||
16777234 8690244974 -rw-r--r-- 1 patrick staff 0 12345 "Mar 10 12:00:00 2026" "Mar 10 11:00:00 2026" "Mar 10 11:00:00 2026" "Mar 9 10:00:00 2026" 4096 24 0 file.txt
|
||||
"""
|
||||
expected = "16777234 8690244974 -rw-r--r-- 1 patrick staff 0 12345 \"Mar 10 12:00:00 2026\" \"Mar 10 11:00:00 2026\" \"Mar 10 11:00:00 2026\" \"Mar 9 10:00:00 2026\" 4096 24 0 file.txt"
|
||||
|
||||
[[tests.stat]]
|
||||
name = "linux stat output kept"
|
||||
input = """
|
||||
File: main.rs
|
||||
Size: 12345 Blocks: 24 IO Block: 4096 regular file
|
||||
Device: 801h/2049d Inode: 1234567 Links: 1
|
||||
Access: (0644/-rw-r--r--) Uid: ( 1000/ patrick) Gid: ( 1000/ patrick)
|
||||
Access: 2026-03-10 12:00:00.000000000 +0100
|
||||
Modify: 2026-03-10 11:00:00.000000000 +0100
|
||||
Change: 2026-03-10 11:00:00.000000000 +0100
|
||||
Birth: 2026-03-09 10:00:00.000000000 +0100
|
||||
"""
|
||||
expected = " File: main.rs\n Size: 12345 Blocks: 24 IO Block: 4096 regular file\nDevice: 801h/2049d Inode: 1234567 Links: 1\nAccess: (0644/-rw-r--r--) Uid: ( 1000/ patrick) Gid: ( 1000/ patrick)\nAccess: 2026-03-10 12:00:00.000000000 +0100\nModify: 2026-03-10 11:00:00.000000000 +0100\nChange: 2026-03-10 11:00:00.000000000 +0100\n Birth: 2026-03-09 10:00:00.000000000 +0100"
|
||||
|
||||
[[tests.stat]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -1,41 +0,0 @@
|
||||
[filters.swift-build]
|
||||
description = "Compact swift build output — short-circuit on success, strip Compiling/Linking"
|
||||
match_command = "^swift\\s+build\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^Compiling ",
|
||||
"^Linking ",
|
||||
]
|
||||
match_output = [
|
||||
{ pattern = "Build complete!", message = "ok (build complete)", unless = "warning:|error:" },
|
||||
]
|
||||
max_lines = 40
|
||||
|
||||
[[tests.swift-build]]
|
||||
name = "successful build short-circuits to ok"
|
||||
input = """
|
||||
Build complete!
|
||||
"""
|
||||
expected = "ok (build complete)"
|
||||
|
||||
[[tests.swift-build]]
|
||||
name = "build errors pass through after stripping noise"
|
||||
input = """
|
||||
Compiling MyApp MyApp.swift
|
||||
/home/user/MyApp/Sources/MyApp/main.swift:5:1: error: use of unresolved identifier 'foo'
|
||||
foo()
|
||||
^~~
|
||||
Linking MyApp
|
||||
error: build had 1 command failure
|
||||
"""
|
||||
expected = "/home/user/MyApp/Sources/MyApp/main.swift:5:1: error: use of unresolved identifier 'foo'\nfoo()\n^~~\nerror: build had 1 command failure"
|
||||
|
||||
[[tests.swift-build]]
|
||||
name = "warnings not swallowed when Build complete present"
|
||||
input = """
|
||||
CompileSwift normal x86_64 MyFile.swift
|
||||
/path/to/MyFile.swift:42:10: warning: unused variable 'x'
|
||||
Build complete! (with warnings)
|
||||
"""
|
||||
expected = "CompileSwift normal x86_64 MyFile.swift\n/path/to/MyFile.swift:42:10: warning: unused variable 'x'\nBuild complete! (with warnings)"
|
||||
@@ -1,33 +0,0 @@
|
||||
[filters.systemctl-status]
|
||||
description = "Compact systemctl status output — strip blank lines, limit to 20 lines"
|
||||
match_command = "^systemctl\\s+status\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
]
|
||||
max_lines = 20
|
||||
|
||||
[[tests.systemctl-status]]
|
||||
name = "verbose unit status stripped of blank lines"
|
||||
input = """
|
||||
● nginx.service - A high performance web server
|
||||
Loaded: loaded (/lib/systemd/system/nginx.service; enabled)
|
||||
Active: active (running) since Mon 2024-01-15 10:30:00 UTC; 2h ago
|
||||
Docs: man:nginx(8)
|
||||
Main PID: 1234 (nginx)
|
||||
Tasks: 3 (limit: 4915)
|
||||
Memory: 8.5M
|
||||
|
||||
CGroup: /system.slice/nginx.service
|
||||
├─1234 nginx: master process /usr/sbin/nginx
|
||||
└─1235 nginx: worker process
|
||||
|
||||
Jan 15 10:30:00 host nginx[1234]: nginx/1.24.0
|
||||
Jan 15 10:30:00 host systemd[1]: Started nginx.service
|
||||
"""
|
||||
expected = "● nginx.service - A high performance web server\n Loaded: loaded (/lib/systemd/system/nginx.service; enabled)\n Active: active (running) since Mon 2024-01-15 10:30:00 UTC; 2h ago\n Docs: man:nginx(8)\n Main PID: 1234 (nginx)\n Tasks: 3 (limit: 4915)\n Memory: 8.5M\n CGroup: /system.slice/nginx.service\n ├─1234 nginx: master process /usr/sbin/nginx\n └─1235 nginx: worker process\nJan 15 10:30:00 host nginx[1234]: nginx/1.24.0\nJan 15 10:30:00 host systemd[1]: Started nginx.service"
|
||||
|
||||
[[tests.systemctl-status]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -1,35 +0,0 @@
|
||||
[filters.terraform-plan]
|
||||
description = "Compact Terraform plan output"
|
||||
match_command = "^terraform\\s+plan"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^Refreshing state",
|
||||
"^\\s*#.*unchanged",
|
||||
"^\\s*$",
|
||||
"^Acquiring state lock",
|
||||
"^Releasing state lock",
|
||||
]
|
||||
max_lines = 80
|
||||
on_empty = "terraform plan: no changes detected"
|
||||
|
||||
[[tests.terraform-plan]]
|
||||
name = "strips Refreshing state lines and blank lines"
|
||||
input = """
|
||||
Acquiring state lock. This may take a few moments...
|
||||
Refreshing state... [id=vpc-abc]
|
||||
Refreshing state... [id=sg-123]
|
||||
Releasing state lock. This may take a few moments...
|
||||
|
||||
Terraform will perform the following actions:
|
||||
|
||||
# aws_instance.web will be created
|
||||
+ resource "aws_instance" "web" {}
|
||||
|
||||
Plan: 1 to add, 0 to change, 0 to destroy.
|
||||
"""
|
||||
expected = "Terraform will perform the following actions:\n # aws_instance.web will be created\n + resource \"aws_instance\" \"web\" {}\nPlan: 1 to add, 0 to change, 0 to destroy."
|
||||
|
||||
[[tests.terraform-plan]]
|
||||
name = "strips noise, preserves non-blank content"
|
||||
input = "Refreshing state... [id=vpc-abc]\nNo changes. Your infrastructure matches the configuration."
|
||||
expected = "No changes. Your infrastructure matches the configuration."
|
||||
@@ -1,16 +0,0 @@
|
||||
[filters.tofu-fmt]
|
||||
description = "Compact OpenTofu fmt output"
|
||||
match_command = "^tofu\\s+fmt(\\s|$)"
|
||||
strip_ansi = true
|
||||
on_empty = "tofu fmt: ok (no changes)"
|
||||
max_lines = 30
|
||||
|
||||
[[tests.tofu-fmt]]
|
||||
name = "empty output returns on_empty message"
|
||||
input = ""
|
||||
expected = "tofu fmt: ok (no changes)"
|
||||
|
||||
[[tests.tofu-fmt]]
|
||||
name = "changed files pass through"
|
||||
input = "main.tf\nvariables.tf"
|
||||
expected = "main.tf\nvariables.tf"
|
||||
@@ -1,38 +0,0 @@
|
||||
[filters.tofu-init]
|
||||
description = "Compact OpenTofu init output"
|
||||
match_command = "^tofu\\s+init(\\s|$)"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^- Downloading",
|
||||
"^- Installing",
|
||||
"^- Using previously-installed",
|
||||
"^\\s*$",
|
||||
"^Initializing provider",
|
||||
"^Initializing the backend",
|
||||
"^Initializing modules",
|
||||
]
|
||||
max_lines = 20
|
||||
on_empty = "tofu init: ok"
|
||||
|
||||
[[tests.tofu-init]]
|
||||
name = "strips downloading/installing lines"
|
||||
input = """
|
||||
Initializing the backend...
|
||||
Initializing provider plugins...
|
||||
- Downloading hashicorp/aws 5.0.0...
|
||||
- Installing hashicorp/aws 5.0.0...
|
||||
- Using previously-installed hashicorp/random 3.5.1
|
||||
|
||||
OpenTofu has been successfully initialized!
|
||||
"""
|
||||
expected = "OpenTofu has been successfully initialized!"
|
||||
|
||||
[[tests.tofu-init]]
|
||||
name = "on_empty when all noise stripped"
|
||||
input = """
|
||||
Initializing the backend...
|
||||
Initializing provider plugins...
|
||||
- Using previously-installed hashicorp/aws 5.0.0
|
||||
|
||||
"""
|
||||
expected = "tofu init: ok"
|
||||
@@ -1,35 +0,0 @@
|
||||
[filters.tofu-plan]
|
||||
description = "Compact OpenTofu plan output"
|
||||
match_command = "^tofu\\s+plan(\\s|$)"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^Refreshing state",
|
||||
"^\\s*#.*unchanged",
|
||||
"^\\s*$",
|
||||
"^Acquiring state lock",
|
||||
"^Releasing state lock",
|
||||
]
|
||||
max_lines = 80
|
||||
on_empty = "tofu plan: no changes detected"
|
||||
|
||||
[[tests.tofu-plan]]
|
||||
name = "strips Refreshing state and lock lines"
|
||||
input = """
|
||||
Acquiring state lock. This may take a few moments...
|
||||
Refreshing state... [id=vpc-abc123]
|
||||
Refreshing state... [id=sg-def456]
|
||||
Releasing state lock. This may take a few moments...
|
||||
|
||||
OpenTofu will perform the following actions:
|
||||
|
||||
# aws_instance.web will be created
|
||||
+ resource "aws_instance" "web" {}
|
||||
|
||||
Plan: 1 to add, 0 to change, 0 to destroy.
|
||||
"""
|
||||
expected = "OpenTofu will perform the following actions:\n # aws_instance.web will be created\n + resource \"aws_instance\" \"web\" {}\nPlan: 1 to add, 0 to change, 0 to destroy."
|
||||
|
||||
[[tests.tofu-plan]]
|
||||
name = "on_empty when all noise stripped"
|
||||
input = "Refreshing state... [id=vpc-abc]\nAcquiring state lock. This may take a few moments...\nReleasing state lock. This may take a few moments..."
|
||||
expected = "tofu plan: no changes detected"
|
||||
@@ -1,17 +0,0 @@
|
||||
[filters.tofu-validate]
|
||||
description = "Compact OpenTofu validate output"
|
||||
match_command = "^tofu\\s+validate(\\s|$)"
|
||||
strip_ansi = true
|
||||
match_output = [
|
||||
{ pattern = "Success! The configuration is valid", message = "ok (valid)" },
|
||||
]
|
||||
|
||||
[[tests.tofu-validate]]
|
||||
name = "success short-circuits to ok"
|
||||
input = "Success! The configuration is valid."
|
||||
expected = "ok (valid)"
|
||||
|
||||
[[tests.tofu-validate]]
|
||||
name = "error passes through unchanged"
|
||||
input = "Error: Invalid resource type\n on main.tf line 3: resource \"aws_instancee\" \"web\""
|
||||
expected = "Error: Invalid resource type\n on main.tf line 3: resource \"aws_instancee\" \"web\""
|
||||
@@ -1,39 +0,0 @@
|
||||
[filters.trunk-build]
|
||||
description = "Compact trunk build output"
|
||||
match_command = "^trunk\\s+build"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^\\s*Compiling\\s",
|
||||
"^\\s*Downloading\\s",
|
||||
"^\\s*Fetching\\s",
|
||||
"^\\s*Fresh\\s",
|
||||
"^\\s*Checking\\s",
|
||||
]
|
||||
tail_lines = 10
|
||||
max_lines = 30
|
||||
on_empty = "trunk build: ok"
|
||||
|
||||
[[tests.trunk-build]]
|
||||
name = "strips compile noise, keeps tail summary"
|
||||
input = """
|
||||
Compiling tokio v1.35.0
|
||||
Compiling hyper v0.14.28
|
||||
Compiling my-crate v0.1.0
|
||||
Downloading serde v1.0.195
|
||||
Fresh regex v1.10.2
|
||||
|
||||
Finished release [optimized] target(s) in 45.23s
|
||||
Binary: target/release/my-crate (5.2MB)
|
||||
"""
|
||||
expected = " Finished release [optimized] target(s) in 45.23s\n Binary: target/release/my-crate (5.2MB)"
|
||||
|
||||
[[tests.trunk-build]]
|
||||
name = "on_empty when all noise stripped"
|
||||
input = """
|
||||
Compiling my-crate v0.1.0
|
||||
Fresh serde v1.0
|
||||
Checking tokio v1.35.0
|
||||
|
||||
"""
|
||||
expected = "trunk build: ok"
|
||||
@@ -1,50 +0,0 @@
|
||||
[filters.ty]
|
||||
description = "Compact ty type checker output — strip blank lines, keep errors"
|
||||
match_command = "^ty\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^Checking \\d+ file",
|
||||
"^ty \\d+\\.\\d+",
|
||||
]
|
||||
max_lines = 50
|
||||
on_empty = "ty: ok"
|
||||
|
||||
[[tests.ty]]
|
||||
name = "strips noise, keeps diagnostics"
|
||||
input = """
|
||||
ty 0.1.0
|
||||
Checking 15 files
|
||||
|
||||
error[unresolved-reference]: Name `foo` used when not defined
|
||||
--> app/main.py:10:5
|
||||
|
|
||||
10 | foo()
|
||||
| ^^^
|
||||
|
|
||||
|
||||
warning[unused-variable]: Variable `x` is not used
|
||||
--> app/utils.py:8:9
|
||||
|
|
||||
8 | x = 42
|
||||
| ^
|
||||
|
|
||||
|
||||
Found 1 error, 1 warning
|
||||
"""
|
||||
expected = "error[unresolved-reference]: Name `foo` used when not defined\n --> app/main.py:10:5\n |\n10 | foo()\n | ^^^\n |\nwarning[unused-variable]: Variable `x` is not used\n --> app/utils.py:8:9\n |\n 8 | x = 42\n | ^\n |\nFound 1 error, 1 warning"
|
||||
|
||||
[[tests.ty]]
|
||||
name = "clean output"
|
||||
input = """
|
||||
ty 0.1.0
|
||||
Checking 10 files
|
||||
|
||||
All checks passed!
|
||||
"""
|
||||
expected = "All checks passed!"
|
||||
|
||||
[[tests.ty]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -1,37 +0,0 @@
|
||||
[filters.uv-sync]
|
||||
description = "Compact uv sync/pip install output — strip downloads, short-circuit when up-to-date"
|
||||
match_command = "^uv\\s+(sync|pip\\s+install)\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^\\s+Downloading ",
|
||||
"^\\s+Using cached ",
|
||||
"^\\s+Preparing ",
|
||||
]
|
||||
match_output = [
|
||||
{ pattern = "Audited \\d+ package", message = "ok (up to date)" },
|
||||
]
|
||||
max_lines = 20
|
||||
|
||||
[[tests.uv-sync]]
|
||||
name = "audited packages short-circuits to ok"
|
||||
input = """
|
||||
Resolved 42 packages in 123ms
|
||||
Audited 42 packages in 0.05ms
|
||||
"""
|
||||
expected = "ok (up to date)"
|
||||
|
||||
[[tests.uv-sync]]
|
||||
name = "install strips download and cached lines"
|
||||
input = """
|
||||
Downloading requests-2.31.0-py3-none-any.whl (62.6 kB)
|
||||
Using cached certifi-2023.11.17-py3-none-any.whl (162 kB)
|
||||
Preparing packages...
|
||||
Installed 5 packages in 23ms
|
||||
+ certifi==2023.11.17
|
||||
+ charset-normalizer==3.3.2
|
||||
+ idna==3.6
|
||||
+ requests==2.31.0
|
||||
+ urllib3==2.1.0
|
||||
"""
|
||||
expected = "Installed 5 packages in 23ms\n + certifi==2023.11.17\n + charset-normalizer==3.3.2\n + idna==3.6\n + requests==2.31.0\n + urllib3==2.1.0"
|
||||
@@ -1,99 +0,0 @@
|
||||
[filters.xcodebuild]
|
||||
description = "Compact xcodebuild output — strip build phases, keep errors/warnings/summary"
|
||||
match_command = "^xcodebuild\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
"^CompileC\\s",
|
||||
"^CompileSwift\\s",
|
||||
"^Ld\\s",
|
||||
"^CreateBuildDirectory\\s",
|
||||
"^MkDir\\s",
|
||||
"^ProcessInfoPlistFile\\s",
|
||||
"^CopySwiftLibs\\s",
|
||||
"^CodeSign\\s",
|
||||
"^Signing Identity:",
|
||||
"^RegisterWithLaunchServices",
|
||||
"^Validate\\s",
|
||||
"^ProcessProductPackaging",
|
||||
"^Touch\\s",
|
||||
"^LinkStoryboards",
|
||||
"^CompileStoryboard",
|
||||
"^CompileAssetCatalog",
|
||||
"^GenerateDSYMFile",
|
||||
"^PhaseScriptExecution",
|
||||
"^PBXCp\\s",
|
||||
"^SetMode\\s",
|
||||
"^SetOwnerAndGroup\\s",
|
||||
"^Ditto\\s",
|
||||
"^CpResource\\s",
|
||||
"^CpHeader\\s",
|
||||
"^\\s+cd\\s+/",
|
||||
"^\\s+export\\s",
|
||||
"^\\s+/Applications/Xcode",
|
||||
"^\\s+/usr/bin/",
|
||||
"^\\s+builtin-",
|
||||
"^note: Using new build system",
|
||||
]
|
||||
max_lines = 60
|
||||
on_empty = "xcodebuild: ok"
|
||||
|
||||
[[tests.xcodebuild]]
|
||||
name = "strips build phases, keeps errors and summary"
|
||||
input = """
|
||||
note: Using new build system
|
||||
CompileSwift normal arm64 /Users/dev/App/ViewController.swift
|
||||
cd /Users/dev/App
|
||||
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift-frontend -c
|
||||
CompileSwift normal arm64 /Users/dev/App/AppDelegate.swift
|
||||
cd /Users/dev/App
|
||||
export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
|
||||
Ld /Users/dev/Build/Products/Debug/App normal arm64
|
||||
cd /Users/dev/App
|
||||
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang
|
||||
CodeSign /Users/dev/Build/Products/Debug/App.app
|
||||
cd /Users/dev/App
|
||||
builtin-codesign --force --sign
|
||||
|
||||
/Users/dev/App/ViewController.swift:42:9: error: use of unresolved identifier 'foo'
|
||||
/Users/dev/App/Model.swift:18:5: warning: variable 'x' was never used
|
||||
|
||||
** BUILD FAILED **
|
||||
"""
|
||||
expected = "/Users/dev/App/ViewController.swift:42:9: error: use of unresolved identifier 'foo'\n/Users/dev/App/Model.swift:18:5: warning: variable 'x' was never used\n** BUILD FAILED **"
|
||||
|
||||
[[tests.xcodebuild]]
|
||||
name = "clean build success"
|
||||
input = """
|
||||
note: Using new build system
|
||||
CompileSwift normal arm64 /Users/dev/App/Main.swift
|
||||
cd /Users/dev/App
|
||||
Ld /Users/dev/Build/Products/Debug/App normal arm64
|
||||
cd /Users/dev/App
|
||||
CodeSign /Users/dev/Build/Products/Debug/App.app
|
||||
cd /Users/dev/App
|
||||
builtin-codesign --force --sign
|
||||
|
||||
** BUILD SUCCEEDED **
|
||||
"""
|
||||
expected = "** BUILD SUCCEEDED **"
|
||||
|
||||
[[tests.xcodebuild]]
|
||||
name = "test output keeps test results"
|
||||
input = """
|
||||
note: Using new build system
|
||||
CompileSwift normal arm64 /Users/dev/AppTests/Tests.swift
|
||||
cd /Users/dev/App
|
||||
Test Suite 'All tests' started at 2026-03-10 12:00:00
|
||||
Test Suite 'AppTests' started at 2026-03-10 12:00:00
|
||||
Test Case '-[AppTests testExample]' passed (0.001 seconds).
|
||||
Test Case '-[AppTests testFailing]' failed (0.002 seconds).
|
||||
Test Suite 'AppTests' passed at 2026-03-10 12:00:01
|
||||
Executed 2 tests, with 1 failure in 0.003 seconds
|
||||
"""
|
||||
expected = "Test Suite 'All tests' started at 2026-03-10 12:00:00\nTest Suite 'AppTests' started at 2026-03-10 12:00:00\nTest Case '-[AppTests testExample]' passed (0.001 seconds).\nTest Case '-[AppTests testFailing]' failed (0.002 seconds).\nTest Suite 'AppTests' passed at 2026-03-10 12:00:01\nExecuted 2 tests, with 1 failure in 0.003 seconds"
|
||||
|
||||
[[tests.xcodebuild]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
@@ -1,25 +0,0 @@
|
||||
[filters.yamllint]
|
||||
description = "Compact yamllint output — strip blank lines, limit rows"
|
||||
match_command = "^yamllint\\b"
|
||||
strip_ansi = true
|
||||
strip_lines_matching = [
|
||||
"^\\s*$",
|
||||
]
|
||||
max_lines = 50
|
||||
truncate_lines_at = 120
|
||||
|
||||
[[tests.yamllint]]
|
||||
name = "multi-warning output stripped of blank lines"
|
||||
input = """
|
||||
config.yml
|
||||
3:1 warning missing document start "---" (document-start)
|
||||
5:12 error too many spaces inside braces (braces)
|
||||
|
||||
8:1 error wrong indentation: expected 2 but found 4 (indentation)
|
||||
"""
|
||||
expected = "config.yml\n 3:1 warning missing document start \"---\" (document-start)\n 5:12 error too many spaces inside braces (braces)\n 8:1 error wrong indentation: expected 2 but found 4 (indentation)"
|
||||
|
||||
[[tests.yamllint]]
|
||||
name = "empty input passes through"
|
||||
input = ""
|
||||
expected = ""
|
||||
+4
-80
@@ -1,12 +1,11 @@
|
||||
use crate::display_helpers::{format_duration, print_period_table};
|
||||
use crate::hook_check;
|
||||
use crate::tracking::{DayStats, MonthStats, Tracker, WeekStats};
|
||||
use crate::utils::format_tokens;
|
||||
use anyhow::{Context, Result};
|
||||
use colored::Colorize;
|
||||
use colored::Colorize; // added: terminal colors
|
||||
use serde::Serialize;
|
||||
use std::io::IsTerminal;
|
||||
use std::path::PathBuf;
|
||||
use std::io::IsTerminal; // added: TTY detection for graceful degradation
|
||||
use std::path::PathBuf; // added: for project path resolution
|
||||
|
||||
pub fn run(
|
||||
project: bool, // added: per-project scope flag
|
||||
@@ -100,35 +99,9 @@ pub fn run(
|
||||
format_duration(summary.avg_time_ms)
|
||||
),
|
||||
);
|
||||
print_efficiency_meter(summary.avg_savings_pct);
|
||||
print_efficiency_meter(summary.avg_savings_pct); // added: visual meter
|
||||
println!();
|
||||
|
||||
// Warn about hook issues that silently kill savings (stderr, not stdout)
|
||||
match hook_check::status() {
|
||||
hook_check::HookStatus::Missing => {
|
||||
eprintln!(
|
||||
"{}",
|
||||
"⚠️ No hook installed — run `rtk init -g` for automatic token savings"
|
||||
.yellow()
|
||||
);
|
||||
eprintln!();
|
||||
}
|
||||
hook_check::HookStatus::Outdated => {
|
||||
eprintln!(
|
||||
"{}",
|
||||
"⚠️ Hook outdated — run `rtk init -g` to update".yellow()
|
||||
);
|
||||
eprintln!();
|
||||
}
|
||||
hook_check::HookStatus::Ok => {}
|
||||
}
|
||||
|
||||
// Lightweight RTK_DISABLED bypass check (best-effort, silent on failure)
|
||||
if let Some(warning) = check_rtk_disabled_bypass() {
|
||||
eprintln!("{}", warning.yellow());
|
||||
eprintln!();
|
||||
}
|
||||
|
||||
if !summary.by_command.is_empty() {
|
||||
// added: styled section header
|
||||
println!("{}", styled("By Command", true));
|
||||
@@ -617,55 +590,6 @@ fn export_csv(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Lightweight scan of recent Claude Code sessions for RTK_DISABLED= overuse.
|
||||
/// Returns a warning string if bypass rate exceeds 10%, None otherwise.
|
||||
/// Silently returns None on any error (missing dirs, permission issues, etc.).
|
||||
fn check_rtk_disabled_bypass() -> Option<String> {
|
||||
use crate::discover::provider::{ClaudeProvider, SessionProvider};
|
||||
use crate::discover::registry::has_rtk_disabled_prefix;
|
||||
|
||||
let provider = ClaudeProvider;
|
||||
|
||||
// Quick scan: last 7 days only
|
||||
let sessions = provider.discover_sessions(None, Some(7)).ok()?;
|
||||
|
||||
// Early bail if no sessions or too many (avoid slow scan)
|
||||
if sessions.is_empty() || sessions.len() > 200 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut total_bash: usize = 0;
|
||||
let mut bypassed: usize = 0;
|
||||
|
||||
for session_path in &sessions {
|
||||
let extracted = match provider.extract_commands(session_path) {
|
||||
Ok(cmds) => cmds,
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
for ext_cmd in &extracted {
|
||||
total_bash += 1;
|
||||
if has_rtk_disabled_prefix(&ext_cmd.command) {
|
||||
bypassed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if total_bash == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let pct = (bypassed as f64 / total_bash as f64) * 100.0;
|
||||
if pct > 10.0 {
|
||||
Some(format!(
|
||||
"⚠️ {} commands ({:.0}%) used RTK_DISABLED=1 unnecessarily — run `rtk discover` for details",
|
||||
bypassed, pct
|
||||
))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn show_failures(tracker: &Tracker) -> Result<()> {
|
||||
let summary = tracker
|
||||
.get_parse_failure_summary()
|
||||
|
||||
+45
-111
@@ -4,6 +4,7 @@
|
||||
//! Focuses on extracting essential information from JSON outputs.
|
||||
|
||||
use crate::git;
|
||||
use crate::json_cmd;
|
||||
use crate::tracking;
|
||||
use crate::utils::{ok_confirmation, truncate};
|
||||
use anyhow::{Context, Result};
|
||||
@@ -121,16 +122,7 @@ fn extract_identifier_and_extra_args(args: &[String]) -> Option<(String, Vec<Str
|
||||
}
|
||||
|
||||
// Known gh flags that take a value — skip these and their values
|
||||
let flags_with_value = [
|
||||
"-R",
|
||||
"--repo",
|
||||
"-q",
|
||||
"--jq",
|
||||
"-t",
|
||||
"--template",
|
||||
"--job",
|
||||
"--attempt",
|
||||
];
|
||||
let flags_with_value = ["-R", "--repo", "-q", "--jq", "-t", "--template"];
|
||||
let mut identifier = None;
|
||||
let mut extra = Vec::new();
|
||||
let mut skip_next = false;
|
||||
@@ -284,12 +276,6 @@ fn list_prs(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn should_passthrough_pr_view(extra_args: &[String]) -> bool {
|
||||
extra_args
|
||||
.iter()
|
||||
.any(|a| a == "--json" || a == "--jq" || a == "--web")
|
||||
}
|
||||
|
||||
fn view_pr(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
@@ -298,12 +284,6 @@ fn view_pr(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
|
||||
None => return Err(anyhow::anyhow!("PR number required")),
|
||||
};
|
||||
|
||||
// If the user provides --jq or --web, pass through directly.
|
||||
// Note: --json is already handled globally by run() via has_json_flag.
|
||||
if should_passthrough_pr_view(&extra_args) {
|
||||
return run_passthrough_with_extra("gh", &["pr", "view", &pr_number], &extra_args);
|
||||
}
|
||||
|
||||
let mut cmd = Command::new("gh");
|
||||
cmd.args([
|
||||
"pr",
|
||||
@@ -1112,23 +1092,11 @@ fn pr_merge(args: &[String], _verbose: u8) -> Result<()> {
|
||||
}
|
||||
|
||||
fn pr_diff(args: &[String], _verbose: u8) -> Result<()> {
|
||||
// --no-compact: pass full diff through (gh CLI doesn't know this flag, strip it)
|
||||
let no_compact = args.iter().any(|a| a == "--no-compact");
|
||||
let gh_args: Vec<String> = args
|
||||
.iter()
|
||||
.filter(|a| *a != "--no-compact")
|
||||
.cloned()
|
||||
.collect();
|
||||
|
||||
if no_compact {
|
||||
return run_passthrough_with_extra("gh", &["pr", "diff"], &gh_args);
|
||||
}
|
||||
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
let mut cmd = Command::new("gh");
|
||||
cmd.args(["pr", "diff"]);
|
||||
for arg in gh_args.iter() {
|
||||
for arg in args {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
|
||||
@@ -1147,7 +1115,7 @@ fn pr_diff(args: &[String], _verbose: u8) -> Result<()> {
|
||||
print!("{}", msg);
|
||||
msg.to_string()
|
||||
} else {
|
||||
let compacted = git::compact_diff(&raw, 500);
|
||||
let compacted = git::compact_diff(&raw, 100);
|
||||
println!("{}", compacted);
|
||||
compacted
|
||||
};
|
||||
@@ -1211,10 +1179,47 @@ fn pr_action(action: &str, args: &[String], _verbose: u8) -> Result<()> {
|
||||
}
|
||||
|
||||
fn run_api(args: &[String], _verbose: u8) -> Result<()> {
|
||||
// gh api is an explicit/advanced command — the user knows what they asked for.
|
||||
// Converting JSON to a schema destroys all values and forces Claude to re-fetch.
|
||||
// Passthrough preserves the full response and tracks metrics at 0% savings.
|
||||
run_passthrough("gh", "api", args)
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
let mut cmd = Command::new("gh");
|
||||
cmd.arg("api");
|
||||
for arg in args {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
|
||||
let output = cmd.output().context("Failed to run gh api")?;
|
||||
let raw = String::from_utf8_lossy(&output.stdout).to_string();
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
|
||||
timer.track("gh api", "rtk gh api", &stderr, &stderr);
|
||||
eprintln!("{}", stderr.trim());
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
// Try to parse as JSON and filter
|
||||
let filtered = match json_cmd::filter_json_string(&raw, 5) {
|
||||
Ok(schema) => {
|
||||
println!("{}", schema);
|
||||
schema
|
||||
}
|
||||
Err(_) => {
|
||||
// Not JSON, print truncated raw output
|
||||
let mut result = String::new();
|
||||
let lines: Vec<&str> = raw.lines().take(20).collect();
|
||||
let joined = lines.join("\n");
|
||||
result.push_str(&joined);
|
||||
print!("{}", joined);
|
||||
if raw.lines().count() > 20 {
|
||||
result.push_str("\n... (truncated)");
|
||||
println!("\n... (truncated)");
|
||||
}
|
||||
result
|
||||
}
|
||||
};
|
||||
|
||||
timer.track("gh api", "rtk gh api", &raw, &filtered);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Pass through a command with base args + extra args, tracking as passthrough.
|
||||
@@ -1427,77 +1432,6 @@ mod tests {
|
||||
assert!(!should_passthrough_run_view(&["--web".into()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_identifier_with_job_flag_after() {
|
||||
// gh run view 12345 --job 67890
|
||||
let args: Vec<String> = vec!["12345".into(), "--job".into(), "67890".into()];
|
||||
let (id, extra) = extract_identifier_and_extra_args(&args).unwrap();
|
||||
assert_eq!(id, "12345");
|
||||
assert_eq!(extra, vec!["--job", "67890"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_identifier_with_job_flag_before() {
|
||||
// gh run view --job 67890 12345
|
||||
let args: Vec<String> = vec!["--job".into(), "67890".into(), "12345".into()];
|
||||
let (id, extra) = extract_identifier_and_extra_args(&args).unwrap();
|
||||
assert_eq!(id, "12345");
|
||||
assert_eq!(extra, vec!["--job", "67890"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_identifier_with_job_and_log_failed() {
|
||||
// gh run view --log-failed --job 67890 12345
|
||||
let args: Vec<String> = vec![
|
||||
"--log-failed".into(),
|
||||
"--job".into(),
|
||||
"67890".into(),
|
||||
"12345".into(),
|
||||
];
|
||||
let (id, extra) = extract_identifier_and_extra_args(&args).unwrap();
|
||||
assert_eq!(id, "12345");
|
||||
assert_eq!(extra, vec!["--log-failed", "--job", "67890"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_identifier_with_attempt_flag() {
|
||||
// gh run view 12345 --attempt 3
|
||||
let args: Vec<String> = vec!["12345".into(), "--attempt".into(), "3".into()];
|
||||
let (id, extra) = extract_identifier_and_extra_args(&args).unwrap();
|
||||
assert_eq!(id, "12345");
|
||||
assert_eq!(extra, vec!["--attempt", "3"]);
|
||||
}
|
||||
|
||||
// --- should_passthrough_pr_view tests ---
|
||||
|
||||
#[test]
|
||||
fn test_should_passthrough_pr_view_json() {
|
||||
assert!(should_passthrough_pr_view(&[
|
||||
"--json".into(),
|
||||
"body,comments".into()
|
||||
]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_should_passthrough_pr_view_jq() {
|
||||
assert!(should_passthrough_pr_view(&["--jq".into(), ".body".into()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_should_passthrough_pr_view_web() {
|
||||
assert!(should_passthrough_pr_view(&["--web".into()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_should_passthrough_pr_view_default() {
|
||||
assert!(!should_passthrough_pr_view(&[]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_should_passthrough_pr_view_other_flags() {
|
||||
assert!(!should_passthrough_pr_view(&["--comments".into()]));
|
||||
}
|
||||
|
||||
// --- filter_markdown_body tests ---
|
||||
|
||||
#[test]
|
||||
|
||||
+13
-100
@@ -130,7 +130,7 @@ fn run_diff(
|
||||
let mut final_output = stat_stdout.to_string();
|
||||
if !diff_stdout.is_empty() {
|
||||
println!("\n--- Changes ---");
|
||||
let compacted = compact_diff(&diff_stdout, max_lines.unwrap_or(500));
|
||||
let compacted = compact_diff(&diff_stdout, max_lines.unwrap_or(100));
|
||||
println!("{}", compacted);
|
||||
final_output.push_str("\n--- Changes ---\n");
|
||||
final_output.push_str(&compacted);
|
||||
@@ -250,7 +250,7 @@ fn run_show(
|
||||
if verbose > 0 {
|
||||
println!("\n--- Changes ---");
|
||||
}
|
||||
let compacted = compact_diff(diff_text, max_lines.unwrap_or(500));
|
||||
let compacted = compact_diff(diff_text, max_lines.unwrap_or(100));
|
||||
println!("{}", compacted);
|
||||
final_output.push_str(&format!("\n{}", compacted));
|
||||
}
|
||||
@@ -277,7 +277,7 @@ pub(crate) fn compact_diff(diff: &str, max_lines: usize) -> String {
|
||||
let mut removed = 0;
|
||||
let mut in_hunk = false;
|
||||
let mut hunk_lines = 0;
|
||||
let max_hunk_lines = 30;
|
||||
let max_hunk_lines = 10;
|
||||
|
||||
for line in diff.lines() {
|
||||
if line.starts_with("diff --git") {
|
||||
@@ -352,11 +352,9 @@ fn run_log(
|
||||
arg.starts_with("--oneline") || arg.starts_with("--pretty") || arg.starts_with("--format")
|
||||
});
|
||||
|
||||
// Check if user provided limit flag (-N, -n N, --max-count=N, --max-count N)
|
||||
// Check if user provided limit flag
|
||||
let has_limit_flag = args.iter().any(|arg| {
|
||||
(arg.starts_with('-') && arg.chars().nth(1).map_or(false, |c| c.is_ascii_digit()))
|
||||
|| arg == "-n"
|
||||
|| arg.starts_with("--max-count")
|
||||
arg.starts_with('-') && arg.chars().nth(1).map_or(false, |c| c.is_ascii_digit())
|
||||
});
|
||||
|
||||
// Apply RTK defaults only if user didn't specify them
|
||||
@@ -364,22 +362,17 @@ fn run_log(
|
||||
cmd.args(["--pretty=format:%h %s (%ar) <%an>"]);
|
||||
}
|
||||
|
||||
// Only inject -10 limit when RTK is applying its own format.
|
||||
// When user provides --oneline/--pretty/--format, respect git's default (no limit).
|
||||
let limit = if !has_limit_flag && !has_format_flag {
|
||||
let limit = if !has_limit_flag {
|
||||
cmd.arg("-10");
|
||||
10
|
||||
} else if has_limit_flag {
|
||||
} else {
|
||||
// Extract limit from args if provided
|
||||
args.iter()
|
||||
.find(|arg| {
|
||||
arg.starts_with('-') && arg.chars().nth(1).map_or(false, |c| c.is_ascii_digit())
|
||||
})
|
||||
.and_then(|arg| arg[1..].parse::<usize>().ok())
|
||||
.unwrap_or(500)
|
||||
} else {
|
||||
// User format, no limit — use a high cap for filter_log_output
|
||||
500
|
||||
.unwrap_or(10)
|
||||
};
|
||||
|
||||
// Only add --no-merges if user didn't explicitly request merge commits
|
||||
@@ -624,14 +617,11 @@ fn run_status(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
|
||||
if !stderr.is_empty() && stderr.contains("not a git repository") {
|
||||
let message = "Not a git repository".to_string();
|
||||
eprintln!("{}", message);
|
||||
timer.track("git status", "rtk git status", &raw_output, &message);
|
||||
std::process::exit(output.status.code().unwrap_or(128));
|
||||
}
|
||||
|
||||
let formatted = format_status_output(&stdout);
|
||||
let formatted = if !stderr.is_empty() && stderr.contains("not a git repository") {
|
||||
"Not a git repository".to_string()
|
||||
} else {
|
||||
format_status_output(&stdout)
|
||||
};
|
||||
|
||||
println!("{}", formatted);
|
||||
|
||||
@@ -1459,40 +1449,6 @@ mod tests {
|
||||
assert!(result.contains("+"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_compact_diff_increased_hunk_limit() {
|
||||
// Build a hunk with 25 changed lines — should NOT be truncated with limit 30
|
||||
let mut diff =
|
||||
"diff --git a/big.rs b/big.rs\n--- a/big.rs\n+++ b/big.rs\n@@ -1,25 +1,25 @@\n"
|
||||
.to_string();
|
||||
for i in 1..=25 {
|
||||
diff.push_str(&format!("+line{}\n", i));
|
||||
}
|
||||
let result = compact_diff(&diff, 500);
|
||||
assert!(
|
||||
!result.contains("... (truncated)"),
|
||||
"25 lines should not be truncated with max_hunk_lines=30"
|
||||
);
|
||||
assert!(result.contains("+line25"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_compact_diff_increased_total_limit() {
|
||||
// Build a diff with 150 output result lines across multiple files — should NOT be cut at 100
|
||||
let mut diff = String::new();
|
||||
for f in 1..=5 {
|
||||
diff.push_str(&format!("diff --git a/file{f}.rs b/file{f}.rs\n--- a/file{f}.rs\n+++ b/file{f}.rs\n@@ -1,20 +1,20 @@\n"));
|
||||
for i in 1..=20 {
|
||||
diff.push_str(&format!("+line{f}_{i}\n"));
|
||||
}
|
||||
}
|
||||
let result = compact_diff(&diff, 500);
|
||||
assert!(
|
||||
!result.contains("more changes truncated"),
|
||||
"5 files × 20 lines should not exceed max_lines=500"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_blob_show_arg() {
|
||||
assert!(is_blob_show_arg("develop:modules/pairs_backtest.py"));
|
||||
@@ -1820,47 +1776,4 @@ no changes added to commit (use "git add" and/or "git commit -a")
|
||||
.collect();
|
||||
assert_eq!(cmd_args, vec!["commit", "--amend", "-m", "new msg"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore] // Requires `cargo build` first — run with `cargo test --ignored`
|
||||
fn test_git_status_not_a_repo_exits_nonzero() {
|
||||
// Run rtk git status in a directory that is not a git repo
|
||||
let tmp = std::env::temp_dir().join("rtk_test_not_a_repo");
|
||||
let _ = std::fs::create_dir_all(&tmp);
|
||||
|
||||
// Build the path to the test binary
|
||||
let bin_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("target")
|
||||
.join("debug")
|
||||
.join("rtk");
|
||||
assert!(
|
||||
bin_path.exists(),
|
||||
"Debug binary not found at {:?} — run `cargo build` first",
|
||||
bin_path
|
||||
);
|
||||
let output = std::process::Command::new(&bin_path)
|
||||
.args(["git", "status"])
|
||||
.current_dir(&tmp)
|
||||
.output()
|
||||
.expect("Failed to run rtk");
|
||||
|
||||
// Should exit with non-zero (128 from git)
|
||||
assert!(
|
||||
!output.status.success(),
|
||||
"Expected non-zero exit code for git status outside a repo, got {:?}",
|
||||
output.status.code()
|
||||
);
|
||||
|
||||
// Message should be on stderr, not stdout
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(
|
||||
stderr.to_lowercase().contains("not a git repository"),
|
||||
"Expected 'not a git repository' on stderr, got stderr={:?}, stdout={:?}",
|
||||
stderr,
|
||||
stdout
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&tmp);
|
||||
}
|
||||
}
|
||||
-810
@@ -1,810 +0,0 @@
|
||||
use crate::tracking;
|
||||
use crate::utils::{ok_confirmation, strip_ansi, truncate};
|
||||
use anyhow::{Context, Result};
|
||||
use lazy_static::lazy_static;
|
||||
use regex::Regex;
|
||||
use std::ffi::OsString;
|
||||
use std::process::Command;
|
||||
|
||||
lazy_static! {
|
||||
static ref EMAIL_RE: Regex =
|
||||
Regex::new(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b").unwrap();
|
||||
static ref BRANCH_NAME_RE: Regex = Regex::new(
|
||||
r#"(?:Created|Pushed|pushed|Deleted|deleted)\s+branch\s+[`"']?([a-zA-Z0-9/_.\-+@]+)"#
|
||||
)
|
||||
.unwrap();
|
||||
static ref PR_LINE_RE: Regex =
|
||||
Regex::new(r"(Created|Updated)\s+pull\s+request\s+#(\d+)\s+for\s+([^\s:]+)(?::\s*(\S+))?")
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn run_gt_filtered(
|
||||
subcmd: &[&str],
|
||||
args: &[String],
|
||||
verbose: u8,
|
||||
tee_label: &str,
|
||||
filter_fn: fn(&str) -> String,
|
||||
) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
let mut cmd = Command::new("gt");
|
||||
for part in subcmd {
|
||||
cmd.arg(part);
|
||||
}
|
||||
for arg in args {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
|
||||
let subcmd_str = subcmd.join(" ");
|
||||
if verbose > 0 {
|
||||
eprintln!("Running: gt {} {}", subcmd_str, args.join(" "));
|
||||
}
|
||||
|
||||
let cmd_output = cmd.output().with_context(|| {
|
||||
format!(
|
||||
"Failed to run gt {}. Is gt (Graphite) installed?",
|
||||
subcmd_str
|
||||
)
|
||||
})?;
|
||||
|
||||
let stdout = String::from_utf8_lossy(&cmd_output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&cmd_output.stderr);
|
||||
let raw = format!("{}\n{}", stdout, stderr);
|
||||
|
||||
let exit_code = cmd_output.status.code().unwrap_or(1);
|
||||
|
||||
let clean = strip_ansi(stdout.trim());
|
||||
let output = if verbose > 0 {
|
||||
clean.clone()
|
||||
} else {
|
||||
filter_fn(&clean)
|
||||
};
|
||||
|
||||
if let Some(hint) = crate::tee::tee_and_hint(&raw, tee_label, exit_code) {
|
||||
println!("{}\n{}", output, hint);
|
||||
} else {
|
||||
println!("{}", output);
|
||||
}
|
||||
|
||||
if !stderr.trim().is_empty() {
|
||||
eprintln!("{}", stderr.trim());
|
||||
}
|
||||
|
||||
let label = if args.is_empty() {
|
||||
format!("gt {}", subcmd_str)
|
||||
} else {
|
||||
format!("gt {} {}", subcmd_str, args.join(" "))
|
||||
};
|
||||
let rtk_label = format!("rtk {}", label);
|
||||
timer.track(&label, &rtk_label, &raw, &output);
|
||||
|
||||
if !cmd_output.status.success() {
|
||||
std::process::exit(exit_code);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn filter_identity(input: &str) -> String {
|
||||
input.to_string()
|
||||
}
|
||||
|
||||
pub fn run_log(args: &[String], verbose: u8) -> Result<()> {
|
||||
match args.first().map(|s| s.as_str()) {
|
||||
Some("short") => run_gt_filtered(
|
||||
&["log", "short"],
|
||||
&args[1..],
|
||||
verbose,
|
||||
"gt_log_short",
|
||||
filter_identity,
|
||||
),
|
||||
Some("long") => run_gt_filtered(
|
||||
&["log", "long"],
|
||||
&args[1..],
|
||||
verbose,
|
||||
"gt_log_long",
|
||||
filter_gt_log_entries,
|
||||
),
|
||||
_ => run_gt_filtered(&["log"], args, verbose, "gt_log", filter_gt_log_entries),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run_submit(args: &[String], verbose: u8) -> Result<()> {
|
||||
run_gt_filtered(&["submit"], args, verbose, "gt_submit", filter_gt_submit)
|
||||
}
|
||||
|
||||
pub fn run_sync(args: &[String], verbose: u8) -> Result<()> {
|
||||
run_gt_filtered(&["sync"], args, verbose, "gt_sync", filter_gt_sync)
|
||||
}
|
||||
|
||||
pub fn run_restack(args: &[String], verbose: u8) -> Result<()> {
|
||||
run_gt_filtered(&["restack"], args, verbose, "gt_restack", filter_gt_restack)
|
||||
}
|
||||
|
||||
pub fn run_create(args: &[String], verbose: u8) -> Result<()> {
|
||||
run_gt_filtered(&["create"], args, verbose, "gt_create", filter_gt_create)
|
||||
}
|
||||
|
||||
pub fn run_branch(args: &[String], verbose: u8) -> Result<()> {
|
||||
run_gt_filtered(&["branch"], args, verbose, "gt_branch", filter_identity)
|
||||
}
|
||||
|
||||
pub fn run_other(args: &[OsString], verbose: u8) -> Result<()> {
|
||||
if args.is_empty() {
|
||||
anyhow::bail!("gt: no subcommand specified");
|
||||
}
|
||||
|
||||
let subcommand = args[0].to_string_lossy();
|
||||
let rest: Vec<String> = args[1..]
|
||||
.iter()
|
||||
.map(|a| a.to_string_lossy().into())
|
||||
.collect();
|
||||
|
||||
// gt passes unknown subcommands to git, so "gt status" = "git status".
|
||||
// Route known git commands to RTK's git filters for token savings.
|
||||
match subcommand.as_ref() {
|
||||
"status" => crate::git::run(crate::git::GitCommand::Status, &rest, None, verbose, &[]),
|
||||
"diff" => crate::git::run(crate::git::GitCommand::Diff, &rest, None, verbose, &[]),
|
||||
"show" => crate::git::run(crate::git::GitCommand::Show, &rest, None, verbose, &[]),
|
||||
"add" => crate::git::run(crate::git::GitCommand::Add, &rest, None, verbose, &[]),
|
||||
"push" => crate::git::run(crate::git::GitCommand::Push, &rest, None, verbose, &[]),
|
||||
"pull" => crate::git::run(crate::git::GitCommand::Pull, &rest, None, verbose, &[]),
|
||||
"fetch" => crate::git::run(crate::git::GitCommand::Fetch, &rest, None, verbose, &[]),
|
||||
"stash" => {
|
||||
let stash_sub = rest.first().cloned();
|
||||
let stash_args = rest.get(1..).unwrap_or(&[]);
|
||||
crate::git::run(
|
||||
crate::git::GitCommand::Stash {
|
||||
subcommand: stash_sub,
|
||||
},
|
||||
stash_args,
|
||||
None,
|
||||
verbose,
|
||||
&[],
|
||||
)
|
||||
}
|
||||
"worktree" => crate::git::run(crate::git::GitCommand::Worktree, &rest, None, verbose, &[]),
|
||||
_ => passthrough_gt(&subcommand, &rest, verbose),
|
||||
}
|
||||
}
|
||||
|
||||
fn passthrough_gt(subcommand: &str, args: &[String], verbose: u8) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
let mut cmd = Command::new("gt");
|
||||
cmd.arg(subcommand);
|
||||
for arg in args {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
|
||||
if verbose > 0 {
|
||||
eprintln!("Running: gt {} {}", subcommand, args.join(" "));
|
||||
}
|
||||
|
||||
let status = cmd
|
||||
.status()
|
||||
.with_context(|| format!("Failed to run gt {}", subcommand))?;
|
||||
|
||||
let args_str = if args.is_empty() {
|
||||
subcommand.to_string()
|
||||
} else {
|
||||
format!("{} {}", subcommand, args.join(" "))
|
||||
};
|
||||
timer.track_passthrough(
|
||||
&format!("gt {}", args_str),
|
||||
&format!("rtk gt {} (passthrough)", args_str),
|
||||
);
|
||||
|
||||
if !status.success() {
|
||||
std::process::exit(status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const MAX_LOG_ENTRIES: usize = 15;
|
||||
|
||||
fn filter_gt_log_entries(input: &str) -> String {
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
let lines: Vec<&str> = trimmed.lines().collect();
|
||||
let mut result = Vec::new();
|
||||
let mut entry_count = 0;
|
||||
|
||||
for (i, line) in lines.iter().enumerate() {
|
||||
if is_graph_node(line) {
|
||||
entry_count += 1;
|
||||
}
|
||||
|
||||
let replaced = EMAIL_RE.replace_all(line, "");
|
||||
let processed = truncate(replaced.trim_end(), 120);
|
||||
result.push(processed);
|
||||
|
||||
if entry_count >= MAX_LOG_ENTRIES {
|
||||
let remaining = lines[i + 1..].iter().filter(|l| is_graph_node(l)).count();
|
||||
if remaining > 0 {
|
||||
result.push(format!("... +{} more entries", remaining));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
result.join("\n")
|
||||
}
|
||||
|
||||
fn filter_gt_submit(input: &str) -> String {
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
let mut pushed = Vec::new();
|
||||
let mut prs = Vec::new();
|
||||
|
||||
for line in trimmed.lines() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
if line.contains("pushed") || line.contains("Pushed") {
|
||||
pushed.push(extract_branch_name(line));
|
||||
} else if let Some(caps) = PR_LINE_RE.captures(line) {
|
||||
let action = caps[1].to_lowercase();
|
||||
let num = &caps[2];
|
||||
let branch = &caps[3];
|
||||
if let Some(url) = caps.get(4) {
|
||||
prs.push(format!(
|
||||
"{} PR #{} {} {}",
|
||||
action,
|
||||
num,
|
||||
branch,
|
||||
url.as_str()
|
||||
));
|
||||
} else {
|
||||
prs.push(format!("{} PR #{} {}", action, num, branch));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut summary = Vec::new();
|
||||
|
||||
if !pushed.is_empty() {
|
||||
let branch_names: Vec<&str> = pushed
|
||||
.iter()
|
||||
.map(|s| s.as_str())
|
||||
.filter(|s| !s.is_empty())
|
||||
.collect();
|
||||
if !branch_names.is_empty() {
|
||||
summary.push(format!("pushed {}", branch_names.join(", ")));
|
||||
} else {
|
||||
summary.push(format!("pushed {} branches", pushed.len()));
|
||||
}
|
||||
}
|
||||
|
||||
summary.extend(prs);
|
||||
|
||||
if summary.is_empty() {
|
||||
return truncate(trimmed, 200);
|
||||
}
|
||||
|
||||
summary.join("\n")
|
||||
}
|
||||
|
||||
fn filter_gt_sync(input: &str) -> String {
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
let mut synced = 0;
|
||||
let mut deleted = 0;
|
||||
let mut deleted_names = Vec::new();
|
||||
|
||||
for line in trimmed.lines() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (line.contains("Synced") && line.contains("branch"))
|
||||
|| line.starts_with("Synced with remote")
|
||||
{
|
||||
synced += 1;
|
||||
}
|
||||
if line.contains("deleted") || line.contains("Deleted") {
|
||||
deleted += 1;
|
||||
let name = extract_branch_name(line);
|
||||
if !name.is_empty() {
|
||||
deleted_names.push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut parts = Vec::new();
|
||||
|
||||
if synced > 0 {
|
||||
parts.push(format!("{} synced", synced));
|
||||
}
|
||||
|
||||
if deleted > 0 {
|
||||
if deleted_names.is_empty() {
|
||||
parts.push(format!("{} deleted", deleted));
|
||||
} else {
|
||||
parts.push(format!(
|
||||
"{} deleted ({})",
|
||||
deleted,
|
||||
deleted_names.join(", ")
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if parts.is_empty() {
|
||||
return ok_confirmation("synced", "");
|
||||
}
|
||||
|
||||
format!("ok sync: {}", parts.join(", "))
|
||||
}
|
||||
|
||||
fn filter_gt_restack(input: &str) -> String {
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
let mut restacked = 0;
|
||||
for line in trimmed.lines() {
|
||||
let line = line.trim();
|
||||
if (line.contains("Restacked") || line.contains("Rebased")) && line.contains("branch") {
|
||||
restacked += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if restacked > 0 {
|
||||
ok_confirmation("restacked", &format!("{} branches", restacked))
|
||||
} else {
|
||||
ok_confirmation("restacked", "")
|
||||
}
|
||||
}
|
||||
|
||||
fn filter_gt_create(input: &str) -> String {
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
let branch_name = trimmed
|
||||
.lines()
|
||||
.find_map(|line| {
|
||||
let line = line.trim();
|
||||
if line.contains("Created") || line.contains("created") {
|
||||
Some(extract_branch_name(line))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
if branch_name.is_empty() {
|
||||
let first_line = trimmed.lines().next().unwrap_or("");
|
||||
ok_confirmation("created", first_line.trim())
|
||||
} else {
|
||||
ok_confirmation("created", &branch_name)
|
||||
}
|
||||
}
|
||||
|
||||
fn is_graph_node(line: &str) -> bool {
|
||||
let stripped = line
|
||||
.trim_start_matches('│')
|
||||
.trim_start_matches('|')
|
||||
.trim_start();
|
||||
stripped.starts_with('◉')
|
||||
|| stripped.starts_with('○')
|
||||
|| stripped.starts_with('◯')
|
||||
|| stripped.starts_with('◆')
|
||||
|| stripped.starts_with('●')
|
||||
|| stripped.starts_with('@')
|
||||
|| stripped.starts_with('*')
|
||||
}
|
||||
|
||||
fn extract_branch_name(line: &str) -> String {
|
||||
BRANCH_NAME_RE
|
||||
.captures(line)
|
||||
.and_then(|cap| cap.get(1))
|
||||
.map(|m| m.as_str().to_string())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn count_tokens(text: &str) -> usize {
|
||||
text.split_whitespace().count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_gt_log_exact_format() {
|
||||
let input = r#"◉ abc1234 feat/add-auth 2d ago
|
||||
│ feat(auth): add login endpoint
|
||||
│
|
||||
◉ def5678 feat/add-db 3d ago user@example.com
|
||||
│ feat(db): add migration system
|
||||
│
|
||||
◉ ghi9012 main 5d ago admin@corp.io
|
||||
│ chore: update dependencies
|
||||
~
|
||||
"#;
|
||||
let output = filter_gt_log_entries(input);
|
||||
let expected = "\
|
||||
◉ abc1234 feat/add-auth 2d ago
|
||||
│ feat(auth): add login endpoint
|
||||
│
|
||||
◉ def5678 feat/add-db 3d ago
|
||||
│ feat(db): add migration system
|
||||
│
|
||||
◉ ghi9012 main 5d ago
|
||||
│ chore: update dependencies
|
||||
~";
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_gt_submit_exact_format() {
|
||||
let input = r#"Pushed branch feat/add-auth
|
||||
Created pull request #42 for feat/add-auth
|
||||
Pushed branch feat/add-db
|
||||
Updated pull request #40 for feat/add-db
|
||||
"#;
|
||||
let output = filter_gt_submit(input);
|
||||
let expected = "\
|
||||
pushed feat/add-auth, feat/add-db
|
||||
created PR #42 feat/add-auth
|
||||
updated PR #40 feat/add-db";
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_gt_sync_exact_format() {
|
||||
let input = r#"Synced with remote
|
||||
Deleted branch feat/merged-feature
|
||||
Deleted branch fix/old-hotfix
|
||||
"#;
|
||||
let output = filter_gt_sync(input);
|
||||
assert_eq!(
|
||||
output,
|
||||
"ok sync: 1 synced, 2 deleted (feat/merged-feature, fix/old-hotfix)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_gt_restack_exact_format() {
|
||||
let input = r#"Restacked branch feat/add-auth on main
|
||||
Restacked branch feat/add-db on feat/add-auth
|
||||
Restacked branch fix/parsing on feat/add-db
|
||||
"#;
|
||||
let output = filter_gt_restack(input);
|
||||
assert_eq!(output, "ok restacked 3 branches");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_gt_create_exact_format() {
|
||||
let input = "Created branch feat/new-feature\n";
|
||||
let output = filter_gt_create(input);
|
||||
assert_eq!(output, "ok created feat/new-feature");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_gt_log_truncation() {
|
||||
let mut input = String::new();
|
||||
for i in 0..20 {
|
||||
input.push_str(&format!(
|
||||
"◉ hash{:02} branch-{} 1d ago dev@example.com\n│ commit message {}\n│\n",
|
||||
i, i, i
|
||||
));
|
||||
}
|
||||
input.push_str("~\n");
|
||||
|
||||
let output = filter_gt_log_entries(&input);
|
||||
assert!(output.contains("... +"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_gt_log_empty() {
|
||||
assert_eq!(filter_gt_log_entries(""), String::new());
|
||||
assert_eq!(filter_gt_log_entries(" "), String::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_gt_log_token_savings() {
|
||||
let mut input = String::new();
|
||||
for i in 0..40 {
|
||||
input.push_str(&format!(
|
||||
"◉ hash{:02}abc feat/feature-{} {}d ago developer{}@longcompany.example.com\n\
|
||||
│ feat(module-{}): implement feature {} with detailed description of changes\n│\n",
|
||||
i,
|
||||
i,
|
||||
i + 1,
|
||||
i,
|
||||
i,
|
||||
i
|
||||
));
|
||||
}
|
||||
input.push_str("~\n");
|
||||
|
||||
let output = filter_gt_log_entries(&input);
|
||||
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,
|
||||
"gt log filter: expected >=60% savings, got {:.1}% ({} -> {} tokens)",
|
||||
savings,
|
||||
input_tokens,
|
||||
output_tokens
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_gt_log_long() {
|
||||
let input = r#"◉ abc1234 feat/add-auth
|
||||
│ Author: Dev User <dev@example.com>
|
||||
│ Date: 2026-02-25 10:30:00 -0800
|
||||
│
|
||||
│ feat(auth): add login endpoint with OAuth2 support
|
||||
│ and session management for web clients
|
||||
│
|
||||
◉ def5678 feat/add-db
|
||||
│ Author: Other Dev <other@example.com>
|
||||
│ Date: 2026-02-24 14:00:00 -0800
|
||||
│
|
||||
│ feat(db): add migration system
|
||||
~
|
||||
"#;
|
||||
|
||||
let output = filter_gt_log_entries(input);
|
||||
assert!(output.contains("abc1234"));
|
||||
assert!(!output.contains("dev@example.com"));
|
||||
assert!(!output.contains("other@example.com"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_gt_submit_empty() {
|
||||
assert_eq!(filter_gt_submit(""), String::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_gt_submit_with_urls() {
|
||||
let input =
|
||||
"Created pull request #42 for feat/add-auth: https://github.com/org/repo/pull/42\n";
|
||||
let output = filter_gt_submit(input);
|
||||
assert!(output.contains("PR #42"));
|
||||
assert!(output.contains("feat/add-auth"));
|
||||
assert!(output.contains("https://github.com/org/repo/pull/42"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_gt_submit_token_savings() {
|
||||
let input = r#"
|
||||
✅ Pushing to remote...
|
||||
Enumerating objects: 15, done.
|
||||
Counting objects: 100% (15/15), done.
|
||||
Delta compression using up to 10 threads
|
||||
Compressing objects: 100% (8/8), done.
|
||||
Writing objects: 100% (10/10), 2.50 KiB | 2.50 MiB/s, done.
|
||||
Total 10 (delta 5), reused 0 (delta 0), pack-reused 0
|
||||
Pushed branch feat/add-auth to origin
|
||||
Creating pull request for feat/add-auth...
|
||||
Created pull request #42 for feat/add-auth: https://github.com/org/repo/pull/42
|
||||
✅ Pushing to remote...
|
||||
Enumerating objects: 8, done.
|
||||
Counting objects: 100% (8/8), done.
|
||||
Delta compression using up to 10 threads
|
||||
Compressing objects: 100% (4/4), done.
|
||||
Writing objects: 100% (5/5), 1.20 KiB | 1.20 MiB/s, done.
|
||||
Total 5 (delta 3), reused 0 (delta 0), pack-reused 0
|
||||
Pushed branch feat/add-db to origin
|
||||
Updating pull request for feat/add-db...
|
||||
Updated pull request #40 for feat/add-db: https://github.com/org/repo/pull/40
|
||||
✅ Pushing to remote...
|
||||
Enumerating objects: 5, done.
|
||||
Counting objects: 100% (5/5), done.
|
||||
Delta compression using up to 10 threads
|
||||
Compressing objects: 100% (3/3), done.
|
||||
Writing objects: 100% (3/3), 890 bytes | 890.00 KiB/s, done.
|
||||
Total 3 (delta 2), reused 0 (delta 0), pack-reused 0
|
||||
Pushed branch fix/parsing to origin
|
||||
All branches submitted successfully!
|
||||
"#;
|
||||
|
||||
let output = filter_gt_submit(input);
|
||||
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,
|
||||
"gt submit filter: expected >=60% savings, got {:.1}% ({} -> {} tokens)",
|
||||
savings,
|
||||
input_tokens,
|
||||
output_tokens
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_gt_sync() {
|
||||
let input = r#"Synced with remote
|
||||
Deleted branch feat/merged-feature
|
||||
Deleted branch fix/old-hotfix
|
||||
"#;
|
||||
|
||||
let output = filter_gt_sync(input);
|
||||
assert!(output.contains("ok sync"));
|
||||
assert!(output.contains("synced"));
|
||||
assert!(output.contains("deleted"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_gt_sync_empty() {
|
||||
assert_eq!(filter_gt_sync(""), String::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_gt_sync_no_deletes() {
|
||||
let input = "Synced with remote\n";
|
||||
let output = filter_gt_sync(input);
|
||||
assert!(output.contains("ok sync"));
|
||||
assert!(output.contains("synced"));
|
||||
assert!(!output.contains("deleted"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_gt_restack() {
|
||||
let input = r#"Restacked branch feat/add-auth on main
|
||||
Restacked branch feat/add-db on feat/add-auth
|
||||
Restacked branch fix/parsing on feat/add-db
|
||||
"#;
|
||||
|
||||
let output = filter_gt_restack(input);
|
||||
assert!(output.contains("ok restacked"));
|
||||
assert!(output.contains("3 branches"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_gt_restack_empty() {
|
||||
assert_eq!(filter_gt_restack(""), String::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_gt_create() {
|
||||
let input = "Created branch feat/new-feature\n";
|
||||
let output = filter_gt_create(input);
|
||||
assert_eq!(output, "ok created feat/new-feature");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_gt_create_empty() {
|
||||
assert_eq!(filter_gt_create(""), String::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_gt_create_no_branch_name() {
|
||||
let input = "Some unexpected output\n";
|
||||
let output = filter_gt_create(input);
|
||||
assert!(output.starts_with("ok created"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_graph_node() {
|
||||
assert!(is_graph_node("◉ abc1234 main"));
|
||||
assert!(is_graph_node("○ def5678 feat/x"));
|
||||
assert!(is_graph_node("@ ghi9012 (current)"));
|
||||
assert!(is_graph_node("* jkl3456 branch"));
|
||||
assert!(is_graph_node("│ ◉ nested node"));
|
||||
assert!(!is_graph_node("│ just a message line"));
|
||||
assert!(!is_graph_node("~"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_branch_name() {
|
||||
assert_eq!(
|
||||
extract_branch_name("Created branch feat/new-feature"),
|
||||
"feat/new-feature"
|
||||
);
|
||||
assert_eq!(
|
||||
extract_branch_name("Pushed branch fix/bug-123"),
|
||||
"fix/bug-123"
|
||||
);
|
||||
assert_eq!(
|
||||
extract_branch_name("Pushed branch feat/auth+session"),
|
||||
"feat/auth+session"
|
||||
);
|
||||
assert_eq!(extract_branch_name("Created branch user@fix"), "user@fix");
|
||||
assert_eq!(extract_branch_name("no branch here"), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_gt_log_pre_stripped_input() {
|
||||
let input = "◉ abc1234 feat/x 1d ago user@test.com\n│ message\n~\n";
|
||||
let output = filter_gt_log_entries(input);
|
||||
assert!(output.contains("abc1234"));
|
||||
assert!(!output.contains("user@test.com"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_gt_sync_token_savings() {
|
||||
let input = r#"
|
||||
✅ Syncing with remote...
|
||||
Pulling latest changes from main...
|
||||
Successfully pulled 5 new commits
|
||||
Synced branch feat/add-auth with remote
|
||||
Synced branch feat/add-db with remote
|
||||
Branch feat/merged-feature has been merged
|
||||
Deleted branch feat/merged-feature
|
||||
Branch fix/old-hotfix has been merged
|
||||
Deleted branch fix/old-hotfix
|
||||
All branches synced!
|
||||
"#;
|
||||
|
||||
let output = filter_gt_sync(input);
|
||||
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,
|
||||
"gt sync filter: expected >=60% savings, got {:.1}% ({} -> {} tokens)",
|
||||
savings,
|
||||
input_tokens,
|
||||
output_tokens
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_gt_create_token_savings() {
|
||||
let input = r#"
|
||||
✅ Creating new branch...
|
||||
Checking out from feat/add-auth...
|
||||
Created branch feat/new-feature from feat/add-auth
|
||||
Tracking branch set up to follow feat/add-auth
|
||||
Branch feat/new-feature is ready for development
|
||||
"#;
|
||||
|
||||
let output = filter_gt_create(input);
|
||||
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,
|
||||
"gt create filter: expected >=60% savings, got {:.1}% ({} -> {} tokens)",
|
||||
savings,
|
||||
input_tokens,
|
||||
output_tokens
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_gt_restack_token_savings() {
|
||||
let input = r#"
|
||||
✅ Restacking branches...
|
||||
Restacked branch feat/add-auth on top of main
|
||||
Successfully rebased feat/add-auth (3 commits)
|
||||
Restacked branch feat/add-db on top of feat/add-auth
|
||||
Successfully rebased feat/add-db (2 commits)
|
||||
Restacked branch fix/parsing on top of feat/add-db
|
||||
Successfully rebased fix/parsing (1 commit)
|
||||
All branches restacked!
|
||||
"#;
|
||||
|
||||
let output = filter_gt_restack(input);
|
||||
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,
|
||||
"gt restack filter: expected >=60% savings, got {:.1}%",
|
||||
savings
|
||||
);
|
||||
}
|
||||
}
|
||||
+14
-97
@@ -3,79 +3,42 @@ use std::path::PathBuf;
|
||||
const CURRENT_HOOK_VERSION: u8 = 2;
|
||||
const WARN_INTERVAL_SECS: u64 = 24 * 3600;
|
||||
|
||||
/// Hook status for diagnostics and `rtk gain`.
|
||||
#[derive(Debug, PartialEq, Clone)]
|
||||
pub enum HookStatus {
|
||||
/// Hook is installed and up to date.
|
||||
Ok,
|
||||
/// Hook exists but is outdated or unreadable.
|
||||
Outdated,
|
||||
/// No hook file found (but Claude Code is installed).
|
||||
Missing,
|
||||
}
|
||||
|
||||
/// Return the current hook status without printing anything.
|
||||
/// Returns `Ok` if no Claude Code is detected (not applicable).
|
||||
pub fn status() -> HookStatus {
|
||||
// Don't warn users who don't have Claude Code installed
|
||||
let home = match dirs::home_dir() {
|
||||
Some(h) => h,
|
||||
None => return HookStatus::Ok,
|
||||
};
|
||||
if !home.join(".claude").exists() {
|
||||
return HookStatus::Ok;
|
||||
}
|
||||
|
||||
let Some(hook_path) = hook_installed_path() else {
|
||||
return HookStatus::Missing;
|
||||
};
|
||||
let Ok(content) = std::fs::read_to_string(&hook_path) else {
|
||||
return HookStatus::Outdated; // exists but unreadable — treat as needs-update
|
||||
};
|
||||
if parse_hook_version(&content) >= CURRENT_HOOK_VERSION {
|
||||
HookStatus::Ok
|
||||
} else {
|
||||
HookStatus::Outdated
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if the installed hook is missing or outdated, warn once per day.
|
||||
/// Check if the installed hook is outdated, warn once per day.
|
||||
pub fn maybe_warn() {
|
||||
// Don't block startup — fail silently on any error
|
||||
let _ = check_and_warn();
|
||||
}
|
||||
|
||||
/// Single source of truth: delegates to `status()` then rate-limits the warning.
|
||||
fn check_and_warn() -> Option<()> {
|
||||
let warning = match status() {
|
||||
HookStatus::Ok => return Some(()),
|
||||
HookStatus::Missing => {
|
||||
"[rtk] /!\\ No hook installed — run `rtk init -g` for automatic token savings"
|
||||
}
|
||||
HookStatus::Outdated => "[rtk] /!\\ Hook outdated — run `rtk init -g` to update",
|
||||
};
|
||||
let hook_path = hook_installed_path()?;
|
||||
let content = std::fs::read_to_string(&hook_path).ok()?;
|
||||
|
||||
let installed_version = parse_hook_version(&content);
|
||||
|
||||
if installed_version >= CURRENT_HOOK_VERSION {
|
||||
return Some(());
|
||||
}
|
||||
|
||||
// Rate limit: warn once per day
|
||||
let marker = warn_marker_path()?;
|
||||
if let Ok(meta) = std::fs::metadata(&marker) {
|
||||
if let Ok(modified) = meta.modified() {
|
||||
if modified.elapsed().map(|e| e.as_secs()).unwrap_or(u64::MAX) < WARN_INTERVAL_SECS {
|
||||
if let Ok(elapsed) = meta.modified().ok()?.elapsed() {
|
||||
if elapsed.as_secs() < WARN_INTERVAL_SECS {
|
||||
return Some(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
eprintln!("{}", warning);
|
||||
|
||||
// Touch marker after warning is printed
|
||||
// Touch marker
|
||||
let _ = std::fs::create_dir_all(marker.parent()?);
|
||||
let _ = std::fs::write(&marker, b"");
|
||||
|
||||
eprintln!("[rtk] Hook outdated — run `rtk init -g` to update");
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
pub fn parse_hook_version(content: &str) -> u8 {
|
||||
// Version tag must be in the first 5 lines (shebang + header convention)
|
||||
for line in content.lines().take(5) {
|
||||
if let Some(rest) = line.strip_prefix("# rtk-hook-version:") {
|
||||
if let Ok(v) = rest.trim().parse::<u8>() {
|
||||
@@ -122,50 +85,4 @@ mod tests {
|
||||
let content = "#!/usr/bin/env bash\n# rtk-hook-version: 5\n";
|
||||
assert_eq!(parse_hook_version(content), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_hook_version_no_tag() {
|
||||
assert_eq!(parse_hook_version("no version here"), 0);
|
||||
assert_eq!(parse_hook_version(""), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hook_status_enum() {
|
||||
assert_ne!(HookStatus::Ok, HookStatus::Missing);
|
||||
assert_ne!(HookStatus::Outdated, HookStatus::Missing);
|
||||
assert_eq!(HookStatus::Ok, HookStatus::Ok);
|
||||
// Clone works
|
||||
let s = HookStatus::Missing;
|
||||
assert_eq!(s.clone(), HookStatus::Missing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_status_returns_valid_variant() {
|
||||
// Skip on machines without Claude Code or without hook
|
||||
let home = match dirs::home_dir() {
|
||||
Some(h) => h,
|
||||
None => return,
|
||||
};
|
||||
if !home
|
||||
.join(".claude")
|
||||
.join("hooks")
|
||||
.join("rtk-rewrite.sh")
|
||||
.exists()
|
||||
{
|
||||
// No hook — status should be Missing (if .claude exists) or Ok (if not)
|
||||
let s = status();
|
||||
if home.join(".claude").exists() {
|
||||
assert_eq!(s, HookStatus::Missing);
|
||||
} else {
|
||||
assert_eq!(s, HookStatus::Ok);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let s = status();
|
||||
assert!(
|
||||
s == HookStatus::Ok || s == HookStatus::Outdated,
|
||||
"Expected Ok or Outdated when hook exists, got {:?}",
|
||||
s
|
||||
);
|
||||
}
|
||||
}
|
||||
+2
-87
@@ -12,37 +12,6 @@ const REWRITE_HOOK: &str = include_str!("../hooks/rtk-rewrite.sh");
|
||||
// Embedded slim RTK awareness instructions
|
||||
const RTK_SLIM: &str = include_str!("../hooks/rtk-awareness.md");
|
||||
|
||||
/// Template written by `rtk init` when no filters.toml exists yet.
|
||||
const FILTERS_TEMPLATE: &str = r#"# Project-local RTK filters — commit this file with your repo.
|
||||
# Filters here override user-global and built-in filters.
|
||||
# Docs: https://github.com/rtk-ai/rtk#custom-filters
|
||||
schema_version = 1
|
||||
|
||||
# Example: suppress build noise from a custom tool
|
||||
# [filters.my-tool]
|
||||
# description = "Compact my-tool output"
|
||||
# match_command = "^my-tool\\s+build"
|
||||
# strip_ansi = true
|
||||
# strip_lines_matching = ["^\\s*$", "^Downloading", "^Installing"]
|
||||
# max_lines = 30
|
||||
# on_empty = "my-tool: ok"
|
||||
"#;
|
||||
|
||||
/// Template for user-global filters (~/.config/rtk/filters.toml).
|
||||
const FILTERS_GLOBAL_TEMPLATE: &str = r#"# User-global RTK filters — apply to all your projects.
|
||||
# Project-local .rtk/filters.toml takes precedence over these.
|
||||
# Docs: https://github.com/rtk-ai/rtk#custom-filters
|
||||
schema_version = 1
|
||||
|
||||
# Example: suppress noise from a tool you use everywhere
|
||||
# [filters.my-global-tool]
|
||||
# description = "Compact my-global-tool output"
|
||||
# match_command = "^my-global-tool\\b"
|
||||
# strip_ansi = true
|
||||
# strip_lines_matching = ["^\\s*$"]
|
||||
# max_lines = 40
|
||||
"#;
|
||||
|
||||
/// Control flow for settings.json patching
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum PatchMode {
|
||||
@@ -697,10 +666,8 @@ fn run_default_mode(_global: bool, _patch_mode: PatchMode, _verbose: u8) -> Resu
|
||||
#[cfg(unix)]
|
||||
fn run_default_mode(global: bool, patch_mode: PatchMode, verbose: u8) -> Result<()> {
|
||||
if !global {
|
||||
// Local init: inject CLAUDE.md + generate project-local filters template
|
||||
run_claude_md_mode(false, verbose)?;
|
||||
generate_project_filters_template(verbose)?;
|
||||
return Ok(());
|
||||
// Local init: unchanged behavior (full injection into ./CLAUDE.md)
|
||||
return run_claude_md_mode(false, verbose);
|
||||
}
|
||||
|
||||
let claude_dir = resolve_claude_dir()?;
|
||||
@@ -750,63 +717,11 @@ fn run_default_mode(global: bool, patch_mode: PatchMode, verbose: u8) -> Result<
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Generate user-global filters template (~/.config/rtk/filters.toml)
|
||||
generate_global_filters_template(verbose)?;
|
||||
|
||||
println!(); // Final newline
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Generate .rtk/filters.toml template in the current directory if not present.
|
||||
fn generate_project_filters_template(verbose: u8) -> Result<()> {
|
||||
let rtk_dir = std::path::Path::new(".rtk");
|
||||
let path = rtk_dir.join("filters.toml");
|
||||
|
||||
if path.exists() {
|
||||
if verbose > 0 {
|
||||
eprintln!(".rtk/filters.toml already exists, skipping template");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
fs::create_dir_all(rtk_dir)
|
||||
.with_context(|| format!("Failed to create directory: {}", rtk_dir.display()))?;
|
||||
fs::write(&path, FILTERS_TEMPLATE)
|
||||
.with_context(|| format!("Failed to write {}", path.display()))?;
|
||||
|
||||
println!(
|
||||
" filters: {} (template, edit to add project filters)",
|
||||
path.display()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Generate ~/.config/rtk/filters.toml template if not present.
|
||||
fn generate_global_filters_template(verbose: u8) -> Result<()> {
|
||||
let config_dir = dirs::config_dir().unwrap_or_else(|| std::path::PathBuf::from(".config"));
|
||||
let rtk_dir = config_dir.join("rtk");
|
||||
let path = rtk_dir.join("filters.toml");
|
||||
|
||||
if path.exists() {
|
||||
if verbose > 0 {
|
||||
eprintln!("{} already exists, skipping template", path.display());
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
fs::create_dir_all(&rtk_dir)
|
||||
.with_context(|| format!("Failed to create directory: {}", rtk_dir.display()))?;
|
||||
fs::write(&path, FILTERS_GLOBAL_TEMPLATE)
|
||||
.with_context(|| format!("Failed to write {}", path.display()))?;
|
||||
|
||||
println!(
|
||||
" filters: {} (template, edit to add user-global filters)",
|
||||
path.display()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Hook-only mode: just the hook, no RTK.md
|
||||
#[cfg(not(unix))]
|
||||
fn run_hook_only_mode(_global: bool, _patch_mode: PatchMode, _verbose: u8) -> Result<()> {
|
||||
|
||||
@@ -121,7 +121,6 @@ fn lang_display_name(lang: &Language) -> &'static str {
|
||||
Language::Java => "Java",
|
||||
Language::Ruby => "Ruby",
|
||||
Language::Shell => "Shell",
|
||||
Language::Data => "Data",
|
||||
Language::Unknown => "Code",
|
||||
}
|
||||
}
|
||||
|
||||
+36
-334
@@ -19,7 +19,6 @@ mod git;
|
||||
mod go_cmd;
|
||||
mod golangci_cmd;
|
||||
mod grep_cmd;
|
||||
mod gt_cmd;
|
||||
mod hook_audit_cmd;
|
||||
mod hook_check;
|
||||
mod init;
|
||||
@@ -48,12 +47,10 @@ mod runner;
|
||||
mod summary;
|
||||
mod tee;
|
||||
mod telemetry;
|
||||
mod toml_filter;
|
||||
mod tracking;
|
||||
mod tree;
|
||||
mod tsc_cmd;
|
||||
mod utils;
|
||||
mod verify_cmd;
|
||||
mod vitest_cmd;
|
||||
mod wc_cmd;
|
||||
mod wget_cmd;
|
||||
@@ -552,15 +549,8 @@ enum Commands {
|
||||
args: Vec<OsString>,
|
||||
},
|
||||
|
||||
/// Verify hook integrity and run TOML filter inline tests
|
||||
Verify {
|
||||
/// Run tests only for this filter name
|
||||
#[arg(long)]
|
||||
filter: Option<String>,
|
||||
/// Fail if any filter has no inline tests (CI mode)
|
||||
#[arg(long)]
|
||||
require_all: bool,
|
||||
},
|
||||
/// Verify hook integrity (SHA-256 check)
|
||||
Verify,
|
||||
|
||||
/// Ruff linter/formatter with compact output
|
||||
Ruff {
|
||||
@@ -596,12 +586,6 @@ enum Commands {
|
||||
command: GoCommands,
|
||||
},
|
||||
|
||||
/// Graphite (gt) stacked PR commands with compact output
|
||||
Gt {
|
||||
#[command(subcommand)]
|
||||
command: GtCommands,
|
||||
},
|
||||
|
||||
/// golangci-lint with compact output
|
||||
#[command(name = "golangci-lint")]
|
||||
GolangciLint {
|
||||
@@ -627,9 +611,7 @@ enum Commands {
|
||||
/// REWRITTEN=$(rtk rewrite "$CMD") || exit 0
|
||||
Rewrite {
|
||||
/// Raw command to rewrite (e.g. "git status", "cargo test && git push")
|
||||
/// Accepts multiple args: `rtk rewrite ls -al` is equivalent to `rtk rewrite "ls -al"`
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
cmd: String,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -739,7 +721,7 @@ enum PnpmCommands {
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
},
|
||||
/// Build (generic passthrough, no framework-specific filter)
|
||||
/// Build (delegates to next build filter)
|
||||
Build {
|
||||
/// Additional build arguments
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
@@ -957,7 +939,6 @@ const RTK_META_COMMANDS: &[&str] = &[
|
||||
"proxy",
|
||||
"hook-audit",
|
||||
"cc-economics",
|
||||
"verify",
|
||||
];
|
||||
|
||||
fn run_fallback(parse_error: clap::Error) -> Result<()> {
|
||||
@@ -980,168 +961,41 @@ fn run_fallback(parse_error: clap::Error) -> Result<()> {
|
||||
// Start timer before execution to capture actual command runtime
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
// TOML filter lookup — bypass with RTK_NO_TOML=1
|
||||
// Use basename of args[0] so absolute paths (/usr/bin/make) still match "^make\b".
|
||||
let lookup_cmd = {
|
||||
let base = std::path::Path::new(&args[0])
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| args[0].clone());
|
||||
std::iter::once(base.as_str())
|
||||
.chain(args[1..].iter().map(|s| s.as_str()))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
};
|
||||
let toml_match = if std::env::var("RTK_NO_TOML").ok().as_deref() == Some("1") {
|
||||
None
|
||||
} else {
|
||||
toml_filter::find_matching_filter(&lookup_cmd)
|
||||
};
|
||||
let status = std::process::Command::new(&args[0])
|
||||
.args(&args[1..])
|
||||
.stdin(std::process::Stdio::inherit())
|
||||
.stdout(std::process::Stdio::inherit())
|
||||
.stderr(std::process::Stdio::inherit())
|
||||
.status();
|
||||
|
||||
if let Some(filter) = toml_match {
|
||||
// TOML match: capture stdout for filtering
|
||||
let result = std::process::Command::new(&args[0])
|
||||
.args(&args[1..])
|
||||
.stdin(std::process::Stdio::inherit())
|
||||
.stdout(std::process::Stdio::piped()) // capture
|
||||
.stderr(std::process::Stdio::inherit()) // stderr always direct
|
||||
.output();
|
||||
match status {
|
||||
Ok(s) => {
|
||||
timer.track_passthrough(&raw_command, &format!("rtk fallback: {}", raw_command));
|
||||
|
||||
match result {
|
||||
Ok(output) => {
|
||||
let stdout_raw = String::from_utf8_lossy(&output.stdout);
|
||||
tracking::record_parse_failure_silent(&raw_command, &error_message, true);
|
||||
|
||||
// Tee raw output BEFORE filtering on failure — lets LLM re-read if needed
|
||||
let tee_hint = if !output.status.success() {
|
||||
tee::tee_and_hint(&stdout_raw, &raw_command, output.status.code().unwrap_or(1))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let filtered = toml_filter::apply_filter(filter, &stdout_raw);
|
||||
println!("{}", filtered);
|
||||
if let Some(hint) = tee_hint {
|
||||
println!("{}", hint);
|
||||
}
|
||||
|
||||
timer.track(
|
||||
&raw_command,
|
||||
&format!("rtk:toml {}", raw_command),
|
||||
&stdout_raw,
|
||||
&filtered,
|
||||
);
|
||||
tracking::record_parse_failure_silent(&raw_command, &error_message, true);
|
||||
|
||||
if !output.status.success() {
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
// Command not found — same behaviour as no-TOML path
|
||||
tracking::record_parse_failure_silent(&raw_command, &error_message, false);
|
||||
eprintln!("[rtk: {}]", e);
|
||||
std::process::exit(127);
|
||||
if !s.success() {
|
||||
std::process::exit(s.code().unwrap_or(1));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// No TOML match: original passthrough behaviour (Stdio::inherit, streaming)
|
||||
let status = std::process::Command::new(&args[0])
|
||||
.args(&args[1..])
|
||||
.stdin(std::process::Stdio::inherit())
|
||||
.stdout(std::process::Stdio::inherit())
|
||||
.stderr(std::process::Stdio::inherit())
|
||||
.status();
|
||||
|
||||
match status {
|
||||
Ok(s) => {
|
||||
timer.track_passthrough(&raw_command, &format!("rtk fallback: {}", raw_command));
|
||||
|
||||
tracking::record_parse_failure_silent(&raw_command, &error_message, true);
|
||||
|
||||
if !s.success() {
|
||||
std::process::exit(s.code().unwrap_or(1));
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracking::record_parse_failure_silent(&raw_command, &error_message, false);
|
||||
// Command not found or other OS error — single message, no duplicate Clap error
|
||||
eprintln!("[rtk: {}]", e);
|
||||
std::process::exit(127);
|
||||
}
|
||||
Err(e) => {
|
||||
tracking::record_parse_failure_silent(&raw_command, &error_message, false);
|
||||
// Command not found or other OS error — show Clap's original error
|
||||
eprintln!("[rtk: fallback failed: {}]", e);
|
||||
parse_error.exit();
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum GtCommands {
|
||||
/// Compact stack log output
|
||||
Log {
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
},
|
||||
/// Compact submit output
|
||||
Submit {
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
},
|
||||
/// Compact sync output
|
||||
Sync {
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
},
|
||||
/// Compact restack output
|
||||
Restack {
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
},
|
||||
/// Compact create output
|
||||
Create {
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
},
|
||||
/// Branch info and management
|
||||
Branch {
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
},
|
||||
/// Passthrough: git-passthrough detection or direct gt execution
|
||||
#[command(external_subcommand)]
|
||||
Other(Vec<OsString>),
|
||||
}
|
||||
|
||||
/// Split a string into shell-like tokens, respecting single and double quotes.
|
||||
/// e.g. `git log --format="%H %s"` → ["git", "log", "--format=%H %s"]
|
||||
fn shell_split(input: &str) -> Vec<String> {
|
||||
let mut tokens = Vec::new();
|
||||
let mut current = String::new();
|
||||
let mut chars = input.chars().peekable();
|
||||
let mut in_single = false;
|
||||
let mut in_double = false;
|
||||
|
||||
while let Some(c) = chars.next() {
|
||||
match c {
|
||||
'\'' if !in_double => in_single = !in_single,
|
||||
'"' if !in_single => in_double = !in_double,
|
||||
' ' | '\t' if !in_single && !in_double => {
|
||||
if !current.is_empty() {
|
||||
tokens.push(std::mem::take(&mut current));
|
||||
}
|
||||
}
|
||||
_ => current.push(c),
|
||||
}
|
||||
}
|
||||
if !current.is_empty() {
|
||||
tokens.push(current);
|
||||
}
|
||||
tokens
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
// Fire-and-forget telemetry ping (1/day, non-blocking)
|
||||
telemetry::maybe_ping();
|
||||
|
||||
// Warn if installed hook is outdated (1/day, non-blocking)
|
||||
hook_check::maybe_warn();
|
||||
|
||||
let cli = match Cli::try_parse() {
|
||||
Ok(cli) => cli,
|
||||
Err(e) => {
|
||||
@@ -1152,12 +1006,6 @@ fn main() -> Result<()> {
|
||||
}
|
||||
};
|
||||
|
||||
// Warn if installed hook is outdated/missing (1/day, non-blocking).
|
||||
// Skip for Gain — it shows its own inline hook warning.
|
||||
if !matches!(cli.command, Commands::Gain { .. }) {
|
||||
hook_check::maybe_warn();
|
||||
}
|
||||
|
||||
// Runtime integrity check for operational commands.
|
||||
// Meta commands (init, gain, verify, config, etc.) skip the check
|
||||
// because they don't go through the hook pipeline.
|
||||
@@ -1367,10 +1215,7 @@ fn main() -> Result<()> {
|
||||
)?;
|
||||
}
|
||||
PnpmCommands::Build { args } => {
|
||||
let mut build_args: Vec<String> = vec!["build".into()];
|
||||
build_args.extend(args);
|
||||
let os_args: Vec<OsString> = build_args.into_iter().map(OsString::from).collect();
|
||||
pnpm_cmd::run_passthrough(&os_args, cli.verbose)?;
|
||||
next_cmd::run(&args, cli.verbose)?;
|
||||
}
|
||||
PnpmCommands::Typecheck { args } => {
|
||||
tsc_cmd::run(&args, cli.verbose)?;
|
||||
@@ -1840,30 +1685,6 @@ fn main() -> Result<()> {
|
||||
}
|
||||
},
|
||||
|
||||
Commands::Gt { command } => match command {
|
||||
GtCommands::Log { args } => {
|
||||
gt_cmd::run_log(&args, cli.verbose)?;
|
||||
}
|
||||
GtCommands::Submit { args } => {
|
||||
gt_cmd::run_submit(&args, cli.verbose)?;
|
||||
}
|
||||
GtCommands::Sync { args } => {
|
||||
gt_cmd::run_sync(&args, cli.verbose)?;
|
||||
}
|
||||
GtCommands::Restack { args } => {
|
||||
gt_cmd::run_restack(&args, cli.verbose)?;
|
||||
}
|
||||
GtCommands::Create { args } => {
|
||||
gt_cmd::run_create(&args, cli.verbose)?;
|
||||
}
|
||||
GtCommands::Branch { args } => {
|
||||
gt_cmd::run_branch(&args, cli.verbose)?;
|
||||
}
|
||||
GtCommands::Other(args) => {
|
||||
gt_cmd::run_other(&args, cli.verbose)?;
|
||||
}
|
||||
},
|
||||
|
||||
Commands::GolangciLint { args } => {
|
||||
golangci_cmd::run(&args, cli.verbose)?;
|
||||
}
|
||||
@@ -1872,8 +1693,7 @@ fn main() -> Result<()> {
|
||||
hook_audit_cmd::run(since, cli.verbose)?;
|
||||
}
|
||||
|
||||
Commands::Rewrite { args } => {
|
||||
let cmd = args.join(" ");
|
||||
Commands::Rewrite { cmd } => {
|
||||
rewrite_cmd::run(&cmd)?;
|
||||
}
|
||||
|
||||
@@ -1890,32 +1710,17 @@ fn main() -> Result<()> {
|
||||
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
// If a single quoted arg contains spaces, split it respecting quotes (#388).
|
||||
// e.g. rtk proxy 'head -50 file.php' → cmd=head, args=["-50", "file.php"]
|
||||
// e.g. rtk proxy 'git log --format="%H %s"' → cmd=git, args=["log", "--format=%H %s"]
|
||||
let (cmd_name, cmd_args): (String, Vec<String>) = if args.len() == 1 {
|
||||
let full = args[0].to_string_lossy();
|
||||
let parts = shell_split(&full);
|
||||
if parts.len() > 1 {
|
||||
(parts[0].clone(), parts[1..].to_vec())
|
||||
} else {
|
||||
(full.into_owned(), vec![])
|
||||
}
|
||||
} else {
|
||||
(
|
||||
args[0].to_string_lossy().into_owned(),
|
||||
args[1..]
|
||||
.iter()
|
||||
.map(|s| s.to_string_lossy().into_owned())
|
||||
.collect(),
|
||||
)
|
||||
};
|
||||
let cmd_name = args[0].to_string_lossy();
|
||||
let cmd_args: Vec<String> = args[1..]
|
||||
.iter()
|
||||
.map(|s| s.to_string_lossy().into_owned())
|
||||
.collect();
|
||||
|
||||
if cli.verbose > 0 {
|
||||
eprintln!("Proxy mode: {} {}", cmd_name, cmd_args.join(" "));
|
||||
}
|
||||
|
||||
let mut child = Command::new(&cmd_name)
|
||||
let mut child = Command::new(cmd_name.as_ref())
|
||||
.args(&cmd_args)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
@@ -1998,18 +1803,8 @@ fn main() -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
Commands::Verify {
|
||||
filter,
|
||||
require_all,
|
||||
} => {
|
||||
if filter.is_some() {
|
||||
// Filter-specific mode: run only that filter's tests
|
||||
verify_cmd::run(filter, require_all)?;
|
||||
} else {
|
||||
// Default or --require-all: always run integrity check first
|
||||
integrity::run_verify(cli.verbose)?;
|
||||
verify_cmd::run(None, require_all)?;
|
||||
}
|
||||
Commands::Verify => {
|
||||
integrity::run_verify(cli.verbose)?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2065,7 +1860,6 @@ fn is_operational_command(cmd: &Commands) -> bool {
|
||||
| Commands::Pip { .. }
|
||||
| Commands::Go { .. }
|
||||
| Commands::GolangciLint { .. }
|
||||
| Commands::Gt { .. }
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2236,19 +2030,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_try_parse_git_with_dash_c_succeeds() {
|
||||
// git -C /path status is now supported via global options
|
||||
let result = Cli::try_parse_from(["rtk", "git", "-C", "/path", "status"]);
|
||||
assert!(
|
||||
result.is_ok(),
|
||||
"git -C /path status should parse successfully"
|
||||
);
|
||||
if let Ok(cli) = result {
|
||||
match cli.command {
|
||||
Commands::Git { directory, .. } => {
|
||||
assert_eq!(directory, vec!["/path"]);
|
||||
}
|
||||
_ => panic!("Expected Git command"),
|
||||
}
|
||||
}
|
||||
assert!(result.is_ok(), "git -C should parse successfully");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2314,86 +2098,4 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_shell_split_simple() {
|
||||
assert_eq!(
|
||||
shell_split("head -50 file.php"),
|
||||
vec!["head", "-50", "file.php"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_shell_split_double_quotes() {
|
||||
assert_eq!(
|
||||
shell_split(r#"git log --format="%H %s""#),
|
||||
vec!["git", "log", "--format=%H %s"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_shell_split_single_quotes() {
|
||||
assert_eq!(
|
||||
shell_split("grep -r 'hello world' ."),
|
||||
vec!["grep", "-r", "hello world", "."]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_shell_split_single_word() {
|
||||
assert_eq!(shell_split("ls"), vec!["ls"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_shell_split_empty() {
|
||||
let result: Vec<String> = shell_split("");
|
||||
assert!(result.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_clap_multi_args() {
|
||||
// This is the bug KuSh reported: `rtk rewrite ls -al` failed because
|
||||
// Clap rejected `-al` as an unknown flag. With trailing_var_arg + allow_hyphen_values,
|
||||
// multiple args are accepted and joined into a single command string.
|
||||
let cases = vec![
|
||||
vec!["rtk", "rewrite", "ls", "-al"],
|
||||
vec!["rtk", "rewrite", "git", "status"],
|
||||
vec!["rtk", "rewrite", "npm", "exec"],
|
||||
vec!["rtk", "rewrite", "cargo", "test"],
|
||||
vec!["rtk", "rewrite", "du", "-sh", "."],
|
||||
vec!["rtk", "rewrite", "head", "-50", "file.txt"],
|
||||
];
|
||||
for args in &cases {
|
||||
let result = Cli::try_parse_from(args.iter());
|
||||
assert!(
|
||||
result.is_ok(),
|
||||
"rtk rewrite {:?} should parse (was failing before trailing_var_arg fix)",
|
||||
&args[2..]
|
||||
);
|
||||
if let Ok(cli) = result {
|
||||
match cli.command {
|
||||
Commands::Rewrite { ref args } => {
|
||||
assert!(args.len() >= 2, "rewrite args should capture all tokens");
|
||||
}
|
||||
_ => panic!("expected Rewrite command"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_clap_quoted_single_arg() {
|
||||
// Quoted form: `rtk rewrite "git status"` — single arg containing spaces
|
||||
let result = Cli::try_parse_from(["rtk", "rewrite", "git status"]);
|
||||
assert!(result.is_ok());
|
||||
if let Ok(cli) = result {
|
||||
match cli.command {
|
||||
Commands::Rewrite { ref args } => {
|
||||
assert_eq!(args.len(), 1);
|
||||
assert_eq!(args[0], "git status");
|
||||
}
|
||||
_ => panic!("expected Rewrite command"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
-133
@@ -2,102 +2,13 @@ use crate::tracking;
|
||||
use anyhow::{Context, Result};
|
||||
use std::process::Command;
|
||||
|
||||
/// Known npm subcommands that should NOT get "run" injected.
|
||||
/// Shared between production code and tests to avoid drift.
|
||||
const NPM_SUBCOMMANDS: &[&str] = &[
|
||||
"install",
|
||||
"i",
|
||||
"ci",
|
||||
"uninstall",
|
||||
"remove",
|
||||
"rm",
|
||||
"update",
|
||||
"up",
|
||||
"list",
|
||||
"ls",
|
||||
"outdated",
|
||||
"init",
|
||||
"create",
|
||||
"publish",
|
||||
"pack",
|
||||
"link",
|
||||
"audit",
|
||||
"fund",
|
||||
"exec",
|
||||
"explain",
|
||||
"why",
|
||||
"search",
|
||||
"view",
|
||||
"info",
|
||||
"show",
|
||||
"config",
|
||||
"set",
|
||||
"get",
|
||||
"cache",
|
||||
"prune",
|
||||
"dedupe",
|
||||
"doctor",
|
||||
"help",
|
||||
"version",
|
||||
"prefix",
|
||||
"root",
|
||||
"bin",
|
||||
"bugs",
|
||||
"docs",
|
||||
"home",
|
||||
"repo",
|
||||
"ping",
|
||||
"whoami",
|
||||
"token",
|
||||
"profile",
|
||||
"team",
|
||||
"access",
|
||||
"owner",
|
||||
"deprecate",
|
||||
"dist-tag",
|
||||
"star",
|
||||
"stars",
|
||||
"login",
|
||||
"logout",
|
||||
"adduser",
|
||||
"unpublish",
|
||||
"pkg",
|
||||
"diff",
|
||||
"rebuild",
|
||||
"test",
|
||||
"t",
|
||||
"start",
|
||||
"stop",
|
||||
"restart",
|
||||
];
|
||||
|
||||
pub fn run(args: &[String], verbose: u8, skip_env: bool) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
let mut cmd = Command::new("npm");
|
||||
cmd.arg("run");
|
||||
|
||||
// Determine if this is "npm run <script>" or another npm subcommand (install, list, etc.)
|
||||
// Only inject "run" when args look like a script name, not a known npm subcommand.
|
||||
let first_arg = args.first().map(|s| s.as_str());
|
||||
let is_run_explicit = first_arg == Some("run");
|
||||
let is_npm_subcommand = first_arg
|
||||
.map(|a| NPM_SUBCOMMANDS.contains(&a) || a.starts_with('-'))
|
||||
.unwrap_or(false);
|
||||
|
||||
let effective_args = if is_run_explicit {
|
||||
// "rtk npm run build" → "npm run build"
|
||||
cmd.arg("run");
|
||||
&args[1..]
|
||||
} else if is_npm_subcommand {
|
||||
// "rtk npm install express" → "npm install express"
|
||||
args
|
||||
} else {
|
||||
// "rtk npm build" → "npm run build" (assume script name)
|
||||
cmd.arg("run");
|
||||
args
|
||||
};
|
||||
|
||||
for arg in effective_args {
|
||||
for arg in args {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
|
||||
@@ -106,10 +17,10 @@ pub fn run(args: &[String], verbose: u8, skip_env: bool) -> Result<()> {
|
||||
}
|
||||
|
||||
if verbose > 0 {
|
||||
eprintln!("Running: npm {}", args.join(" "));
|
||||
eprintln!("Running: npm run {}", args.join(" "));
|
||||
}
|
||||
|
||||
let output = cmd.output().context("Failed to run npm")?;
|
||||
let output = cmd.output().context("Failed to run npm run")?;
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let raw = format!("{}\n{}", stdout, stderr);
|
||||
@@ -118,8 +29,8 @@ pub fn run(args: &[String], verbose: u8, skip_env: bool) -> Result<()> {
|
||||
println!("{}", filtered);
|
||||
|
||||
timer.track(
|
||||
&format!("npm {}", args.join(" ")),
|
||||
&format!("rtk npm {}", args.join(" ")),
|
||||
&format!("npm run {}", args.join(" ")),
|
||||
&format!("rtk npm run {}", args.join(" ")),
|
||||
&raw,
|
||||
&filtered,
|
||||
);
|
||||
@@ -189,44 +100,6 @@ npm notice
|
||||
assert!(result.contains("Build completed"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_npm_subcommand_routing() {
|
||||
// Uses the shared NPM_SUBCOMMANDS constant — no drift between prod and test
|
||||
fn needs_run_injection(args: &[&str]) -> bool {
|
||||
let first = args.first().copied();
|
||||
let is_run_explicit = first == Some("run");
|
||||
let is_subcommand = first
|
||||
.map(|a| NPM_SUBCOMMANDS.contains(&a) || a.starts_with('-'))
|
||||
.unwrap_or(false);
|
||||
!is_run_explicit && !is_subcommand
|
||||
}
|
||||
|
||||
// Known subcommands should NOT get "run" injected
|
||||
for subcmd in NPM_SUBCOMMANDS {
|
||||
assert!(
|
||||
!needs_run_injection(&[subcmd]),
|
||||
"'npm {}' should NOT inject 'run'",
|
||||
subcmd
|
||||
);
|
||||
}
|
||||
|
||||
// Script names SHOULD get "run" injected
|
||||
for script in &["build", "dev", "lint", "typecheck", "deploy"] {
|
||||
assert!(
|
||||
needs_run_injection(&[script]),
|
||||
"'npm {}' SHOULD inject 'run'",
|
||||
script
|
||||
);
|
||||
}
|
||||
|
||||
// Flags should NOT get "run" injected
|
||||
assert!(!needs_run_injection(&["--version"]));
|
||||
assert!(!needs_run_injection(&["-h"]));
|
||||
|
||||
// Explicit "run" should NOT inject another "run"
|
||||
assert!(!needs_run_injection(&["run", "build"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_npm_output_empty() {
|
||||
let output = "\n\n\n";
|
||||
|
||||
+1
-1
@@ -37,7 +37,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_run_unsupported_returns_none() {
|
||||
assert!(registry::rewrite_command("htop", &[]).is_none());
|
||||
assert!(registry::rewrite_command("terraform plan", &[]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+7
-111
@@ -52,23 +52,18 @@ fn send_ping() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let version = env!("CARGO_PKG_VERSION").to_string();
|
||||
let os = std::env::consts::OS.to_string();
|
||||
let arch = std::env::consts::ARCH.to_string();
|
||||
let install_method = detect_install_method();
|
||||
|
||||
// Get stats from tracking DB
|
||||
let (commands_24h, top_commands, savings_pct, tokens_saved_24h, tokens_saved_total) =
|
||||
get_stats();
|
||||
let (commands_24h, top_commands, savings_pct) = get_stats();
|
||||
|
||||
let payload = serde_json::json!({
|
||||
"device_hash": device_hash,
|
||||
"version": version,
|
||||
"os": os,
|
||||
"arch": arch,
|
||||
"install_method": install_method,
|
||||
"commands_24h": commands_24h,
|
||||
"top_commands": top_commands,
|
||||
"savings_pct": savings_pct,
|
||||
"tokens_saved_24h": tokens_saved_24h,
|
||||
"tokens_saved_total": tokens_saved_total,
|
||||
});
|
||||
|
||||
let mut req = ureq::post(url).set("Content-Type", "application/json");
|
||||
@@ -99,58 +94,22 @@ fn generate_device_hash() -> String {
|
||||
format!("{:x}", hasher.finalize())
|
||||
}
|
||||
|
||||
fn get_stats() -> (i64, Vec<String>, Option<f64>, i64, i64) {
|
||||
fn get_stats() -> (i64, Vec<String>, Option<f64>) {
|
||||
let tracker = match tracking::Tracker::new() {
|
||||
Ok(t) => t,
|
||||
Err(_) => return (0, vec![], None, 0, 0),
|
||||
Err(_) => return (0, vec![], None),
|
||||
};
|
||||
|
||||
let since_24h = chrono::Utc::now() - chrono::Duration::hours(24);
|
||||
|
||||
// Get 24h command count and top commands from tracking DB
|
||||
let commands_24h = tracker.count_commands_since(since_24h).unwrap_or(0);
|
||||
let commands_24h = tracker
|
||||
.count_commands_since(chrono::Utc::now() - chrono::Duration::hours(24))
|
||||
.unwrap_or(0);
|
||||
|
||||
let top_commands = tracker.top_commands(5).unwrap_or_default();
|
||||
|
||||
let savings_pct = tracker.overall_savings_pct().ok();
|
||||
|
||||
let tokens_saved_24h = tracker.tokens_saved_24h(since_24h).unwrap_or(0);
|
||||
|
||||
let tokens_saved_total = tracker.total_tokens_saved().unwrap_or(0);
|
||||
|
||||
(
|
||||
commands_24h,
|
||||
top_commands,
|
||||
savings_pct,
|
||||
tokens_saved_24h,
|
||||
tokens_saved_total,
|
||||
)
|
||||
}
|
||||
|
||||
fn detect_install_method() -> &'static str {
|
||||
let exe = match std::env::current_exe() {
|
||||
Ok(p) => p,
|
||||
Err(_) => return "unknown",
|
||||
};
|
||||
let real_path = std::fs::canonicalize(&exe)
|
||||
.unwrap_or(exe)
|
||||
.to_string_lossy()
|
||||
.to_string();
|
||||
install_method_from_path(&real_path)
|
||||
}
|
||||
|
||||
fn install_method_from_path(path: &str) -> &'static str {
|
||||
if path.contains("/Cellar/rtk/") || path.contains("/homebrew/") {
|
||||
"homebrew"
|
||||
} else if path.contains("/.cargo/bin/") || path.contains("\\.cargo\\bin\\") {
|
||||
"cargo"
|
||||
} else if path.contains("/.local/bin/") || path.contains("\\.local\\bin\\") {
|
||||
"script"
|
||||
} else if path.contains("/nix/store/") {
|
||||
"nix"
|
||||
} else {
|
||||
"other"
|
||||
}
|
||||
(commands_24h, top_commands, savings_pct)
|
||||
}
|
||||
|
||||
fn telemetry_marker_path() -> PathBuf {
|
||||
@@ -182,67 +141,4 @@ mod tests {
|
||||
let path = telemetry_marker_path();
|
||||
assert!(path.to_string_lossy().contains("rtk"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_install_method_unix_paths() {
|
||||
assert_eq!(
|
||||
install_method_from_path("/opt/homebrew/Cellar/rtk/0.28.0/bin/rtk"),
|
||||
"homebrew"
|
||||
);
|
||||
assert_eq!(
|
||||
install_method_from_path("/usr/local/homebrew/bin/rtk"),
|
||||
"homebrew"
|
||||
);
|
||||
assert_eq!(
|
||||
install_method_from_path("/home/user/.cargo/bin/rtk"),
|
||||
"cargo"
|
||||
);
|
||||
assert_eq!(
|
||||
install_method_from_path("/home/user/.local/bin/rtk"),
|
||||
"script"
|
||||
);
|
||||
assert_eq!(
|
||||
install_method_from_path("/nix/store/abc123-rtk/bin/rtk"),
|
||||
"nix"
|
||||
);
|
||||
assert_eq!(install_method_from_path("/usr/bin/rtk"), "other");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_install_method_windows_paths() {
|
||||
assert_eq!(
|
||||
install_method_from_path("C:\\Users\\user\\.cargo\\bin\\rtk.exe"),
|
||||
"cargo"
|
||||
);
|
||||
assert_eq!(
|
||||
install_method_from_path("C:\\Users\\user\\.local\\bin\\rtk.exe"),
|
||||
"script"
|
||||
);
|
||||
assert_eq!(
|
||||
install_method_from_path("C:\\Program Files\\rtk\\rtk.exe"),
|
||||
"other"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_detect_install_method_returns_known_value() {
|
||||
let method = detect_install_method();
|
||||
assert!(
|
||||
["homebrew", "cargo", "script", "nix", "other", "unknown"].contains(&method),
|
||||
"Unexpected install method: {}",
|
||||
method
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_stats_returns_tuple() {
|
||||
let (cmds, top, pct, saved_24h, saved_total) = get_stats();
|
||||
assert!(cmds >= 0);
|
||||
assert!(top.len() <= 5);
|
||||
assert!(saved_24h >= 0);
|
||||
assert!(saved_total >= 0);
|
||||
if let Some(p) = pct {
|
||||
assert!((0.0..=100.0).contains(&p));
|
||||
}
|
||||
}
|
||||
}
|
||||
-1655
File diff suppressed because it is too large.
Load diff
@@ -925,27 +925,6 @@ impl Tracker {
|
||||
Ok(0.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Get total tokens saved across all tracked commands (for telemetry).
|
||||
pub fn total_tokens_saved(&self) -> Result<i64> {
|
||||
let saved: i64 = self.conn.query_row(
|
||||
"SELECT COALESCE(SUM(saved_tokens), 0) FROM commands",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
Ok(saved)
|
||||
}
|
||||
|
||||
/// Get tokens saved in the last 24 hours (for telemetry).
|
||||
pub fn tokens_saved_24h(&self, since: chrono::DateTime<chrono::Utc>) -> Result<i64> {
|
||||
let ts = since.format("%Y-%m-%dT%H:%M:%S").to_string();
|
||||
let saved: i64 = self.conn.query_row(
|
||||
"SELECT COALESCE(SUM(saved_tokens), 0) FROM commands WHERE timestamp >= ?1",
|
||||
params![ts],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
Ok(saved)
|
||||
}
|
||||
}
|
||||
|
||||
fn get_db_path() -> Result<PathBuf> {
|
||||
|
||||
+14
-14
@@ -9,11 +9,11 @@ use anyhow::{Context, Result};
|
||||
use regex::Regex;
|
||||
use std::process::Command;
|
||||
|
||||
/// Truncates a string to `max_len` characters, appending `...` if needed.
|
||||
/// Tronque une chaîne à `max_len` caractères avec "..." si nécessaire.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `s` - The string to truncate
|
||||
/// * `max_len` - Maximum length before truncation (minimum 3 to include "...")
|
||||
/// * `s` - La chaîne à tronquer
|
||||
/// * `max_len` - Longueur maximale avant troncature (minimum 3 pour inclure "...")
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
@@ -33,10 +33,10 @@ pub fn truncate(s: &str, max_len: usize) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Strips ANSI escape codes (colors, styles) from a string.
|
||||
/// Supprime les codes ANSI d'une chaîne (couleurs, styles).
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `text` - Text potentially containing ANSI escape codes
|
||||
/// * `text` - Texte contenant potentiellement des codes ANSI
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
@@ -51,11 +51,11 @@ pub fn strip_ansi(text: &str) -> String {
|
||||
ANSI_RE.replace_all(text, "").to_string()
|
||||
}
|
||||
|
||||
/// Executes a command and returns cleaned stdout/stderr.
|
||||
/// Exécute une commande et retourne stdout/stderr nettoyés.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `cmd` - Command to execute (e.g. "eslint")
|
||||
/// * `args` - Command arguments
|
||||
/// * `cmd` - Commande à exécuter (ex: "eslint")
|
||||
/// * `args` - Arguments de la commande
|
||||
///
|
||||
/// # Returns
|
||||
/// `(stdout: String, stderr: String, exit_code: i32)`
|
||||
@@ -80,13 +80,13 @@ pub fn execute_command(cmd: &str, args: &[&str]) -> Result<(String, String, i32)
|
||||
Ok((stdout, stderr, exit_code))
|
||||
}
|
||||
|
||||
/// Formats a token count with K/M suffixes for readability.
|
||||
/// Formate un nombre de tokens avec suffixes K/M pour lisibilité.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `n` - Token count
|
||||
/// * `n` - Nombre de tokens
|
||||
///
|
||||
/// # Returns
|
||||
/// Formatted string (e.g. "1.2M", "59.2K", "694")
|
||||
/// String formaté (ex: "1.2M", "59.2K", "694")
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
@@ -105,13 +105,13 @@ pub fn format_tokens(n: usize) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Formats a USD amount with adaptive precision.
|
||||
/// Formate un montant USD avec précision adaptée.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `amount` - Amount in dollars
|
||||
/// * `amount` - Montant en dollars
|
||||
///
|
||||
/// # Returns
|
||||
/// Formatted string with $ prefix
|
||||
/// String formaté avec $ prefix
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
use anyhow::Result;
|
||||
|
||||
use crate::toml_filter;
|
||||
|
||||
/// Run TOML filter inline tests.
|
||||
///
|
||||
/// - `filter`: if `Some`, only run tests for that filter name
|
||||
/// - `require_all`: fail if any filter has no inline tests
|
||||
pub fn run(filter: Option<String>, require_all: bool) -> Result<()> {
|
||||
let results = toml_filter::run_filter_tests(filter.as_deref());
|
||||
|
||||
let total = results.outcomes.len();
|
||||
let passed = results.outcomes.iter().filter(|o| o.passed).count();
|
||||
let failed = total - passed;
|
||||
|
||||
// Print failures with details
|
||||
for outcome in &results.outcomes {
|
||||
if !outcome.passed {
|
||||
eprintln!(
|
||||
"FAIL [{}] {}\n expected: {:?}\n actual: {:?}",
|
||||
outcome.filter_name, outcome.test_name, outcome.expected, outcome.actual
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if total == 0 {
|
||||
println!("No inline tests found.");
|
||||
} else {
|
||||
println!("{}/{} tests passed", passed, total);
|
||||
}
|
||||
|
||||
if require_all && !results.filters_without_tests.is_empty() {
|
||||
for name in &results.filters_without_tests {
|
||||
eprintln!("MISSING tests for filter: {}", name);
|
||||
}
|
||||
anyhow::bail!(
|
||||
"{} filter(s) have no inline tests (use --require-all in CI)",
|
||||
results.filters_without_tests.len()
|
||||
);
|
||||
}
|
||||
|
||||
if failed > 0 {
|
||||
anyhow::bail!("{} test(s) failed", failed);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user