RTK uses a sophisticated pipeline to ensure shell commands are rewritten safely without breaking syntax:
1. Tokenization
A lexer (lexer.rs) converts raw strings into typed tokens. This prevents errors caused by naive string splitting, such as breaking on quoted content like git commit -m "fix && update".
2. Compound Splitting
The engine splits commands on operators (&&, ||, ;) and pipes (|, |&).
- Safety Rule: For standard pipelines, only the final stage marked
pipeline_final_safe is rewritten. - Exclusions: Stderr pipelines (
|&) and pipelines containing opaque shell groups remain raw to prevent corruption.
3. Per-segment Rewriting
Each command segment undergoes these steps:
- Strip Redirects: Trailing redirects like
2>&1 or >/dev/null are stripped and re-appended after the rewrite. - Short-circuit Special Cases: Specific patterns like
head -20 file are converted to rtk read file --max-lines 20 rather than using generic prefix replacement. - Classification: The command is normalized (stripping
sudo, environment variables, and absolute paths) and matched against 60+ regex patterns. - Application: The matching prefix is replaced with
rtk <cmd>, and the original environment prefixes and redirects are re-applied.
4. Rewrite Guards (When rewriting is skipped)
Rewriting is automatically skipped if:
RTK_DISABLED=1 is present in the environment prefix.- The command is
gh with structured output flags (--json, --jq, --template). - The command is
cat with flags other than -n. - The command involves write operations (e.g.,
cat or head with > or >>). - The command is explicitly listed in the
hooks.exclude_commands configuration.