Compare commits

...
Author SHA1 Message Date
github-actions[bot] aef823c8e6 chore(master): release 0.28.1 (#466)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-10 18:13:21 +01:00
patrick szymkowiak 0c5cde9ec2 fix: restore lost telemetry install_method enrichment (#469)
Re-add detect_install_method() and install_method_from_path() with
Windows path support that were lost during develop→master rebase.
The install_method field (homebrew/cargo/script/nix/other) is now
included in telemetry pings again.

Signed-off-by: Patrick <patrick@rtk-ai.app>
Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-03-10 18:11:01 +01:00
patrick szymkowiakandaesoft 7d76af84b9 fix: 4 critical bugs + telemetry enrichment (#462)
* fix(cicd): Add security check on dev branch PR

add security check cicd on dev branch PR

Signed-off-by: aesoft <43991222+aeppling@users.noreply.github.com>

* fix: enrich telemetry with install_method and token savings

- Add install_method detection (homebrew/cargo/script/nix/other)
- Add tokens_saved_24h and tokens_saved_total to payload
- Add Tracker::total_tokens_saved() and Tracker::tokens_saved_24h() methods
- Point telemetry to new dedicated rtk-telemetry service

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* fix: detect install method on Windows paths

Add backslash variants for .cargo\bin and .local\bin detection

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* fix: enrich telemetry with install_method and token savings (#432)

- Add install_method detection (homebrew/cargo/script/nix/other)
- Add tokens_saved_24h and tokens_saved_total to payload
- Add Tracker::total_tokens_saved() and Tracker::tokens_saved_24h() methods
- Point telemetry to new dedicated rtk-telemetry service

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* fix: 4 critical bugs — git exit code, jq warning, npm run doubling, pnpm build filter (#458)

* fix: propagate exit code 128 when rtk git status runs outside a repo (#435)

Previously printed "Not a git repository" to stdout and returned exit 0.
Now prints to stderr and exits with git's actual exit code (128).

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* fix: warn when jq is not installed instead of silent exit (#430)

Hook now prints a warning to stderr before exiting cleanly,
so users know the rewrite pipeline is not functioning.

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* fix: strip leading 'run' arg to prevent npm run run doubling (#438)

When user types 'rtk npm run build', args contain ["run", "build"].
Since npm_cmd always prepends 'run', this caused 'npm run run build'.
Now strips the leading 'run' from args if present.

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* fix: route pnpm build through generic passthrough instead of Next.js filter (#454)

pnpm build was hardcoded to next_cmd::run which misparses Vite/other
framework output as errors. Now uses generic passthrough.

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* docs: bump README version to 0.28.0

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

---------

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* fix: warn when rtk binary is not in PATH instead of silent exit (#430) (#465)

Applies the same fix as jq — all silent exits now warn on stderr.

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

---------

Signed-off-by: aesoft <43991222+aeppling@users.noreply.github.com>
Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
Co-authored-by: aesoft <43991222+aeppling@users.noreply.github.com>
2026-03-10 16:46:54 +01:00
github-actions[bot] b9cb238144 chore(master): release 0.28.0 (#378)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-10 11:46:09 +01:00
Florian BRUNIAUXandClaude Sonnet 4.6 b71a8d24e2 feat: TOML Part 3 — 15 additional built-in filters (ping, rsync, dotnet, swift, shellcheck, hadolint, poetry, composer, brew, df, ps, systemctl, yamllint, markdownlint, uv) (#386)
* docs: bump version refs to 0.27.1, fix module count to 59

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(filters): split monolithic builtin_filters.toml into 28 individual files

Replace the 848-line src/builtin_filters.toml monolith with individual
files under src/filters/<name>.toml (1 filter + tests per file).

Files are concatenated alphabetically by build.rs at compile time into
OUT_DIR/builtin_filters.toml, then embedded via a BUILTIN_TOML constant
in toml_filter.rs. The build step validates TOML syntax and detects
duplicate filter names across files.

Benefits:
- Zero merge conflicts when multiple PRs add filters (different files)
- Clear PR diffs: "+1 file of 30 lines" vs "+30 lines in 850-line file"
- Easy onboarding: copy any .toml, rename, edit 3 fields — done
- Build-time TOML validation catches syntax errors before tests run

Changes:
- build.rs (new): concat + validate src/filters/*.toml
- Cargo.toml: add [build-dependencies] toml = "0.8"
- src/filters/*.toml (28 files): split from monolith
- src/filters/README.md (new): contributor guide
- src/toml_filter.rs: BUILTIN_TOML const + 5 include_str replacements
- src/builtin_filters.toml: deleted

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(filters): add 15 TOML filters (ping, rsync, dotnet, swift, shellcheck, hadolint, poetry, composer, brew, df, ps, systemctl, yamllint, markdownlint, uv)

Tier 1 (high value):
- ping: strip per-packet lines, tail_lines=4 keeps summary only (70%+)
- rsync: match_output on "total size is" → "ok (synced)" (80%+)
- dotnet-build: match_output on "Build succeeded" → "ok (build succeeded)" (70%+)
- swift-build: match_output on "Build complete!" → "ok (build complete)" (70%+)
- shellcheck: strip blank lines + caret indicator lines, max_lines=50 (60%+)
- hadolint: strip blank lines, truncate_lines_at=120, max_lines=40 (60%+)
- poetry-install: strip downloads, match_output on "No dependencies to install" (75%+)
- composer-install: strip downloads, match_output on "Nothing to install" (75%+)
- brew-install: strip Downloading/Pouring, match_output on "already installed" (70%+)

Tier 2 (medium value):
- df: truncate_lines_at=80, max_lines=20 (60%+)
- ps-aux: truncate_lines_at=120, max_lines=30 (60%+)
- systemctl-status: strip blank lines, max_lines=20 (65%+)
- yamllint: strip blank lines, max_lines=50, truncate_lines_at=120 (60%+)
- markdownlint: strip blank lines, max_lines=50, truncate_lines_at=120 (60%+)
- uv-sync: strip downloads, match_output on "Audited"/"Resolved" (70%+)

Updates test guards: count 29→44, expected list +15 names, concat test 30→45.
All 90 inline TOML tests pass. 720 unit tests pass.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(filters): address PR #386 code review (P1 + P2 items)

P1-2: rsync.toml — remove dead strip rule "^total size is \d"
  match_output fires at stage 3, strip at stage 4 — the rule was
  unreachable on success and removed a useful line on error paths.

P2-1: ps-aux.toml renamed to ps.toml, match_command ^ps\b → ^ps(\s|$)
  Prevents false matches on pstree, psql, pstack. Filter name and
  test sections updated from ps-aux to ps. Guard list updated.

P2-2: df.toml match_command ^df\b → ^df(\s|$)
  Prevents false matches on dfs, dfx.

P2-4: shellcheck.toml — keep caret indicator lines (^-- SC...)
  Stripping them lost the exact character position of the error.
  Only blank lines are now stripped.

P2-7: swift-build.toml — remove dead strip rule "^Build complete!"
  match_output short-circuits before strip runs on success paths.
  The rule was unreachable and confusing.

All 90 inline tests pass. 720 unit tests pass.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: address PR #386 code review — 4 filter fixes

- uv-sync: remove Resolved short-circuit (fires before package list)
- dotnet-build: short-circuit only on 0 warnings + 0 errors (not on
  any "Build succeeded" — catches builds with warnings too)
- poetry-install: support Poetry 2.x bullet syntax (• vs -) and
  "No changes." message; add Poetry 2.x test
- ping: add Windows format support (Pinging + Reply from patterns);
  add Windows test

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(changelog): document round 2 fixes (PR #351 + #386)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: rebase on updated PR #351 — remove 7 dead filters re-added by rebase

Rebase on feat/toml-dsl-pr2 (post-PR-#349 fixes) caused the refactor
commit to re-add dead filters that PR #351 had already removed:
cargo-run, docker-compose-ps, docker-inspect, git-checkout,
git-merge, git-remote, pnpm-build.

These 7 files are removed to maintain the expected 36 filter count.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(dsl): add 'unless' to match_output — prevent short-circuit when errors present

Fixes two match_output bugs where success short-circuit fires before
strip_lines_matching can surface errors in the full output blob.

Changes:
- Add optional `unless` field to MatchOutputRule (serde default = None)
- Compile `unless` into Option<Regex> in CompiledMatchOutputRule
- In apply_filter stage 3: if `unless` matches the blob, skip the rule
  and continue to the next match_output rule (or fall through to the pipeline)
- rsync.toml: add `unless = "error|failed|No such file"` to the
  "total size is" rule; add test verifying errors are not swallowed
- swift-build.toml: add `unless = "warning:|error:"` to the
  "Build complete!" rule; add test verifying warnings are not swallowed
- CONTRIBUTING.md: document match_output[].unless in the field reference table
- Unit tests: 5 new tests covering unless blocks/allows/falls-through/
  no-regression/invalid-regex

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: fix README version string 0.27.1 → 0.27.2 after rebase

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: fix version 0.27.1→0.27.2 and module count 59→60 in ARCHITECTURE.md + CLAUDE.md

Version strings and module count were stale after rebase onto
updated feat/toml-dsl-pr2. validate-docs.sh now passes clean.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-10 11:09:20 +01:00
Florian BRUNIAUXandClaude Sonnet 4.6 926e6a0dd4 feat: TOML Part 2 — user-global config, shadow warning, rtk init templates, 4 new built-in filters (#351)
* docs: update module count to 58 (toml_filter + verify_cmd)

* docs: bump version refs to 0.27.1, fix module count to 59

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat: TOML DSL PR 2 — user-global config, shadow warning, init templates, 4 new filters

- toml_filter: add ~/.config/rtk/filters.toml (priority 2, between project and built-in)
- toml_filter: shadow warning when match_command overlaps a Rust-handled command
- init: rtk init generates .rtk/filters.toml template (local) and ~/.config/rtk/filters.toml (global)
- builtin_filters: add pre-commit, helm, gcloud, ansible-playbook (46/46 inline tests)
- README: add "Custom Filters" section with lookup table, primitives, examples, built-in list

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(filters): add quarto-render, pnpm-build, trunk-build from rtk discover data (52/52 tests)

* feat(filters): add docker-inspect, sops, docker-compose-ps built-in filters

Resolves issues #279, #277, #276 as TOML-native filters (no Rust required).

- docker-inspect: strip_ansi + truncate_lines_at=120 + max_lines=60
- sops: strip_ansi + strip_lines_matching blank lines + max_lines=40
- docker-compose-ps: strip_ansi + truncate_lines_at=120 + max_lines=40

6 inline tests added (2 per filter), all passing.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(filters): split monolithic builtin_filters.toml into 28 individual files

Replace the 848-line src/builtin_filters.toml monolith with individual
files under src/filters/<name>.toml (1 filter + tests per file).

Files are concatenated alphabetically by build.rs at compile time into
OUT_DIR/builtin_filters.toml, then embedded via a BUILTIN_TOML constant
in toml_filter.rs. The build step validates TOML syntax and detects
duplicate filter names across files.

Benefits:
- Zero merge conflicts when multiple PRs add filters (different files)
- Clear PR diffs: "+1 file of 30 lines" vs "+30 lines in 850-line file"
- Easy onboarding: copy any .toml, rename, edit 3 fields — done
- Build-time TOML validation catches syntax errors before tests run

Changes:
- build.rs (new): concat + validate src/filters/*.toml
- Cargo.toml: add [build-dependencies] toml = "0.8"
- src/filters/*.toml (28 files): split from monolith
- src/filters/README.md (new): contributor guide
- src/toml_filter.rs: BUILTIN_TOML const + 5 include_str replacements
- src/builtin_filters.toml: deleted

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test(filters): add 5 new unit tests for multi-file architecture + wget filter

Unit tests added (toml_filter.rs):
- test_builtin_toml_has_schema_version: ensures build.rs injects schema_version
- test_builtin_all_expected_filters_present: guards against accidental file deletion
- test_builtin_filter_count: exact count check (fails if filter added/removed without update)
- test_builtin_all_filters_have_inline_tests: prevents shipping filters with no tests
- test_new_filter_discoverable_after_concat: simulates build.rs concat, verifies lookup

New built-in filter:
- src/filters/wget.toml: compact wget download output (strips connection/resolution
  noise, short-circuits on 'saved [' to 'ok (downloaded)', 2 inline tests)

Test results: 661/661 unit tests, 60/60 inline TOML filter tests

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: add filter-workflow.md with Mermaid diagrams

Build pipeline + runtime lookup priority, both as Mermaid flowcharts.
Shows the full path from src/filters/*.toml to binary to execution.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: remove dead TOML filters — wget, git-checkout, git-merge, git-remote, cargo-run

These filters were never reachable: Clap routes rtk git/cargo commands
to their dedicated Rust modules before run_fallback is called. The TOML
engine only fires for unknown commands. Shipping dead filters gives false
confidence (inline tests pass, but filters never activate in production).

Also fixes P1-1 from the PR #386 review: wget was in RUST_HANDLED_COMMANDS
and the shadow warning fired at compile time but did not block the build.

Removed: cargo-run.toml, git-checkout.toml, git-merge.toml,
         git-remote.toml, wget.toml

Updated test guards: count 29→24, expected list -5 names,
concat test 30→25.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: remove 3 dead TOML filters + update guards (PR #351)

docker-inspect, docker-compose-ps, and pnpm-build are handled by
container.rs and pnpm_cmd.rs before run_fallback is reached — their
TOML filters never fire. Remove the files to avoid false documentation.

Update toml_filter.rs guards: expected list -3 names, count 24→21,
concat test 25→22. Update CONTRIBUTING.md example count to match.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: rebase on PR #349 — apply regex anchors, make on_empty, build.rs clippy, docs macOS path

- Add (\\s|$) word-boundary anchors to 6 tofu/mix match_command regexes
  (tofu-plan, tofu-init, tofu-validate, tofu-fmt, mix-format, mix-compile)
- Add on_empty = "make: ok" to make.toml + update existing empty-output test
- Fix build.rs clippy: map_or(false, ...) → is_some_and(..)
- Add macOS alt path note to filter-workflow.md Mermaid diagram

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-10 11:02:18 +01:00
Florian BRUNIAUXandClaude Sonnet 4.6 adda2537be feat: TOML Part 1 — filter DSL engine + 14 built-in filters (#349)
* feat: TOML filter DSL + 14 built-in filters (#299)

Add a declarative TOML-based filter engine for zero-Rust command
filtering, plus 14 built-in filters targeting open issues.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: update module count to 58 (toml_filter + verify_cmd)

* docs(changelog): add TOML DSL + 14 built-in filters entry

* chore: ignore worktrees directory

* fix: address PR #349 code review (P1 + P2)

P1-1: println! — add trailing newline to TOML-filtered output
  print!("{}", filtered) → println!("{}", filtered). Fixes broken
  pipe compatibility (rtk make all | wc -l returned 0 for 1 line).

P1-2: remove dead filters — git-checkout, git-remote, git-merge, cargo-run
  Clap routes these commands to git.rs/cargo_cmd.rs before run_fallback
  is reached, so these TOML filters never activate. Tests passed but
  gave false confidence. Removed filter definitions and test sections.

P1-3: map_or instead of is_none_or (MSRV compatibility)
  is_none_or requires Rust 1.82+. Replaced with map_or(true, ...) which
  compiles on all supported toolchain versions.

P1-4: print tee hint for TOML-filtered commands on failure
  let _ = tee::tee_and_hint(...) silently discarded the hint path.
  Now follows the same pattern as runner.rs: if let Some(hint) = ... {
  println!("{}", hint); }. LLMs can now find the full output file.

P1-5: --require-all now runs integrity check
  Previously, `rtk verify --require-all` branched away from
  integrity::run_verify(). Now: filter-specific mode (--filter foo)
  skips integrity, but default and --require-all always run it first.

P2-1: RTK_NO_TOML checks value not presence
  .is_ok() matched any value including RTK_NO_TOML=0.
  Replaced with .ok().as_deref() == Some("1").

P2-5: terraform-plan regex — add word boundary after "plan"
  ^terraform\s+plan → ^terraform\s+plan(\s|$) to prevent matching
  "terraform planning" or other plan-prefixed subcommands.

P2-6: iptables regex — \b → (\s|$)
  ^iptables\b matched iptables-save and iptables-restore (\b fires at
  hyphen). Fixed to ^iptables(\s|$).

All 715 tests pass.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: add word-boundary anchors to 6 tofu/mix match_command regexes

Prevents overmatch on subcommands (e.g. `tofu planet` or `mix formats`).
Mirrors the same `(\s|$)` pattern already used by terraform-plan.

Fixes: tofu-plan, tofu-init, tofu-validate, tofu-fmt, mix-format, mix-compile

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(changelog): add round 2 fix for tofu/mix regex overmatch (PR #349)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: address PR #349 round 3 review (BUG-1 + BUG-2 + P2 items)

- println! trailing newline on TOML-filtered output (BUG-1)
- RTK_NO_TOML check presence→value (as_deref==Ok("1")) (BUG-2)
- make filter: add on_empty="make: ok" + test (P2-3)
- TOML lookup: use basename of args[0] for absolute path support (P2-8)
- utils.rs: translate French docstrings to English (P2-9)
- main.rs: single error message on command-not-found, exit(127) (NEW)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: bump version refs to 0.27.2 and module count to 60

Fixes pre-push validation: README, CLAUDE.md, ARCHITECTURE.md were
still referencing 0.27.1 (Cargo.toml is 0.27.2). Also updates module
count from 59 to 60 to match main.rs (toml_filter + verify_cmd).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-10 10:24:07 +01:00
patrick szymkowiak b11fb00cde docs: add comprehensive functional and user guide documentation (#389)
- Create docs/FEATURES.md with all 45+ commands documented (syntax, options, examples, token savings)
- Create docs/GUIDE.md with getting started, workflows per language, Claude Code integration, FAQ, troubleshooting
2026-03-06 19:00:50 +01:00
aesoft 15f3befccf Merge pull request #382 from rtk-ai/hotfix-readme-discord-link
Update README.md
2026-03-06 15:22:19 +01:00
aesoft e194c7cd4b Update README_zh.md 2026-03-06 15:20:18 +01:00
aesoft e0f503a556 Update README_ko.md 2026-03-06 15:20:06 +01:00
aesoft 9deaf00f86 Update README_ja.md 2026-03-06 15:19:52 +01:00
aesoft 4f8b9f02fa Update README_fr.md 2026-03-06 15:19:40 +01:00
aesoft 55ac640b8e Update README_es.md 2026-03-06 15:19:27 +01:00
aesoft 949104d502 Update README.md 2026-03-06 15:18:59 +01:00
aesoft ae03bb4565 Update README.md 2026-03-06 15:16:21 +01:00
aesoft 30ac4bb4ae Update README_zh.md 2026-03-06 15:14:57 +01:00
aesoft dc8d325e51 Update README_ko.md 2026-03-06 15:14:21 +01:00
aesoft 530b42fa02 Update README_ja.md 2026-03-06 15:14:10 +01:00
aesoft fa05110145 Update README_fr.md 2026-03-06 15:13:59 +01:00
aesoft a69e8c4a66 Update README_es.md 2026-03-06 15:13:49 +01:00
aesoft a097d36f51 Update README.md 2026-03-06 15:13:26 +01:00
aesoft 5816e95d21 Update README.md 2026-03-06 15:12:00 +01:00
aesoft 560ad44b04 Merge pull request #335 from rtk-ai/doc/add-contributing
docs: add contributing.md guide
2026-03-06 14:39:47 +01:00
aesoft f50ff31cb7 Update CONTRIBUTING.md 2026-03-06 14:33:18 +01:00
aesoft e6ce6e6a14 Merge branch 'master' into doc/add-contributing 2026-03-06 14:31:21 +01:00
Charles Vien 7fbc4ef4b5 feat(gt): add Graphite CLI support (#290) 2026-03-06 13:59:39 +01:00
patrick szymkowiak 6099bb8d25 ci: add Discord notification on release (#375)
Sends an embed with version, release notes, and link to the GitHub
release page via the RTK_DISCORD_RELEASE webhook secret.
2026-03-06 13:05:46 +01:00
github-actions[bot] 34b2474d4c chore(master): release 0.27.2 (#365)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-06 12:54:04 +01:00
Florian BRUNIAUXandClaude Sonnet 4.6 e356c1280d fix: reduce gh diff / git diff / gh api truncation (#354) (#370)
* fix: reduce gh diff / git diff / gh api truncation (#354)

- compact_diff: increase max_hunk_lines 10→30, max_lines default 100→500
- gh api: passthrough instead of JSON→schema destruction
- gh pr diff: add --no-compact flag + increase limit to 500
- gh pr view: passthrough when --json/--jq/--web provided by user

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: update version reference 0.26.0→0.27.1 in README

* docs: update version reference 0.26.0→0.27.1 in CLAUDE.md

* docs: update version reference 0.26.0→0.27.1 in ARCHITECTURE.md

* fix: resolve compile errors in gh_cmd.rs (type mismatches)

* fix: use explicit .iter() in pr_diff loop (avoids &&[String] ambiguity)

* docs: fix version reference 0.27.x→0.27.1 in README

* fix: remove shadowed extra_args in view_pr (was &&[String] not iterator)

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-06 12:36:42 +01:00
patrick szymkowiak a22fe7b31f docs: revamp README with logo, badges, and structure cleanup (#371)
* docs: revamp README with logo, badges, and cleaner structure

- Add centered logo (og-image) and tagline
- Add badges: CI, release version, license, Discord, Homebrew
- Add language links placeholder (fr, zh, ja, ko, es)
- Fix Linux binary filename (gnu -> musl) — fixes #323
- Put Homebrew as recommended install method
- Simplify and reorganize all sections (871 -> ~360 lines)
- Add Discord invite link
- Remove verbose troubleshooting (link to TROUBLESHOOTING.md instead)
- Remove detailed security review section (link to SECURITY.md)

* docs: add translated READMEs (fr, zh, ja, ko, es)

Add localized README files linked from the main README language selector:
- README_fr.md (French)
- README_zh.md (Chinese)
- README_ja.md (Japanese)
- README_ko.md (Korean)
- README_es.md (Spanish)

Each translation includes: installation, quick start, commands overview,
how it works diagram, and links to documentation.

* docs: use rtk-ai org avatar as logo in all READMEs
2026-03-06 12:01:06 +01:00
aesoft 33cc14e780 Create dco-check.yaml 2026-03-05 17:41:11 +01:00
aesoft 171e63002f Update CONTRIBUTING.md 2026-03-05 17:31:09 +01:00
aesoft 1dff09df62 Update CONTRIBUTING.md 2026-03-05 17:15:30 +01:00
aesoft 9c3162a968 Update CONTRIBUTING.md 2026-03-05 17:15:11 +01:00
aesoft d318006d77 Update README.md 2026-03-05 15:24:51 +01:00
aesoft 18e7e085f5 Update CONTRIBUTING.md 2026-03-05 15:23:05 +01:00
aesoft 7bd27b98bd Update README.md 2026-03-05 15:22:13 +01:00
aesoft 3f5cdb4334 Update README.md 2026-03-05 15:21:46 +01:00
aesoft f2f17bb4b4 Update CONTRIBUTING.md 2026-03-05 15:12:51 +01:00
aesoft 93f8c09485 Add files via upload 2026-03-05 15:09:44 +01:00
68 changed files with 7201 additions and 811 deletions

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
name: DCO Check
on:
workflow_dispatch:
pull_request:
branches:
- develop
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: KineticCafe/actions-dco@v1
+33
View File
@@ -201,6 +201,39 @@ 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]
+5 -1
View File
@@ -35,4 +35,8 @@ benchmark-report.md
*.sqlite
*.sqlite3
rtk_tracking.db
claudedocs
claudedocs
# Vitals provenance data
.vitals/
.worktrees/
+1 -1
View File
@@ -1,3 +1,3 @@
{
".": "0.27.1"
".": "0.28.1"
}
+3 -3
View File
@@ -293,12 +293,12 @@ SHARED utils.rs Helpers N/A ✓
tee.rs Full output recovery N/A ✓
```
**Total: 57 modules** (38 command modules + 19 infrastructure modules)
**Total: 60 modules** (38 command modules + 22 infrastructure modules)
### Module Count Breakdown
- **Command Modules**: 34 (directly exposed to users)
- **Infrastructure Modules**: 18 (utils, filter, tracking, tee, config, init, gain, etc.)
- **Infrastructure Modules**: 20 (utils, filter, tracking, tee, config, init, gain, toml_filter, verify_cmd, 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.26.0
**rtk Version**: 0.28.0
+42
View File
@@ -5,6 +5,34 @@ 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.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)
@@ -46,11 +74,25 @@ 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)
+1 -1
View File
@@ -16,7 +16,7 @@ This is a fork with critical fixes for git argument parsing and modern JavaScrip
**Verify correct installation:**
```bash
rtk --version # Should show "rtk 0.26.0" (or newer)
rtk --version # Should show "rtk 0.28.0" (or newer)
rtk gain # Should show token savings stats (NOT "command not found")
```
+199
View File
@@ -0,0 +1,199 @@
# 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
View File
@@ -838,7 +838,7 @@ dependencies = [
[[package]]
name = "rtk"
version = "0.27.1"
version = "0.28.1"
dependencies = [
"anyhow",
"chrono",
+4 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "rtk"
version = "0.27.1"
version = "0.28.1"
edition = "2021"
authors = ["Patrick Szymkowiak"]
description = "Rust Token Killer - High-performance CLI proxy to minimize LLM token consumption"
@@ -31,6 +31,9 @@ sha2 = "0.10"
ureq = "2"
hostname = "0.4"
[build-dependencies]
toml = "0.8"
[dev-dependencies]
[profile.release]
+195 -703
View File
File diff suppressed because it is too large. Load diff
+159
View File
@@ -0,0 +1,159 @@
<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> &bull;
<a href="#instalacion">Instalar</a> &bull;
<a href="docs/TROUBLESHOOTING.md">Solucion de problemas</a> &bull;
<a href="ARCHITECTURE.md">Arquitectura</a> &bull;
<a href="https://discord.gg/gFwRPEKq4p">Discord</a>
</p>
<p align="center">
<a href="README.md">English</a> &bull;
<a href="README_fr.md">Francais</a> &bull;
<a href="README_zh.md">中文</a> &bull;
<a href="README_ja.md">日本語</a> &bull;
<a href="README_ko.md">한국어</a> &bull;
<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
View File
@@ -0,0 +1,197 @@
<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> &bull;
<a href="#installation">Installer</a> &bull;
<a href="docs/TROUBLESHOOTING.md">Depannage</a> &bull;
<a href="ARCHITECTURE.md">Architecture</a> &bull;
<a href="https://discord.gg/gFwRPEKq4p">Discord</a>
</p>
<p align="center">
<a href="README.md">English</a> &bull;
<a href="README_fr.md">Francais</a> &bull;
<a href="README_zh.md">中文</a> &bull;
<a href="README_ja.md">日本語</a> &bull;
<a href="README_ko.md">한국어</a> &bull;
<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
View File
@@ -0,0 +1,159 @@
<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> &bull;
<a href="#インストール">インストール</a> &bull;
<a href="docs/TROUBLESHOOTING.md">トラブルシューティング</a> &bull;
<a href="ARCHITECTURE.md">アーキテクチャ</a> &bull;
<a href="https://discord.gg/gFwRPEKq4p">Discord</a>
</p>
<p align="center">
<a href="README.md">English</a> &bull;
<a href="README_fr.md">Francais</a> &bull;
<a href="README_zh.md">中文</a> &bull;
<a href="README_ja.md">日本語</a> &bull;
<a href="README_ko.md">한국어</a> &bull;
<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)** - 技術アーキテクチャ
## コントリビュート
コントリビューション歓迎![GitHub](https://github.com/rtk-ai/rtk) で issue または PR を作成してください。
[Discord](https://discord.gg/pvHdzAec) コミュニティに参加。
## ライセンス
MIT ライセンス - 詳細は [LICENSE](LICENSE) を参照。
+159
View File
@@ -0,0 +1,159 @@
<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> &bull;
<a href="#설치">설치</a> &bull;
<a href="docs/TROUBLESHOOTING.md">문제 해결</a> &bull;
<a href="ARCHITECTURE.md">아키텍처</a> &bull;
<a href="https://discord.gg/gFwRPEKq4p">Discord</a>
</p>
<p align="center">
<a href="README.md">English</a> &bull;
<a href="README_fr.md">Francais</a> &bull;
<a href="README_zh.md">中文</a> &bull;
<a href="README_ja.md">日本語</a> &bull;
<a href="README_ko.md">한국어</a> &bull;
<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
View File
@@ -0,0 +1,167 @@
<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> &bull;
<a href="#安装">安装</a> &bull;
<a href="docs/TROUBLESHOOTING.md">故障排除</a> &bull;
<a href="ARCHITECTURE.md">架构</a> &bull;
<a href="https://discord.gg/gFwRPEKq4p">Discord</a>
</p>
<p align="center">
<a href="README.md">English</a> &bull;
<a href="README_fr.md">Francais</a> &bull;
<a href="README_zh.md">中文</a> &bull;
<a href="README_ja.md">日本語</a> &bull;
<a href="README_ko.md">한국어</a> &bull;
<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)。
+57
View File
@@ -0,0 +1,57 @@
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
View File
File diff suppressed because it is too large. Load diff
+102
View File
@@ -0,0 +1,102 @@
# 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
```
+2
View File
@@ -8,10 +8,12 @@
# 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
+14 -3
View File
@@ -426,20 +426,31 @@ else
skip_test "rtk golangci-lint" "golangci-lint not installed"
fi
# ── 29. Global flags ────────────────────────────────
# ── 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 ────────────────────────────────
section "Global flags"
assert_ok "rtk -u ls ." rtk -u ls .
assert_ok "rtk --skip-env npm --help" rtk --skip-env npm --help
# ── 30. CcEconomics ─────────────────────────────────
# ── 31. CcEconomics ─────────────────────────────────
section "CcEconomics"
assert_ok "rtk cc-economics" rtk cc-economics
# ── 31. Learn ───────────────────────────────────────
# ── 32. Learn ───────────────────────────────────────
section "Learn"
+52
View File
@@ -0,0 +1,52 @@
# 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.
+34
View File
@@ -0,0 +1,34 @@
[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"
+37
View File
@@ -0,0 +1,37 @@
[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"
+40
View File
@@ -0,0 +1,40 @@
[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"
+16
View File
@@ -0,0 +1,16 @@
[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 = ""
+64
View File
@@ -0,0 +1,64 @@
[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)"
+16
View File
@@ -0,0 +1,16 @@
[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."
+15
View File
@@ -0,0 +1,15 @@
[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"
+22
View File
@@ -0,0 +1,22 @@
[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."
+24
View File
@@ -0,0 +1,24 @@
[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 = ""
+29
View File
@@ -0,0 +1,29 @@
[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"
+27
View File
@@ -0,0 +1,27 @@
[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"
+41
View File
@@ -0,0 +1,41 @@
[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"
+24
View File
@@ -0,0 +1,24 @@
[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 = ""
+27
View File
@@ -0,0 +1,27 @@
[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"
+15
View File
@@ -0,0 +1,15 @@
[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"
+44
View File
@@ -0,0 +1,44 @@
[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"
+63
View File
@@ -0,0 +1,63 @@
[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"""
+40
View File
@@ -0,0 +1,40 @@
[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"
+50
View File
@@ -0,0 +1,50 @@
[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"
+35
View File
@@ -0,0 +1,35 @@
[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"
+16
View File
@@ -0,0 +1,16 @@
[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 = ""
+41
View File
@@ -0,0 +1,41 @@
[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"
+48
View File
@@ -0,0 +1,48 @@
[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"""
+27
View File
@@ -0,0 +1,27 @@
[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 = ""
+29
View File
@@ -0,0 +1,29 @@
[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"
+16
View File
@@ -0,0 +1,16 @@
[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"
+41
View File
@@ -0,0 +1,41 @@
[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)"
+33
View File
@@ -0,0 +1,33 @@
[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 = ""
+35
View File
@@ -0,0 +1,35 @@
[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."
+16
View File
@@ -0,0 +1,16 @@
[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"
+38
View File
@@ -0,0 +1,38 @@
[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"
+35
View File
@@ -0,0 +1,35 @@
[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"
+17
View File
@@ -0,0 +1,17 @@
[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\""
+39
View File
@@ -0,0 +1,39 @@
[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"
+37
View File
@@ -0,0 +1,37 @@
[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"
+25
View File
@@ -0,0 +1,25 @@
[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 = ""
+60 -44
View File
@@ -4,7 +4,6 @@
//! 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};
@@ -276,6 +275,12 @@ 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();
@@ -284,6 +289,12 @@ 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",
@@ -1092,11 +1103,23 @@ 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 args {
for arg in gh_args.iter() {
cmd.arg(arg);
}
@@ -1115,7 +1138,7 @@ fn pr_diff(args: &[String], _verbose: u8) -> Result<()> {
print!("{}", msg);
msg.to_string()
} else {
let compacted = git::compact_diff(&raw, 100);
let compacted = git::compact_diff(&raw, 500);
println!("{}", compacted);
compacted
};
@@ -1179,47 +1202,10 @@ fn pr_action(action: &str, args: &[String], _verbose: u8) -> Result<()> {
}
fn run_api(args: &[String], _verbose: u8) -> Result<()> {
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(())
// 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)
}
/// Pass through a command with base args + extra args, tracking as passthrough.
@@ -1432,6 +1418,36 @@ mod tests {
assert!(!should_passthrough_run_view(&["--web".into()]));
}
// --- 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]
+82 -8
View File
@@ -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(100));
let compacted = compact_diff(&diff_stdout, max_lines.unwrap_or(500));
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(100));
let compacted = compact_diff(diff_text, max_lines.unwrap_or(500));
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 = 10;
let max_hunk_lines = 30;
for line in diff.lines() {
if line.starts_with("diff --git") {
@@ -617,11 +617,14 @@ 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);
let formatted = if !stderr.is_empty() && stderr.contains("not a git repository") {
"Not a git repository".to_string()
} else {
format_status_output(&stdout)
};
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);
println!("{}", formatted);
@@ -1449,6 +1452,40 @@ 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"));
@@ -1776,4 +1813,41 @@ 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]
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");
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.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
View File
@@ -0,0 +1,810 @@
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
);
}
}
+87 -2
View File
@@ -12,6 +12,37 @@ 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 {
@@ -666,8 +697,10 @@ 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: unchanged behavior (full injection into ./CLAUDE.md)
return run_claude_md_mode(false, verbose);
// Local init: inject CLAUDE.md + generate project-local filters template
run_claude_md_mode(false, verbose)?;
generate_project_filters_template(verbose)?;
return Ok(());
}
let claude_dir = resolve_claude_dir()?;
@@ -717,11 +750,63 @@ 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<()> {
+193 -25
View File
@@ -19,6 +19,7 @@ mod git;
mod go_cmd;
mod golangci_cmd;
mod grep_cmd;
mod gt_cmd;
mod hook_audit_cmd;
mod hook_check;
mod init;
@@ -47,10 +48,12 @@ 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;
@@ -549,8 +552,15 @@ enum Commands {
args: Vec<OsString>,
},
/// Verify hook integrity (SHA-256 check)
Verify,
/// 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,
},
/// Ruff linter/formatter with compact output
Ruff {
@@ -586,6 +596,12 @@ 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 {
@@ -721,7 +737,7 @@ enum PnpmCommands {
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
args: Vec<String>,
},
/// Build (delegates to next build filter)
/// Build (generic passthrough, no framework-specific filter)
Build {
/// Additional build arguments
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
@@ -939,6 +955,7 @@ const RTK_META_COMMANDS: &[&str] = &[
"proxy",
"hook-audit",
"cc-economics",
"verify",
];
fn run_fallback(parse_error: clap::Error) -> Result<()> {
@@ -961,34 +978,137 @@ fn run_fallback(parse_error: clap::Error) -> Result<()> {
// Start timer before execution to capture actual command runtime
let timer = tracking::TimedExecution::start();
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();
// 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)
};
match status {
Ok(s) => {
timer.track_passthrough(&raw_command, &format!("rtk fallback: {}", raw_command));
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();
tracking::record_parse_failure_silent(&raw_command, &error_message, true);
match result {
Ok(output) => {
let stdout_raw = String::from_utf8_lossy(&output.stdout);
if !s.success() {
std::process::exit(s.code().unwrap_or(1));
// 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);
}
}
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();
} 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);
}
}
}
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>),
}
fn main() -> Result<()> {
// Fire-and-forget telemetry ping (1/day, non-blocking)
telemetry::maybe_ping();
@@ -1215,7 +1335,10 @@ fn main() -> Result<()> {
)?;
}
PnpmCommands::Build { args } => {
next_cmd::run(&args, cli.verbose)?;
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)?;
}
PnpmCommands::Typecheck { args } => {
tsc_cmd::run(&args, cli.verbose)?;
@@ -1685,6 +1808,30 @@ 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)?;
}
@@ -1803,8 +1950,18 @@ fn main() -> Result<()> {
}
}
Commands::Verify => {
integrity::run_verify(cli.verbose)?;
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)?;
}
}
}
@@ -1860,6 +2017,7 @@ fn is_operational_command(cmd: &Commands) -> bool {
| Commands::Pip { .. }
| Commands::Go { .. }
| Commands::GolangciLint { .. }
| Commands::Gt { .. }
)
}
@@ -2030,9 +2188,19 @@ 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 should parse successfully");
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"),
}
}
}
#[test]
+44 -4
View File
@@ -8,7 +8,14 @@ pub fn run(args: &[String], verbose: u8, skip_env: bool) -> Result<()> {
let mut cmd = Command::new("npm");
cmd.arg("run");
for arg in args {
// Strip leading "run" to avoid doubling (rtk npm run build → npm run build, not npm run run build)
let effective_args = if args.first().map(|s| s.as_str()) == Some("run") {
&args[1..]
} else {
args
};
for arg in effective_args {
cmd.arg(arg);
}
@@ -17,7 +24,7 @@ pub fn run(args: &[String], verbose: u8, skip_env: bool) -> Result<()> {
}
if verbose > 0 {
eprintln!("Running: npm run {}", args.join(" "));
eprintln!("Running: npm run {}", effective_args.join(" "));
}
let output = cmd.output().context("Failed to run npm run")?;
@@ -29,8 +36,8 @@ pub fn run(args: &[String], verbose: u8, skip_env: bool) -> Result<()> {
println!("{}", filtered);
timer.track(
&format!("npm run {}", args.join(" ")),
&format!("rtk npm run {}", args.join(" ")),
&format!("npm run {}", effective_args.join(" ")),
&format!("rtk npm run {}", effective_args.join(" ")),
&raw,
&filtered,
);
@@ -100,6 +107,39 @@ npm notice
assert!(result.contains("Build completed"));
}
#[test]
fn test_strip_leading_run_from_args() {
// When user runs `rtk npm run build`, args = ["run", "build"]
// The "run" should be stripped since cmd.arg("run") already adds it
let args: Vec<String> = vec!["run".into(), "build".into()];
let effective_args = if args.first().map(|s| s.as_str()) == Some("run") {
&args[1..]
} else {
&args[..]
};
assert_eq!(effective_args, &["build"]);
// When user runs `rtk npm build`, args = ["build"]
// No stripping needed
let args2: Vec<String> = vec!["build".into()];
let effective_args2 = if args2.first().map(|s| s.as_str()) == Some("run") {
&args2[1..]
} else {
&args2[..]
};
assert_eq!(effective_args2, &["build"]);
// When user runs `rtk npm run`, args = ["run"]
// Strip "run" → empty args (npm run with no script)
let args3: Vec<String> = vec!["run".into()];
let effective_args3 = if args3.first().map(|s| s.as_str()) == Some("run") {
&args3[1..]
} else {
&args3[..]
};
assert!(effective_args3.is_empty());
}
#[test]
fn test_filter_npm_output_empty() {
let output = "\n\n\n";
+79
View File
@@ -52,6 +52,7 @@ 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) = get_stats();
@@ -61,6 +62,7 @@ fn send_ping() -> Result<(), Box<dyn std::error::Error>> {
"version": version,
"os": os,
"arch": arch,
"install_method": install_method,
"commands_24h": commands_24h,
"top_commands": top_commands,
"savings_pct": savings_pct,
@@ -112,6 +114,32 @@ fn get_stats() -> (i64, Vec<String>, Option<f64>) {
(commands_24h, top_commands, savings_pct)
}
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"
}
}
fn telemetry_marker_path() -> PathBuf {
let data_dir = dirs::data_local_dir()
.unwrap_or_else(|| PathBuf::from("/tmp"))
@@ -141,4 +169,55 @@ 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
);
}
}
+1655
View File
File diff suppressed because it is too large. Load diff
+14 -14
View File
@@ -9,11 +9,11 @@ use anyhow::{Context, Result};
use regex::Regex;
use std::process::Command;
/// Tronque une chaîne à `max_len` caractères avec "..." si nécessaire.
/// Truncates a string to `max_len` characters, appending `...` if needed.
///
/// # Arguments
/// * `s` - La chaîne à tronquer
/// * `max_len` - Longueur maximale avant troncature (minimum 3 pour inclure "...")
/// * `s` - The string to truncate
/// * `max_len` - Maximum length before truncation (minimum 3 to include "...")
///
/// # Examples
/// ```
@@ -33,10 +33,10 @@ pub fn truncate(s: &str, max_len: usize) -> String {
}
}
/// Supprime les codes ANSI d'une chaîne (couleurs, styles).
/// Strips ANSI escape codes (colors, styles) from a string.
///
/// # Arguments
/// * `text` - Texte contenant potentiellement des codes ANSI
/// * `text` - Text potentially containing ANSI escape codes
///
/// # Examples
/// ```
@@ -51,11 +51,11 @@ pub fn strip_ansi(text: &str) -> String {
ANSI_RE.replace_all(text, "").to_string()
}
/// Exécute une commande et retourne stdout/stderr nettoyés.
/// Executes a command and returns cleaned stdout/stderr.
///
/// # Arguments
/// * `cmd` - Commande à exécuter (ex: "eslint")
/// * `args` - Arguments de la commande
/// * `cmd` - Command to execute (e.g. "eslint")
/// * `args` - Command arguments
///
/// # 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))
}
/// Formate un nombre de tokens avec suffixes K/M pour lisibilité.
/// Formats a token count with K/M suffixes for readability.
///
/// # Arguments
/// * `n` - Nombre de tokens
/// * `n` - Token count
///
/// # Returns
/// String formaté (ex: "1.2M", "59.2K", "694")
/// Formatted string (e.g. "1.2M", "59.2K", "694")
///
/// # Examples
/// ```
@@ -105,13 +105,13 @@ pub fn format_tokens(n: usize) -> String {
}
}
/// Formate un montant USD avec précision adaptée.
/// Formats a USD amount with adaptive precision.
///
/// # Arguments
/// * `amount` - Montant en dollars
/// * `amount` - Amount in dollars
///
/// # Returns
/// String formaté avec $ prefix
/// Formatted string with $ prefix
///
/// # Examples
/// ```
+47
View File
@@ -0,0 +1,47 @@
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(())
}