Compare commits
32
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d402152ffa | ||
|
|
06d538728c | ||
|
|
cfe248c1f6 | ||
|
|
784d347011 | ||
|
|
e224b159af | ||
|
|
2ff2f71711 | ||
|
|
cb5e5994e1 | ||
|
|
4b6c0f00ef | ||
|
|
b6a171242c | ||
|
|
23a1be622f | ||
|
|
6f4913b37b | ||
|
|
9573488935 | ||
|
|
86668b065a | ||
|
|
d0c2985155 | ||
|
|
d105227193 | ||
|
|
83b1957cca | ||
|
|
0cd3eba80b | ||
|
|
718c18530d | ||
|
|
83f87f92f3 | ||
|
|
3d2d244406 | ||
|
|
f64d1d4808 | ||
|
|
8b4c445815 | ||
|
|
ed8480f3e2 | ||
|
|
ba802ac82d | ||
|
|
905ca3a852 | ||
|
|
d5364b814e | ||
|
|
656a8640e6 | ||
|
|
3b4ab8735a | ||
|
|
0f45992a0d | ||
|
|
de0450d26f | ||
|
|
f3e0094183 | ||
|
|
ecdf332a3d |
No files matched your search
@@ -85,15 +85,15 @@ elif echo "$FIRST_CMD" | grep -qE '^find\s+'; then
|
||||
elif echo "$FIRST_CMD" | grep -qE '^diff\s+'; then
|
||||
SUGGESTION=$(echo "$CMD" | sed 's/^diff /rtk diff /')
|
||||
elif echo "$FIRST_CMD" | grep -qE '^head\s+'; then
|
||||
# Suggest rtk read with --max-lines transformation
|
||||
# Suggest rtk read with --head-lines transformation
|
||||
if echo "$FIRST_CMD" | grep -qE '^head\s+-[0-9]+\s+'; then
|
||||
LINES=$(echo "$FIRST_CMD" | sed -E 's/^head +-([0-9]+) +.+$/\1/')
|
||||
FILE=$(echo "$FIRST_CMD" | sed -E 's/^head +-[0-9]+ +(.+)$/\1/')
|
||||
SUGGESTION="rtk read $FILE --max-lines $LINES"
|
||||
SUGGESTION="rtk read $FILE --head-lines $LINES"
|
||||
elif echo "$FIRST_CMD" | grep -qE '^head\s+--lines=[0-9]+\s+'; then
|
||||
LINES=$(echo "$FIRST_CMD" | sed -E 's/^head +--lines=([0-9]+) +.+$/\1/')
|
||||
FILE=$(echo "$FIRST_CMD" | sed -E 's/^head +--lines=[0-9]+ +(.+)$/\1/')
|
||||
SUGGESTION="rtk read $FILE --max-lines $LINES"
|
||||
SUGGESTION="rtk read $FILE --head-lines $LINES"
|
||||
fi
|
||||
|
||||
# --- JS/TS tooling ---
|
||||
|
||||
@@ -45,6 +45,7 @@ RTK intercepts shell commands and compresses their output before your agent read
|
||||
| `ls` / `tree` | Tree format with file counts instead of one line per entry |
|
||||
| `cat` / `read` | Smart file reading: signatures and structure over full bodies |
|
||||
| `grep` / `rg` | Truncates long lines, groups matches by file |
|
||||
| `ast-grep` | Groups structural matches by file, caps overflow |
|
||||
| `git status` | Compact stat format, grouped by state |
|
||||
| `git diff` | Reduced context, headers stripped |
|
||||
| `git log` | Hash, author and subject only |
|
||||
|
||||
+2
-2
@@ -62,8 +62,8 @@ This data directly drives our roadmap. For example, if telemetry shows that 40%
|
||||
|-------|---------|---------|
|
||||
| `passthrough_top` | `["git:15", "npm:8"]` | Top 5 commands with 0% savings — these need filters |
|
||||
| `parse_failures_24h` | `3` | Filter fragility — high count means filters are breaking |
|
||||
| `low_savings_commands` | `["rtk docker ps:25%"]` | Commands averaging <30% savings — filters to improve |
|
||||
| `avg_savings_per_command` | `68.5` | Unweighted average (vs global which is volume-biased) |
|
||||
| `low_savings_commands` | `["rtk docker ps:25%"]` | Commands with weighted savings rate <30%, net-negative ones included — filters to improve. Rate is `SUM(saved)/SUM(input)` over every call of the command, the same figure as the `rtk gain` By Command table, so high-volume calls are not diluted by passthrough calls. Exact 0% is left to `passthrough_top`. |
|
||||
| `avg_savings_per_command` | `68.5` | Unweighted average across distinct command names (each filter counts once regardless of invocation volume). Each command's individual rate is weighted by volume before the outer average; commands that never had any input are skipped. |
|
||||
| `recall_mode` | `sqlite` | Which recovery mode is active (`sqlite`/`tee`/`disabled`) |
|
||||
| `recall_stats` | `[{"filter":"grep","mode":"sqlite","elisions":142,"recalls":9}]` | Per-filter counters: how often elided output is retrieved — calibrates filter caps. Filter names come from a fixed allowlist of rtk filter families; anything else is folded into `other`. No hashes, no paths, no command arguments, no output content. |
|
||||
|
||||
|
||||
@@ -166,7 +166,7 @@ rewrite_segment(seg, excluded) [src/discover/registry.rs]
|
||||
| Step 4 — Already RTK → return as-is
|
||||
|
|
||||
| Step 5 — Special cases (short-circuit before classification)
|
||||
| head -N / --lines=N → rewrite_line_range() → "rtk read file --max-lines N"
|
||||
| head -N / -n N / --lines[= ]N / bare → rewrite_line_range() → "rtk read file --head-lines N"
|
||||
| tail -N / -n N / --lines N → rewrite_line_range() → "rtk read file --tail-lines N"
|
||||
| head/tail with unsupported flag (-c, -f) → None (skip rewrite)
|
||||
| cat with incompatible flag (-A, -v, -e) → None (skip rewrite)
|
||||
|
||||
@@ -67,8 +67,8 @@ This data directly drives our roadmap. For example, if telemetry shows that 40%
|
||||
|-------|---------|---------|
|
||||
| `passthrough_top` | `["git:15", "npm:8"]` | Top 5 commands with 0% bash output reduction — these need filters |
|
||||
| `parse_failures_24h` | `3` | Filter fragility — high count means filters are breaking |
|
||||
| `low_savings_commands` | `["rtk <cmd>:25%"]` | Commands averaging <30% bash output reduction — filters to improve. The example is a placeholder, not a measured value |
|
||||
| `avg_savings_per_command` | `68.5` | Unweighted average (vs global which is volume-biased) |
|
||||
| `low_savings_commands` | `["rtk <cmd>:25%"]` | Commands with a weighted bash output reduction <30%, net-negative ones included — filters to improve. The rate is `SUM(saved)/SUM(input)` over every call of the command, the same figure as the `rtk gain` By Command table, so high-volume calls are not diluted by passthrough calls. Exact 0% is left to `passthrough_top`. The example is a placeholder, not a measured value |
|
||||
| `avg_savings_per_command` | `68.5` | Unweighted average across distinct command names (each filter counts once regardless of invocation volume); each command's own rate is weighted by volume before the outer average, and commands that never had any input are skipped |
|
||||
|
||||
### Ecosystem distribution
|
||||
|
||||
|
||||
@@ -116,6 +116,7 @@ Every percentage below measures **bash output bytes removed** — the only thing
|
||||
| `ls` | 80% | Tree format with file counts |
|
||||
| `find` | 75% | Tree format |
|
||||
| `grep` | 70% | Truncated lines, grouped by file |
|
||||
| `ast-grep` | 85% | Grouped by file, capped overflow; `--json` passes through |
|
||||
| `diff` | 65% | Context reduced |
|
||||
| `wc` | 60% | Compact counts |
|
||||
| `cat` / `head` / `tail <file>` | 60-80% | Smart file reading via `rtk read` |
|
||||
|
||||
+20
-2
@@ -130,7 +130,9 @@ rtk read - [options] # Lecture depuis stdin
|
||||
| Option | Court | Defaut | Description |
|
||||
|--------|-------|--------|-------------|
|
||||
| `--level` | `-l` | `minimal` | Niveau de filtrage : `none`, `minimal`, `aggressive` |
|
||||
| `--max-lines` | `-m` | illimite | Nombre maximum de lignes |
|
||||
| `--max-lines` | `-m` | illimite | Apercu structurel plafonne a N lignes (signatures et imports, pas les N premieres) |
|
||||
| `--head-lines` | | illimite | Garde seulement les N premieres lignes, a l'octet pres |
|
||||
| `--tail-lines` | | illimite | Garde seulement les N dernieres lignes, a l'octet pres |
|
||||
| `--line-numbers` | `-n` | non | Afficher les numeros de ligne |
|
||||
|
||||
**Niveaux de filtrage :**
|
||||
@@ -238,6 +240,21 @@ src/ls.rs:25:fn run_tree(...) src/ls.rs
|
||||
|
||||
---
|
||||
|
||||
### `rtk ast-grep` -- Recherche structurelle (AST)
|
||||
|
||||
**Objectif :** Remplace `ast-grep` avec une sortie groupee par fichier, plafonnee.
|
||||
|
||||
**Syntaxe :**
|
||||
```bash
|
||||
rtk ast-grep run -p '<pattern>' [chemin] [options]
|
||||
```
|
||||
|
||||
Regroupe les correspondances par fichier, plafonnees a 5 par fichier et 50 au total ; le surplus est remplace par une note de comptage ("N more match line(s) in X" / "N more file(s) not shown"). ast-grep imprime une ligne par ligne source d'une correspondance, et une correspondance structurelle s'etend sur plusieurs lignes : le decompte porte donc sur les lignes, pas sur les correspondances. Les sorties que rtk ne sait pas decouper (`ast-grep scan`, `--heading`) passent telles quelles. Sur une recherche reelle dans ce depot, ~85% de reduction.
|
||||
|
||||
`--json` n'est pas filtre -- une demande explicite de sortie structuree passe telle quelle, sans compression.
|
||||
|
||||
---
|
||||
|
||||
### `rtk diff` -- Diff condense
|
||||
|
||||
**Objectif :** Diff ultra-condense entre deux fichiers (uniquement les lignes modifiees).
|
||||
@@ -1276,6 +1293,7 @@ rtk verify
|
||||
| `cargo test/build/clippy/check` | `rtk cargo ...` |
|
||||
| `cat/head/tail <fichier>` | `rtk read <fichier>` |
|
||||
| `rg/grep <pattern>` | `rtk grep <pattern>` |
|
||||
| `ast-grep run -p <pattern>` | `rtk ast-grep run -p <pattern>` |
|
||||
| `ls` | `rtk ls` |
|
||||
| `tree` | `rtk tree` |
|
||||
| `wc` | `rtk wc` |
|
||||
@@ -1448,7 +1466,7 @@ Octets de sortie bash supprimes (voir [A propos de la reduction de sortie bash](
|
||||
|
||||
| Categorie | Commandes | Reduction sortie bash |
|
||||
|-----------|-----------|-------------------|
|
||||
| **Fichiers** | ls, tree, read, find, grep, diff | 60-80% |
|
||||
| **Fichiers** | ls, tree, read, find, grep, ast-grep, diff | 60-85% |
|
||||
| **Git** | status, log, diff, show, add, commit, push, pull | 75-92% |
|
||||
| **GitHub** | pr, issue, run, api | 79-87% |
|
||||
| **Tests** | cargo test, vitest, playwright, pytest, go test | 90-99% |
|
||||
|
||||
@@ -220,7 +220,7 @@ pub fn run(
|
||||
println!("{}", "─".repeat(table_width));
|
||||
println!(
|
||||
"{:>3} {:<cmd_width$} {:>count_width$} {:>saved_width$} {:>6} {:>time_width$} {:<impact_width$}",
|
||||
"#", "Command", "Count", "Saved", "Avg%", "Time", "Impact",
|
||||
"#", "Command", "Count", "Saved", "Total%", "Time", "Impact",
|
||||
cmd_width = cmd_width, count_width = count_width,
|
||||
saved_width = saved_width, time_width = time_width,
|
||||
impact_width = impact_width
|
||||
|
||||
+141
-16
@@ -462,29 +462,54 @@ fn pr_checks(args: &[String], _verbose: u8, _ultra_compact: bool) -> Result<i32>
|
||||
"gh",
|
||||
&label,
|
||||
format_pr_checks,
|
||||
RunOptions::stdout_only()
|
||||
.early_exit_on_failure()
|
||||
.no_trailing_newline(),
|
||||
RunOptions::stdout_only().no_trailing_newline(),
|
||||
)
|
||||
}
|
||||
|
||||
fn format_pr_checks(stdout: &str) -> String {
|
||||
let mut passed = 0;
|
||||
let mut failed = 0;
|
||||
let mut pending = 0;
|
||||
let mut failed_checks = Vec::new();
|
||||
|
||||
// `gh pr checks --watch` appends each poll's table when stdout is not a TTY.
|
||||
// Keep the latest row for each check so status transitions are reflected
|
||||
// without inflating the summary.
|
||||
let mut checks: Vec<(String, String, PrCheckStatus, String)> = Vec::new();
|
||||
for line in stdout.lines() {
|
||||
if line.contains("[ok]") || line.contains("pass") {
|
||||
passed += 1;
|
||||
} else if line.contains("[x]") || line.contains("fail") {
|
||||
failed += 1;
|
||||
failed_checks.push(line.trim().to_string());
|
||||
} else if line.contains('*') || line.contains("pending") {
|
||||
pending += 1;
|
||||
let Some((name, link, status)) = parse_pr_check_line(line) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if let Some(check) = checks
|
||||
.iter_mut()
|
||||
.find(|check| check.0 == name && check.1 == link)
|
||||
{
|
||||
check.2 = status;
|
||||
check.3 = line.trim().to_string();
|
||||
} else {
|
||||
checks.push((
|
||||
name.to_string(),
|
||||
link.to_string(),
|
||||
status,
|
||||
line.trim().to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let passed = checks
|
||||
.iter()
|
||||
.filter(|check| check.2 == PrCheckStatus::Passed)
|
||||
.count();
|
||||
let failed = checks
|
||||
.iter()
|
||||
.filter(|check| check.2 == PrCheckStatus::Failed)
|
||||
.count();
|
||||
let pending = checks
|
||||
.iter()
|
||||
.filter(|check| check.2 == PrCheckStatus::Pending)
|
||||
.count();
|
||||
|
||||
let other = checks
|
||||
.iter()
|
||||
.filter(|check| check.2 == PrCheckStatus::Other)
|
||||
.count();
|
||||
|
||||
let mut out = String::new();
|
||||
out.push_str("CI Checks Summary:\n");
|
||||
out.push_str(&format!(" [ok] Passed: {}\n", passed));
|
||||
@@ -492,7 +517,14 @@ fn format_pr_checks(stdout: &str) -> String {
|
||||
if pending > 0 {
|
||||
out.push_str(&format!(" [pending] Pending: {}\n", pending));
|
||||
}
|
||||
if !failed_checks.is_empty() {
|
||||
if other > 0 {
|
||||
out.push_str(&format!(" [skip] Skipped/cancelled: {}\n", other));
|
||||
}
|
||||
let failed_checks = checks
|
||||
.iter()
|
||||
.filter(|check| check.2 == PrCheckStatus::Failed)
|
||||
.map(|check| check.3.as_str());
|
||||
if failed > 0 {
|
||||
out.push_str("\n Failed checks:\n");
|
||||
for check in failed_checks {
|
||||
out.push_str(&format!(" {}\n", check));
|
||||
@@ -501,6 +533,31 @@ fn format_pr_checks(stdout: &str) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum PrCheckStatus {
|
||||
Passed,
|
||||
Failed,
|
||||
Pending,
|
||||
Other,
|
||||
}
|
||||
|
||||
fn parse_pr_check_line(line: &str) -> Option<(&str, &str, PrCheckStatus)> {
|
||||
let mut fields = line.split('\t');
|
||||
let name = fields.next()?.trim();
|
||||
let status = match fields.next()?.trim() {
|
||||
"pass" => PrCheckStatus::Passed,
|
||||
"fail" => PrCheckStatus::Failed,
|
||||
"pending" | "*" => PrCheckStatus::Pending,
|
||||
// skipping, cancelled, and whatever a later gh adds. Counted rather than
|
||||
// dropped, so the totals add up to the checks gh listed and a cancelled
|
||||
// run cannot read as "nothing wrong".
|
||||
_ => PrCheckStatus::Other,
|
||||
};
|
||||
let link = fields.nth(1).unwrap_or("").trim();
|
||||
|
||||
(!name.is_empty()).then_some((name, link, status))
|
||||
}
|
||||
|
||||
fn pr_status(args: &[String], _verbose: u8, _ultra_compact: bool) -> Result<i32> {
|
||||
if should_passthrough_pr_status(args) {
|
||||
let mut passthrough_args = Vec::with_capacity(args.len() + 1);
|
||||
@@ -1121,6 +1178,74 @@ mod tests {
|
||||
assert!(extract_identifier_and_extra_args(&args).is_none());
|
||||
}
|
||||
|
||||
// --- format_pr_checks tests ---
|
||||
|
||||
#[test]
|
||||
fn test_format_pr_checks_counts_each_watch_snapshot_once() {
|
||||
let output = concat!(
|
||||
"Analyze (actions)\tpass\t42s\thttps://example.com/actions\n",
|
||||
"Analyze (rust)\tpass\t2m\thttps://example.com/rust\n",
|
||||
"Analyze (actions)\tpass\t42s\thttps://example.com/actions\n",
|
||||
"Analyze (rust)\tpass\t2m\thttps://example.com/rust\n",
|
||||
);
|
||||
|
||||
let result = format_pr_checks(output);
|
||||
|
||||
assert!(result.contains("Passed: 2"));
|
||||
assert!(!result.contains("Passed: 4"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_format_pr_checks_uses_final_status_for_each_check() {
|
||||
let output = concat!(
|
||||
"Lint\tpending\t0\thttps://example.com/lint\n",
|
||||
"Unit tests\tfail\t1m\thttps://example.com/unit\n",
|
||||
"Lint\tpass\t30s\thttps://example.com/lint\n",
|
||||
"Unit tests\tfail\t1m\thttps://example.com/unit\n",
|
||||
);
|
||||
|
||||
let result = format_pr_checks(output);
|
||||
|
||||
assert!(result.contains("Passed: 1"));
|
||||
assert!(result.contains("Failed: 1"));
|
||||
assert!(!result.contains("Pending:"));
|
||||
assert!(result.contains("Unit tests\tfail"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_format_pr_checks_keeps_same_name_checks_with_different_links() {
|
||||
let output = concat!(
|
||||
"build\tpass\t1m\thttps://example.com/workflow-a\n",
|
||||
"build\tfail\t1m\thttps://example.com/workflow-b\n",
|
||||
);
|
||||
|
||||
let result = format_pr_checks(output);
|
||||
|
||||
assert!(result.contains("Passed: 1"));
|
||||
assert!(result.contains("Failed: 1"));
|
||||
}
|
||||
|
||||
/// Rows exactly as `gh` prints them when stdout is a pipe: five tab-separated
|
||||
/// fields, the fifth (the description) usually empty. Captured from
|
||||
/// `gh pr checks --watch` against a run that was still going, so the pending
|
||||
/// rows here are the shape a real transition arrives in.
|
||||
#[test]
|
||||
fn test_format_pr_checks_handles_real_gh_row_shape() {
|
||||
let output = concat!(
|
||||
"test (macos-latest)\tpending\t0\thttps://example.com/job/1\t\n",
|
||||
"clippy\tpass\t28s\thttps://example.com/job/2\t\n",
|
||||
"license/cla\tpass\t0\thttps://cla.example.com/pr/1\tContributor License Agreement is signed.\n",
|
||||
"test (macos-latest)\tpass\t3m1s\thttps://example.com/job/1\t\n",
|
||||
"clippy\tpass\t28s\thttps://example.com/job/2\t\n",
|
||||
"license/cla\tpass\t0\thttps://cla.example.com/pr/1\tContributor License Agreement is signed.\n",
|
||||
);
|
||||
|
||||
let result = format_pr_checks(output);
|
||||
|
||||
assert!(result.contains("Passed: 3"), "got:\n{result}");
|
||||
assert!(!result.contains("Pending:"), "got:\n{result}");
|
||||
}
|
||||
|
||||
// --- parse_optional_identifier tests ---
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
//! Filters `ast-grep run` plain-mode output by grouping matches by file and
|
||||
//! capping how many are shown. `--json` is left near-passthrough (explicit
|
||||
//! structured-output request — see Correctness vs Token Savings).
|
||||
|
||||
use crate::core::stream::exec_capture;
|
||||
use crate::core::tracking;
|
||||
use crate::core::utils::resolved_command;
|
||||
use anyhow::{Context, Result};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
/// Matches the `path:line:` prefix ast-grep emits for every match/context line.
|
||||
static MATCH_LINE_RE: LazyLock<regex::Regex> =
|
||||
LazyLock::new(|| regex::Regex::new(r"^(?P<file>[^:]+):(?P<line>\d+):(?P<content>.*)$").unwrap());
|
||||
|
||||
const DEFAULT_MAX_TOTAL: usize = 50;
|
||||
const DEFAULT_MAX_PER_FILE: usize = 5;
|
||||
|
||||
/// Counts non-blank lines that are not `path:line:content`.
|
||||
///
|
||||
/// Plain `ast-grep run` output is made up entirely of that shape. Other modes
|
||||
/// are not: in an `ast-grep scan` diagnostic only the ` ┌─ a.rs:2:13` locator
|
||||
/// parses, while the rule id, severity, message and source line do not, and
|
||||
/// `--heading` mode and Windows drive-letter paths (`C:\src\a.rs`, which
|
||||
/// `[^:]+` cannot match) fail to parse the same way. Grouping such a shape
|
||||
/// would keep whichever lines happen to parse and discard the rest, so any
|
||||
/// non-zero count leaves the output alone. `search.rs::unparsed_signal` guards
|
||||
/// grep/rg with the same rule.
|
||||
fn unparsed_signal(raw: &str) -> usize {
|
||||
raw.lines()
|
||||
.filter(|line| !line.trim().is_empty() && !MATCH_LINE_RE.is_match(line))
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Groups raw `ast-grep run` plain output by file, keeping at most
|
||||
/// `max_per_file` lines per file and `max_total` lines overall. Every line the
|
||||
/// caps hold back is counted in a hint, so nothing disappears silently; any
|
||||
/// other output shape is returned unchanged.
|
||||
fn filter_ast_grep(raw: &str, max_per_file: usize, max_total: usize) -> String {
|
||||
if unparsed_signal(raw) > 0 {
|
||||
return raw.to_string();
|
||||
}
|
||||
|
||||
let mut by_file: HashMap<&str, Vec<(usize, &str)>> = HashMap::new();
|
||||
let mut order: Vec<&str> = Vec::new();
|
||||
|
||||
for line in raw.lines() {
|
||||
let Some(caps) = MATCH_LINE_RE.captures(line) else {
|
||||
continue;
|
||||
};
|
||||
let file = caps.name("file").unwrap().as_str();
|
||||
let line_num: usize = caps.name("line").unwrap().as_str().parse().unwrap_or(0);
|
||||
let content = caps.name("content").unwrap().as_str();
|
||||
if !by_file.contains_key(file) {
|
||||
order.push(file);
|
||||
}
|
||||
by_file.entry(file).or_default().push((line_num, content));
|
||||
}
|
||||
|
||||
if order.is_empty() {
|
||||
return raw.to_string();
|
||||
}
|
||||
|
||||
let mut out = String::new();
|
||||
let mut shown_total = 0;
|
||||
let mut skipped_files = 0;
|
||||
|
||||
for file in &order {
|
||||
let entries = &by_file[file];
|
||||
if shown_total >= max_total {
|
||||
skipped_files += 1;
|
||||
continue;
|
||||
}
|
||||
let mut shown_here = 0;
|
||||
for (line_num, content) in entries.iter().take(max_per_file) {
|
||||
if shown_total >= max_total {
|
||||
break;
|
||||
}
|
||||
out.push_str(file);
|
||||
out.push(':');
|
||||
out.push_str(&line_num.to_string());
|
||||
out.push(':');
|
||||
out.push_str(content);
|
||||
out.push('\n');
|
||||
shown_total += 1;
|
||||
shown_here += 1;
|
||||
}
|
||||
// `shown_here`, not `max_per_file`: `max_total` can cut a file short of
|
||||
// its own cap, and the hint has to cover every line this loop skipped.
|
||||
// ast-grep prints one line per matched source line and a structural
|
||||
// match spans several, so the unit is lines rather than matches.
|
||||
if entries.len() > shown_here {
|
||||
out.push_str(&format!(
|
||||
" … {} more match line(s) in {}\n",
|
||||
entries.len() - shown_here,
|
||||
file
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if skipped_files > 0 {
|
||||
out.push_str(&format!(
|
||||
"… {} more file(s) with matches not shown (use --json or narrow the pattern)\n",
|
||||
skipped_files
|
||||
));
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
pub fn run(args: &[String]) -> Result<i32> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
let real_cmd = format!("ast-grep {}", args.join(" "));
|
||||
|
||||
let is_json = args.iter().any(|a| a == "--json" || a.starts_with("--json="));
|
||||
|
||||
let mut cmd = resolved_command("ast-grep");
|
||||
cmd.args(args);
|
||||
let result = exec_capture(&mut cmd).context("Failed to execute ast-grep")?;
|
||||
|
||||
let filtered_owned;
|
||||
let filtered: &str = if is_json {
|
||||
&result.stdout
|
||||
} else {
|
||||
filtered_owned = filter_ast_grep(&result.stdout, DEFAULT_MAX_PER_FILE, DEFAULT_MAX_TOTAL);
|
||||
&filtered_owned
|
||||
};
|
||||
|
||||
let shown = crate::core::guard::never_worse(&result.stdout, filtered);
|
||||
timer.track(&real_cmd, "rtk ast-grep", &result.stdout, shown);
|
||||
print!("{}", shown);
|
||||
|
||||
if !result.stderr.is_empty() {
|
||||
eprint!("{}", result.stderr);
|
||||
}
|
||||
|
||||
Ok(result.exit_code)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn count_tokens(s: &str) -> usize {
|
||||
s.split_whitespace().count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_groups_and_caps_by_file() {
|
||||
let input = "\
|
||||
src/a.rs:1:fn foo() {}
|
||||
src/a.rs:2:fn bar() {}
|
||||
src/a.rs:3:fn baz() {}
|
||||
src/b.rs:10:fn qux() {}
|
||||
";
|
||||
let out = filter_ast_grep(input, 2, 50);
|
||||
assert!(out.contains("src/a.rs:1:"));
|
||||
assert!(out.contains("src/a.rs:2:"));
|
||||
assert!(!out.contains("src/a.rs:3:"));
|
||||
assert!(out.contains("1 more match line(s) in src/a.rs"));
|
||||
assert!(out.contains("src/b.rs:10:"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_empty_input() {
|
||||
assert_eq!(filter_ast_grep("", 5, 50), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_unparseable_input_falls_back_unchanged() {
|
||||
let input = "no colons here\njust plain text\n";
|
||||
assert_eq!(filter_ast_grep(input, 5, 50), input);
|
||||
}
|
||||
|
||||
/// A scan diagnostic parses only on its locator line, so grouping it would
|
||||
/// keep ` ┌─ a.rs:2:13` and discard the rule id, severity, message and
|
||||
/// source line.
|
||||
#[test]
|
||||
fn test_scan_diagnostic_shape_passes_through() {
|
||||
let input = "\
|
||||
warning[no-unwrap]: avoid unwrap
|
||||
┌─ a.rs:2:13
|
||||
│
|
||||
2 │ let x = foo().unwrap();
|
||||
│ ^^^^^^^^^^^^^^
|
||||
";
|
||||
assert_eq!(filter_ast_grep(input, 5, 50), input);
|
||||
}
|
||||
|
||||
/// `max_total` can cut a file short before its own `max_per_file` cap is
|
||||
/// reached; the per-file hint must still account for the remainder.
|
||||
#[test]
|
||||
fn test_total_cap_hints_lines_it_cut() {
|
||||
let input = "\
|
||||
a.rs:1:one
|
||||
a.rs:2:two
|
||||
a.rs:3:three
|
||||
a.rs:4:four
|
||||
a.rs:5:five
|
||||
b.rs:1:six
|
||||
b.rs:2:seven
|
||||
b.rs:3:eight
|
||||
";
|
||||
let out = filter_ast_grep(input, 5, 6);
|
||||
assert!(out.contains("b.rs:1:six"), "{out}");
|
||||
assert!(!out.contains("b.rs:2:seven"), "{out}");
|
||||
assert!(
|
||||
out.contains("2 more match line(s) in b.rs"),
|
||||
"cut lines must be hinted, got: {out}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_real_fixture_savings() {
|
||||
let input = include_str!("../../../tests/fixtures/ast_grep_lazylock_raw.txt");
|
||||
let output = filter_ast_grep(input, DEFAULT_MAX_PER_FILE, DEFAULT_MAX_TOTAL);
|
||||
|
||||
let input_tokens = count_tokens(input);
|
||||
let output_tokens = count_tokens(&output);
|
||||
let savings = 100.0 - (output_tokens as f64 / input_tokens as f64 * 100.0);
|
||||
|
||||
assert!(
|
||||
savings >= 60.0,
|
||||
"ast-grep filter: expected >=60% savings, got {:.1}% ({} -> {} tokens)",
|
||||
savings,
|
||||
input_tokens,
|
||||
output_tokens
|
||||
);
|
||||
}
|
||||
}
|
||||
+262
-22
@@ -5,12 +5,14 @@ use crate::core::guard::never_worse;
|
||||
use crate::core::tracking;
|
||||
use anyhow::{Context, Result};
|
||||
use std::fs;
|
||||
use std::io::{self, Read as IoRead, Write};
|
||||
use std::path::Path;
|
||||
|
||||
pub fn run(
|
||||
file: &Path,
|
||||
level: FilterLevel,
|
||||
max_lines: Option<usize>,
|
||||
head_lines: Option<usize>,
|
||||
tail_lines: Option<usize>,
|
||||
line_numbers: bool,
|
||||
verbose: u8,
|
||||
@@ -22,8 +24,25 @@ pub fn run(
|
||||
}
|
||||
|
||||
// Read file content
|
||||
let content = fs::read_to_string(file)
|
||||
let bytes = fs::read(file)
|
||||
.with_context(|| format!("Failed to read file: {}", file.display()))?;
|
||||
if level == FilterLevel::None && !line_numbers {
|
||||
if let Some(window) = byte_line_window(&bytes, head_lines, tail_lines) {
|
||||
io::stdout()
|
||||
.lock()
|
||||
.write_all(window)
|
||||
.context("Failed to write line window")?;
|
||||
timer.track(
|
||||
&format!("cat {}", file.display()),
|
||||
"rtk read",
|
||||
&String::from_utf8_lossy(&bytes),
|
||||
&String::from_utf8_lossy(window),
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let content = String::from_utf8(bytes)
|
||||
.with_context(|| format!("Failed to decode file: {}", file.display()))?;
|
||||
|
||||
// Detect language from extension
|
||||
let lang = file
|
||||
@@ -64,7 +83,7 @@ pub fn run(
|
||||
);
|
||||
}
|
||||
|
||||
filtered = apply_line_window(&filtered, max_lines, tail_lines, &lang);
|
||||
filtered = apply_line_window(&filtered, max_lines, head_lines, tail_lines, &lang);
|
||||
|
||||
let (raw, rtk_output) = if line_numbers {
|
||||
(
|
||||
@@ -88,12 +107,11 @@ pub fn run(
|
||||
pub fn run_stdin(
|
||||
level: FilterLevel,
|
||||
max_lines: Option<usize>,
|
||||
head_lines: Option<usize>,
|
||||
tail_lines: Option<usize>,
|
||||
line_numbers: bool,
|
||||
verbose: u8,
|
||||
) -> Result<()> {
|
||||
use std::io::{self, Read as IoRead};
|
||||
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
if verbose > 0 {
|
||||
@@ -101,11 +119,27 @@ pub fn run_stdin(
|
||||
}
|
||||
|
||||
// Read from stdin
|
||||
let mut content = String::new();
|
||||
let mut bytes = Vec::new();
|
||||
io::stdin()
|
||||
.lock()
|
||||
.read_to_string(&mut content)
|
||||
.read_to_end(&mut bytes)
|
||||
.context("Failed to read from stdin")?;
|
||||
if level == FilterLevel::None && !line_numbers {
|
||||
if let Some(window) = byte_line_window(&bytes, head_lines, tail_lines) {
|
||||
io::stdout()
|
||||
.lock()
|
||||
.write_all(window)
|
||||
.context("Failed to write line window")?;
|
||||
timer.track(
|
||||
"cat - (stdin)",
|
||||
"rtk read -",
|
||||
&String::from_utf8_lossy(&bytes),
|
||||
&String::from_utf8_lossy(window),
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let content = String::from_utf8(bytes).context("Failed to decode stdin")?;
|
||||
|
||||
// No file extension, so use Unknown language
|
||||
let lang = Language::Unknown;
|
||||
@@ -132,7 +166,7 @@ pub fn run_stdin(
|
||||
);
|
||||
}
|
||||
|
||||
filtered = apply_line_window(&filtered, max_lines, tail_lines, &lang);
|
||||
filtered = apply_line_window(&filtered, max_lines, head_lines, tail_lines, &lang);
|
||||
|
||||
let (raw, rtk_output) = if line_numbers {
|
||||
(
|
||||
@@ -162,20 +196,12 @@ fn format_with_line_numbers(content: &str) -> String {
|
||||
fn apply_line_window(
|
||||
content: &str,
|
||||
max_lines: Option<usize>,
|
||||
head_lines: Option<usize>,
|
||||
tail_lines: Option<usize>,
|
||||
lang: &Language,
|
||||
) -> String {
|
||||
if let Some(tail) = tail_lines {
|
||||
if tail == 0 {
|
||||
return String::new();
|
||||
}
|
||||
let lines: Vec<&str> = content.lines().collect();
|
||||
let start = lines.len().saturating_sub(tail);
|
||||
let mut result = lines[start..].join("\n");
|
||||
if content.ends_with('\n') {
|
||||
result.push('\n');
|
||||
}
|
||||
return result;
|
||||
if let Some(window) = byte_line_window(content.as_bytes(), head_lines, tail_lines) {
|
||||
return String::from_utf8_lossy(window).into_owned();
|
||||
}
|
||||
|
||||
if let Some(max) = max_lines {
|
||||
@@ -185,6 +211,61 @@ fn apply_line_window(
|
||||
content.to_string()
|
||||
}
|
||||
|
||||
/// First `n` lines, sliced on byte offsets rather than round-tripped through
|
||||
/// `lines()`, so CRLF endings and an unterminated final line survive verbatim.
|
||||
/// `\n` is ASCII, so valid UTF-8 input also stays valid after slicing.
|
||||
fn head_window(content: &[u8], n: usize) -> &[u8] {
|
||||
if n == 0 {
|
||||
return &[];
|
||||
}
|
||||
let mut seen = 0;
|
||||
for (idx, &byte) in content.iter().enumerate() {
|
||||
if byte == b'\n' {
|
||||
seen += 1;
|
||||
if seen == n {
|
||||
return &content[..=idx];
|
||||
}
|
||||
}
|
||||
}
|
||||
content
|
||||
}
|
||||
|
||||
/// Last `n` lines, byte-sliced for the same fidelity reasons as `head_window`.
|
||||
/// A trailing newline terminates the final line instead of starting a new one,
|
||||
/// so it is excluded before counting separators backwards — otherwise `n` would
|
||||
/// select one line too few for newline-terminated input.
|
||||
fn tail_window(content: &[u8], n: usize) -> &[u8] {
|
||||
if n == 0 {
|
||||
return &[];
|
||||
}
|
||||
let search_end = match content.last() {
|
||||
Some(b'\n') => content.len() - 1,
|
||||
_ => content.len(),
|
||||
};
|
||||
let mut seen = 0;
|
||||
for idx in (0..search_end).rev() {
|
||||
if content[idx] == b'\n' {
|
||||
seen += 1;
|
||||
if seen == n {
|
||||
return &content[idx + 1..];
|
||||
}
|
||||
}
|
||||
}
|
||||
content
|
||||
}
|
||||
|
||||
fn byte_line_window(
|
||||
content: &[u8],
|
||||
head_lines: Option<usize>,
|
||||
tail_lines: Option<usize>,
|
||||
) -> Option<&[u8]> {
|
||||
if let Some(head) = head_lines {
|
||||
Some(head_window(content, head))
|
||||
} else {
|
||||
tail_lines.map(|tail| tail_window(content, tail))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -203,7 +284,7 @@ fn main() {{
|
||||
)?;
|
||||
|
||||
// Just verify it doesn't panic
|
||||
run(file.path(), FilterLevel::Minimal, None, None, false, 0)?;
|
||||
run(file.path(), FilterLevel::Minimal, None, None, None, false, 0)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -217,21 +298,180 @@ fn main() {{
|
||||
#[test]
|
||||
fn test_apply_line_window_tail_lines() {
|
||||
let input = "a\nb\nc\nd\n";
|
||||
let output = apply_line_window(input, None, Some(2), &Language::Unknown);
|
||||
let output = apply_line_window(input, None, None, Some(2), &Language::Unknown);
|
||||
assert_eq!(output, "c\nd\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_apply_line_window_tail_lines_no_trailing_newline() {
|
||||
let input = "a\nb\nc\nd";
|
||||
let output = apply_line_window(input, None, Some(2), &Language::Unknown);
|
||||
let output = apply_line_window(input, None, None, Some(2), &Language::Unknown);
|
||||
assert_eq!(output, "c\nd");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_head_window_matches_native_head() {
|
||||
let input = "1\n2\n3\n4\n5\n";
|
||||
assert_eq!(
|
||||
apply_line_window(input, None, Some(3), None, &Language::Unknown),
|
||||
"1\n2\n3\n"
|
||||
);
|
||||
}
|
||||
|
||||
/// The defect this window exists to fix: `--max-lines N` keeps only about
|
||||
/// N/2 lines, so it could never stand in for `head -N`.
|
||||
#[test]
|
||||
fn test_head_window_keeps_all_n_lines_unlike_max_lines() {
|
||||
let input = (1..=200)
|
||||
.map(|n| n.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
+ "\n";
|
||||
let head = apply_line_window(&input, None, Some(10), None, &Language::Unknown);
|
||||
assert_eq!(head.lines().count(), 10);
|
||||
assert_eq!(head.lines().last(), Some("10"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_head_window_single_line() {
|
||||
let input = "1\n2\n3\n";
|
||||
assert_eq!(
|
||||
apply_line_window(input, None, Some(1), None, &Language::Unknown),
|
||||
"1\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_head_window_zero_is_empty() {
|
||||
assert_eq!(
|
||||
apply_line_window("a\nb\n", None, Some(0), None, &Language::Unknown),
|
||||
""
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_head_window_n_exceeds_line_count() {
|
||||
let input = "a\nb\n";
|
||||
assert_eq!(
|
||||
apply_line_window(input, None, Some(99), None, &Language::Unknown),
|
||||
input
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_head_window_empty_input() {
|
||||
assert_eq!(apply_line_window("", None, Some(5), None, &Language::Unknown), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_head_window_unterminated_final_line() {
|
||||
assert_eq!(
|
||||
apply_line_window("a\nb\nc", None, Some(3), None, &Language::Unknown),
|
||||
"a\nb\nc"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_head_window_preserves_crlf() {
|
||||
assert_eq!(
|
||||
apply_line_window("a\r\nb\r\nc\r\n", None, Some(2), None, &Language::Unknown),
|
||||
"a\r\nb\r\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tail_window_preserves_crlf() {
|
||||
assert_eq!(
|
||||
apply_line_window("a\r\nb\r\nc\r\n", None, None, Some(2), &Language::Unknown),
|
||||
"b\r\nc\r\n"
|
||||
);
|
||||
}
|
||||
|
||||
/// Without discounting the terminal newline, counting separators backwards
|
||||
/// selects one line too few for newline-terminated input.
|
||||
#[test]
|
||||
fn test_tail_window_unterminated_single_line() {
|
||||
assert_eq!(
|
||||
apply_line_window("a\nb\nc", None, None, Some(1), &Language::Unknown),
|
||||
"c"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tail_window_n_exceeds_line_count() {
|
||||
let input = "a\nb\n";
|
||||
assert_eq!(
|
||||
apply_line_window(input, None, None, Some(99), &Language::Unknown),
|
||||
input
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tail_window_empty_input() {
|
||||
assert_eq!(apply_line_window("", None, None, Some(5), &Language::Unknown), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_max_lines_zero_is_empty() {
|
||||
assert_eq!(
|
||||
apply_line_window("a\nb\nc\n", Some(0), None, None, &Language::Unknown),
|
||||
""
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_head_window_mixed_line_endings() {
|
||||
assert_eq!(
|
||||
apply_line_window("a\r\nb\nc\r\n", None, Some(2), None, &Language::Unknown),
|
||||
"a\r\nb\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tail_window_mixed_line_endings() {
|
||||
assert_eq!(
|
||||
apply_line_window("a\r\nb\nc\r\n", None, None, Some(2), &Language::Unknown),
|
||||
"b\nc\r\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_windows_preserve_multibyte_utf8() {
|
||||
let input = "héllo\n日本語\nثالث\n";
|
||||
assert_eq!(
|
||||
apply_line_window(input, None, Some(2), None, &Language::Unknown),
|
||||
"héllo\n日本語\n"
|
||||
);
|
||||
assert_eq!(
|
||||
apply_line_window(input, None, None, Some(2), &Language::Unknown),
|
||||
"日本語\nثالث\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_windows_on_blank_lines_only() {
|
||||
assert_eq!(
|
||||
apply_line_window("\n\n\n", None, Some(2), None, &Language::Unknown),
|
||||
"\n\n"
|
||||
);
|
||||
assert_eq!(
|
||||
apply_line_window("\n\n\n", None, None, Some(2), &Language::Unknown),
|
||||
"\n\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tail_window_zero_is_empty() {
|
||||
assert_eq!(
|
||||
apply_line_window("a\nb\n", None, None, Some(0), &Language::Unknown),
|
||||
""
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_apply_line_window_max_lines_still_works() {
|
||||
let input = "a\nb\nc\nd\n";
|
||||
let output = apply_line_window(input, Some(2), None, &Language::Unknown);
|
||||
let output = apply_line_window(input, Some(2), None, None, &Language::Unknown);
|
||||
assert!(output.starts_with("a\n"));
|
||||
assert!(output.contains("more lines"));
|
||||
}
|
||||
|
||||
+7
-1
@@ -318,6 +318,12 @@ pub fn get_filter(level: FilterLevel) -> Box<dyn FilterStrategy> {
|
||||
}
|
||||
|
||||
pub fn smart_truncate(content: &str, max_lines: usize, _lang: &Language) -> String {
|
||||
// A zero budget shows nothing, matching `--tail-lines 0`/`--head-lines 0`.
|
||||
// Returning early also keeps `max_lines - 1` below from underflowing.
|
||||
if max_lines == 0 {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
let lines: Vec<&str> = content.lines().collect();
|
||||
if lines.len() <= max_lines {
|
||||
return content.to_string();
|
||||
@@ -346,7 +352,7 @@ pub fn smart_truncate(content: &str, max_lines: usize, _lang: &Language) -> Stri
|
||||
// Non-important lines beyond max_lines/2 are silently skipped —
|
||||
// no inline markers that could be mistaken for file content.
|
||||
|
||||
if kept_lines >= max_lines - 1 {
|
||||
if kept_lines + 1 >= max_lines {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
+294
-10
@@ -202,7 +202,7 @@ pub struct GainSummary {
|
||||
pub total_time_ms: u64,
|
||||
/// Average execution time per command (milliseconds)
|
||||
pub avg_time_ms: u64,
|
||||
/// Top 10 commands by tokens saved: (cmd, count, saved, avg_pct, avg_time_ms)
|
||||
/// Top 10 commands by tokens saved: (cmd, count, saved, weighted_rate, avg_time_ms)
|
||||
pub by_command: Vec<(String, usize, usize, f64, u64)>,
|
||||
/// Last 30 days of activity: (date, saved_tokens)
|
||||
pub by_day: Vec<(String, usize)>,
|
||||
@@ -295,7 +295,16 @@ pub struct MonthStats {
|
||||
pub avg_time_ms: u64,
|
||||
}
|
||||
|
||||
/// Type alias for command statistics tuple: (command, count, saved_tokens, avg_savings_pct, avg_time_ms)
|
||||
/// Type alias for command statistics tuple: (command, count, saved_tokens, weighted_savings_rate, avg_time_ms)
|
||||
///
|
||||
/// # Warning
|
||||
/// The 4th field is a **weighted** savings rate: `SUM(saved_tokens) / SUM(input_tokens) * 100.0`,
|
||||
/// guarded so that a group whose every row has zero input reports 0.0 rather than NULL.
|
||||
/// Do NOT aggregate this column with `AVG()` — that would produce an unweighted mean that
|
||||
/// under-weights high-volume commands. Always recompute it as
|
||||
/// `CASE WHEN SUM(input_tokens) > 0 THEN SUM(saved_tokens) / SUM(input_tokens) * 100.0 ELSE 0.0 END`
|
||||
/// instead. `saved_tokens` is signed, so the rate can be negative where the 3rd field, being
|
||||
/// unsigned, is clamped to 0.
|
||||
type CommandStats = (String, usize, usize, f64, u64);
|
||||
|
||||
/// Current tracking-DB schema version, stored in the SQLite `user_version` pragma.
|
||||
@@ -893,7 +902,9 @@ impl Tracker {
|
||||
) -> Result<Vec<CommandStats>> {
|
||||
let (project_exact, project_glob) = project_filter_params(project_path); // added
|
||||
let mut stmt = self.conn.prepare(
|
||||
"SELECT rtk_cmd, COUNT(*), SUM(saved_tokens), AVG(savings_pct), AVG(exec_time_ms)
|
||||
"SELECT rtk_cmd, COUNT(*), SUM(saved_tokens),
|
||||
CASE WHEN SUM(input_tokens) > 0 THEN SUM(saved_tokens) * 100.0 / SUM(input_tokens) ELSE 0.0 END,
|
||||
AVG(exec_time_ms)
|
||||
FROM commands
|
||||
WHERE (?1 IS NULL OR project_path = ?1 OR project_path GLOB ?2)
|
||||
GROUP BY rtk_cmd
|
||||
@@ -1312,12 +1323,21 @@ impl Tracker {
|
||||
}
|
||||
|
||||
/// Count commands with low savings (<30%) — filters that need improvement.
|
||||
///
|
||||
/// Uses the same weighted rate as `get_by_command`, `SUM(saved_tokens) / SUM(input_tokens)`
|
||||
/// over every call of the command, so that a handful of 0%-savings passthrough calls don't
|
||||
/// dilute a filter that genuinely performs well on high-volume invocations, and so that the
|
||||
/// figure sent here is the one `rtk gain` prints for the same command. A net-regressing
|
||||
/// command (negative rate) is listed: it is the filter most in need of improvement. Exact
|
||||
/// 0% is left out, `passthrough_top` already reports it, and a command whose calls never
|
||||
/// had any input carries no signal, so it is skipped rather than reported as 0%.
|
||||
pub fn low_savings_commands(&self, limit: usize) -> Result<Vec<(String, f64)>> {
|
||||
let mut stmt = self.conn.prepare(
|
||||
"SELECT rtk_cmd, AVG(savings_pct) as avg_sav FROM commands
|
||||
WHERE input_tokens > 0
|
||||
"SELECT rtk_cmd,
|
||||
SUM(saved_tokens) * 100.0 / SUM(input_tokens) AS sav
|
||||
FROM commands
|
||||
GROUP BY rtk_cmd
|
||||
HAVING avg_sav < 30.0 AND avg_sav > 0.0
|
||||
HAVING SUM(input_tokens) > 0 AND sav < 30.0 AND sav <> 0.0
|
||||
ORDER BY COUNT(*) DESC LIMIT ?1",
|
||||
)?;
|
||||
let rows = stmt.query_map(params![limit as i64], |row| {
|
||||
@@ -1329,7 +1349,15 @@ impl Tracker {
|
||||
Ok(rows.filter_map(|r| r.ok()).collect())
|
||||
}
|
||||
|
||||
/// Average savings percentage per command (unweighted — each command name counts once).
|
||||
/// Average savings percentage per command (unweighted across command names — each distinct
|
||||
/// command counts once, regardless of how many times it was invoked).
|
||||
///
|
||||
/// The *inner* rate per command is weighted by volume (`SUM(saved)/SUM(input)`) so that
|
||||
/// passthrough calls don't dilute a command's own rate. The *outer* average across command
|
||||
/// names stays unweighted — this is intentional: it gives equal weight to every filter
|
||||
/// instead of being dominated by the most-called one. Documented in `docs/TELEMETRY.md`.
|
||||
/// A command whose calls never had any input carries no signal about its filter and is
|
||||
/// skipped, not counted as 0%.
|
||||
///
|
||||
/// Keeps the honest signed value: a command whose filter consistently emits
|
||||
/// more than it saves yields a negative average, mirroring `overall_savings_pct`
|
||||
@@ -1338,10 +1366,12 @@ impl Tracker {
|
||||
/// not on a `0..=100` floor.
|
||||
pub fn avg_savings_per_command(&self) -> Result<f64> {
|
||||
let avg: f64 = self.conn.query_row(
|
||||
"SELECT COALESCE(AVG(avg_sav), 0.0) FROM (
|
||||
SELECT rtk_cmd, AVG(savings_pct) as avg_sav
|
||||
FROM commands WHERE input_tokens > 0
|
||||
"SELECT COALESCE(AVG(cmd_rate), 0.0) FROM (
|
||||
SELECT rtk_cmd,
|
||||
SUM(saved_tokens) * 100.0 / SUM(input_tokens) AS cmd_rate
|
||||
FROM commands
|
||||
GROUP BY rtk_cmd
|
||||
HAVING SUM(input_tokens) > 0
|
||||
)",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
@@ -2535,4 +2565,258 @@ mod tests {
|
||||
assert_eq!(categorize_command(cmd), "js", "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
// 14. get_by_command uses weighted savings rate, not unweighted average
|
||||
//
|
||||
// Regression test for: AVG(savings_pct) gave wrong results when small invocations
|
||||
// with 0% savings diluted the average of high-volume commands.
|
||||
//
|
||||
// Setup: one small command (10% savings) + one large command (95% savings).
|
||||
// Unweighted avg would be ~52.5%. Weighted rate must be ~95%.
|
||||
//
|
||||
// Rows carry a project path so the project-filtered form of the query is the one
|
||||
// under test.
|
||||
#[test]
|
||||
fn test_get_by_command_weighted_savings_rate() {
|
||||
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
|
||||
let cmd_name = "weighted_test";
|
||||
let project = "/tmp/rtk_weighted_test";
|
||||
|
||||
// Override project_path by inserting directly via conn
|
||||
let saved_small = 10_i64; // 100 in - 90 out = 10 saved → 10%
|
||||
let saved_large = 95_000_i64; // 100_000 in - 5_000 out = 95_000 saved → 95%
|
||||
tracker
|
||||
.conn
|
||||
.execute(
|
||||
"INSERT INTO commands (timestamp, original_cmd, rtk_cmd, project_path, input_tokens, output_tokens, saved_tokens, savings_pct, exec_time_ms)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
|
||||
rusqlite::params![
|
||||
chrono::Utc::now().to_rfc3339(),
|
||||
cmd_name, cmd_name, project,
|
||||
100_i64, 90_i64, saved_small, 10.0_f64, 5_i64
|
||||
],
|
||||
)
|
||||
.expect("Failed to insert small invocation");
|
||||
tracker
|
||||
.conn
|
||||
.execute(
|
||||
"INSERT INTO commands (timestamp, original_cmd, rtk_cmd, project_path, input_tokens, output_tokens, saved_tokens, savings_pct, exec_time_ms)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
|
||||
rusqlite::params![
|
||||
chrono::Utc::now().to_rfc3339(),
|
||||
cmd_name, cmd_name, project,
|
||||
100_000_i64, 5_000_i64, saved_large, 95.0_f64, 10_i64
|
||||
],
|
||||
)
|
||||
.expect("Failed to insert large invocation");
|
||||
|
||||
let by_cmd = tracker
|
||||
.get_by_command(Some(project))
|
||||
.expect("Failed to get by_command stats");
|
||||
|
||||
let entry = by_cmd
|
||||
.iter()
|
||||
.find(|(name, _, _, _, _)| name == cmd_name)
|
||||
.expect("Test command not found in by_command stats");
|
||||
|
||||
let (_name, _count, _saved, rate, _time) = entry;
|
||||
|
||||
// Weighted rate = (10 + 95_000) / (100 + 100_000) * 100.0 ≈ 94.9%
|
||||
// Unweighted avg would be (10.0 + 95.0) / 2 = 52.5%
|
||||
// The gap proves the fix works.
|
||||
assert!(
|
||||
*rate > 90.0,
|
||||
"Expected weighted rate >90%, got {:.1}% — unweighted avg would be ~52.5%",
|
||||
rate
|
||||
);
|
||||
}
|
||||
|
||||
// 15. The weighted rate tracks SUM(saved_tokens), not the mean of per-call percentages
|
||||
//
|
||||
// A long-tailed pair under one rtk_cmd: a 1M-token call saving 90% and a 100-token
|
||||
// call saving 10%. The mean of the two percentages is 50%; the weighted rate is
|
||||
// ~89.99% and is the figure consistent with the Saved column in the same row.
|
||||
#[test]
|
||||
fn test_weighted_rate_via_get_by_command() {
|
||||
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
|
||||
|
||||
tracker
|
||||
.record("grep huge", "rtk grep", 1_000_000, 100_000, 50)
|
||||
.expect("record huge");
|
||||
tracker
|
||||
.record("grep tiny", "rtk grep", 100, 90, 5)
|
||||
.expect("record tiny");
|
||||
|
||||
let by_command = tracker.get_by_command(None).expect("get_by_command");
|
||||
|
||||
let (_cmd, count, saved, pct, _avg_time) = by_command
|
||||
.iter()
|
||||
.find(|(cmd, ..)| cmd == "rtk grep")
|
||||
.expect("rtk grep row not found");
|
||||
|
||||
assert_eq!(*count, 2);
|
||||
assert_eq!(*saved, 900_010);
|
||||
let expected = 900_010.0 / 1_000_100.0 * 100.0;
|
||||
assert!(
|
||||
(pct - expected).abs() < 0.01,
|
||||
"expected weighted rate ~{expected:.2}, got {pct:.2}"
|
||||
);
|
||||
assert!(
|
||||
(pct - 50.0).abs() > 1.0,
|
||||
"mean-of-percentages regression: got {pct:.2}"
|
||||
);
|
||||
}
|
||||
|
||||
// 16. The rate reaches the gain summary through get_summary(), not only get_by_command
|
||||
#[test]
|
||||
fn test_weighted_rate_via_get_summary() {
|
||||
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
|
||||
|
||||
tracker
|
||||
.record("large grep", "rtk grep", 1000, 100, 10)
|
||||
.expect("Failed to record large command");
|
||||
tracker
|
||||
.record("small grep", "rtk grep", 10, 9, 20)
|
||||
.expect("Failed to record small command");
|
||||
|
||||
let summary = tracker.get_summary().expect("Failed to get summary");
|
||||
let (_, count, saved, savings_pct, _) = summary
|
||||
.by_command
|
||||
.iter()
|
||||
.find(|(command, _, _, _, _)| command == "rtk grep")
|
||||
.expect("rtk grep stats not found");
|
||||
|
||||
assert_eq!(*count, 2);
|
||||
assert_eq!(*saved, 901);
|
||||
let expected_pct = 901.0 / 1010.0 * 100.0;
|
||||
assert!(
|
||||
(savings_pct - expected_pct).abs() < 1e-10,
|
||||
"expected weighted rate {expected_pct}, got {savings_pct}"
|
||||
);
|
||||
}
|
||||
|
||||
// 17. A group whose every call has zero input reports 0%, not a division by zero
|
||||
#[test]
|
||||
fn test_by_command_zero_input_has_zero_savings_percentage() {
|
||||
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
|
||||
tracker
|
||||
.record("interactive command", "rtk proxy", 0, 0, 5)
|
||||
.expect("Failed to record passthrough command");
|
||||
|
||||
let summary = tracker.get_summary().expect("Failed to get summary");
|
||||
let (_, _, _, savings_pct, _) = summary
|
||||
.by_command
|
||||
.iter()
|
||||
.find(|(command, _, _, _, _)| command == "rtk proxy")
|
||||
.expect("rtk proxy stats not found");
|
||||
|
||||
assert_eq!(*savings_pct, 0.0);
|
||||
}
|
||||
|
||||
// 18. low_savings_commands reports the same weighted rate as the `rtk gain` By Command
|
||||
// table, including net-regressing commands, and nothing for commands without input.
|
||||
//
|
||||
// `rtk ls -R`: one 95% call plus four 0% passthrough calls. Unweighted AVG(savings_pct)
|
||||
// over those five rows is 19%, under the 30% threshold, so the command would reach
|
||||
// telemetry as low-savings while `get_by_command` shows it at ~94.6% in the same
|
||||
// `rtk gain` run. Weighted, 95_000 / 100_400 ≈ 94.6%: not listed.
|
||||
// `rtk grep`: 25% on one call, then a call with no input that still printed 10 tokens.
|
||||
// Every row counts, as in `get_by_command`: (250 - 10) / 1_000 = 24%, listed at 24.
|
||||
// `rtk read`: emits more than it saves, -50%. Listed: it is the filter to fix first.
|
||||
// `rtk proxy`: never had any input. Nothing to say about its filter, not listed.
|
||||
#[test]
|
||||
fn test_low_savings_commands_matches_gain_weighted_rate() {
|
||||
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
|
||||
tracker
|
||||
.record("ls -R big", "rtk ls -R", 100_000, 5_000, 10)
|
||||
.expect("record big call");
|
||||
for _ in 0..4 {
|
||||
tracker
|
||||
.record("ls -R empty", "rtk ls -R", 100, 100, 5)
|
||||
.expect("record passthrough call");
|
||||
}
|
||||
tracker
|
||||
.record("grep x", "rtk grep", 1_000, 750, 5)
|
||||
.expect("record 25% call");
|
||||
tracker
|
||||
.record("grep none", "rtk grep", 0, 10, 5)
|
||||
.expect("record no-input call");
|
||||
tracker
|
||||
.record("read big.json", "rtk read", 100, 150, 5)
|
||||
.expect("record regressing call");
|
||||
tracker
|
||||
.record("interactive", "rtk proxy", 0, 0, 5)
|
||||
.expect("record zero-input call");
|
||||
|
||||
let low = tracker
|
||||
.low_savings_commands(10)
|
||||
.expect("low_savings_commands");
|
||||
let listed: Vec<(&str, f64)> = low.iter().map(|(n, r)| (n.as_str(), *r)).collect();
|
||||
assert_eq!(
|
||||
listed.len(),
|
||||
2,
|
||||
"expected `rtk grep` (24%) and `rtk read` (-50%); ~94.6% weighted must not be \
|
||||
listed (unweighted AVG(savings_pct) would put it at 19%), got {listed:?}"
|
||||
);
|
||||
assert_eq!(listed[0].0, "rtk grep");
|
||||
assert!((listed[0].1 - 24.0).abs() < 1e-9, "got {listed:?}");
|
||||
assert_eq!(listed[1].0, "rtk read");
|
||||
assert!((listed[1].1 - (-50.0)).abs() < 1e-9, "got {listed:?}");
|
||||
|
||||
// The figure sent to telemetry is the one `rtk gain` prints for the same command.
|
||||
let summary = tracker.get_summary().expect("get_summary");
|
||||
for (name, rate) in &low {
|
||||
let (_, _, _, gain_rate, _) = summary
|
||||
.by_command
|
||||
.iter()
|
||||
.find(|(command, _, _, _, _)| command == name)
|
||||
.unwrap_or_else(|| panic!("{name} missing from by_command"));
|
||||
assert!(
|
||||
(gain_rate - rate).abs() < 1e-9,
|
||||
"{name}: telemetry says {rate}, rtk gain says {gain_rate}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 19. avg_savings_per_command weights each command's own rate by volume (every call
|
||||
// counted, as in test 18), then averages the per-command rates without weighting: each
|
||||
// command name counts once, and a command that never had any input is not counted.
|
||||
//
|
||||
// Same rows as test 18: `rtk ls -R` ≈ 94.6% (19% if the inner aggregate were
|
||||
// AVG(savings_pct)), `rtk grep` 24%, `rtk read` -50%, `rtk proxy` skipped.
|
||||
#[test]
|
||||
fn test_avg_savings_per_command_inner_rate_is_weighted() {
|
||||
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
|
||||
tracker
|
||||
.record("ls -R big", "rtk ls -R", 100_000, 5_000, 10)
|
||||
.expect("record big call");
|
||||
for _ in 0..4 {
|
||||
tracker
|
||||
.record("ls -R empty", "rtk ls -R", 100, 100, 5)
|
||||
.expect("record passthrough call");
|
||||
}
|
||||
tracker
|
||||
.record("grep x", "rtk grep", 1_000, 750, 5)
|
||||
.expect("record 25% call");
|
||||
tracker
|
||||
.record("grep none", "rtk grep", 0, 10, 5)
|
||||
.expect("record no-input call");
|
||||
tracker
|
||||
.record("read big.json", "rtk read", 100, 150, 5)
|
||||
.expect("record regressing call");
|
||||
tracker
|
||||
.record("interactive", "rtk proxy", 0, 0, 5)
|
||||
.expect("record zero-input call");
|
||||
|
||||
let avg = tracker
|
||||
.avg_savings_per_command()
|
||||
.expect("avg_savings_per_command");
|
||||
let ls_rate = 95_000.0 * 100.0 / 100_400.0;
|
||||
let expected = (ls_rate + 24.0 - 50.0) / 3.0;
|
||||
assert!(
|
||||
(avg - expected).abs() < 1e-6,
|
||||
"expected ({ls_rate:.1} + 24 - 50) / 3 = {expected:.1}%, got {avg:.1}% \
|
||||
(an unweighted inner AVG(savings_pct) would give (19 + 12.5 - 50) / 3 = -6.2%)"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@ When a hook sends `cargo fmt --all && cargo test 2>&1 | tail -20`:
|
||||
**Per-segment rewriting** — Each segment goes through:
|
||||
|
||||
1. Strip trailing redirects (`2>&1`, `>/dev/null`) — matched via lexer tokens, set aside, re-appended after rewriting
|
||||
2. Short-circuit special cases — `head -20 file` → `rtk read file --max-lines 20`, `tail -n 5 file` → `rtk read file --tail-lines 5`. These can't go through generic prefix replacement because it would produce `rtk read -20 file` (wrong flag position)
|
||||
2. Short-circuit special cases — `head -20 file` → `rtk read file --head-lines 20`, `tail -n 5 file` → `rtk read file --tail-lines 5`. These can't go through generic prefix replacement because it would produce `rtk read -20 file` (wrong flag position)
|
||||
3. Classify the command — strip env prefixes (`FOO="bar baz"`), normalize paths (`/usr/bin/grep` → `grep`), strip git global opts (`git -C /tmp` → `git`), then match against 60+ regex patterns from `rules.rs`
|
||||
4. Apply the rewrite — find the matching rule, replace the command prefix with `rtk <cmd>`, re-prepend the env prefix, re-append the redirect suffix
|
||||
|
||||
|
||||
+264
-15
@@ -80,10 +80,67 @@ static GIT_GLOBAL_OPT: LazyLock<Regex> = LazyLock::new(|| {
|
||||
// Issue #1362: each capture expects a SINGLE file argument (`\S+$`). Multi-file
|
||||
// invocations like `head -3 a b c` fail to match so the segment is passed through
|
||||
// to the native `head`/`tail` binary — which already handles multi-file with
|
||||
// `==> name <==` banners that `rtk read --max-lines` cannot reproduce.
|
||||
// `==> name <==` banners that a single `rtk read` window cannot reproduce.
|
||||
static HEAD_N: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^head\s+-(\d+)\s+(\S+)$").unwrap());
|
||||
static HEAD_LINES: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"^head\s+--lines=(\d+)\s+(\S+)$").unwrap());
|
||||
// `-n N` and `--lines N` are the spellings `tail` already accepted below; `head`
|
||||
// silently fell through to no rewrite at all without them.
|
||||
static HEAD_N_SPACE: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"^head\s+-n\s+(\d+)\s+(\S+)$").unwrap());
|
||||
static HEAD_LINES_SPACE: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"^head\s+--lines\s+(\d+)\s+(\S+)$").unwrap());
|
||||
// Bare `head FILE` means ten lines, not the whole file. Restricted to a single
|
||||
// operand: multi-file and optioned forms stay with the native binary.
|
||||
static HEAD_BARE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^head\s+(\S+)$").unwrap());
|
||||
|
||||
/// Re-attach a trailing redirect to a rewritten head/tail command.
|
||||
///
|
||||
/// `head -n 1 f>out` strips to a suffix with no leading space, and these
|
||||
/// rewrites end in a bare number, so plain concatenation yields
|
||||
/// `--head-lines 1>out` — which the shell reads as an fd-1 redirect, leaving
|
||||
/// `--head-lines` with no value. A separating space keeps the flag intact.
|
||||
///
|
||||
/// Deliberately not applied to the shared prefix rewrites: those keep the
|
||||
/// original argument/redirect boundary, where inserting a space could split a
|
||||
/// descriptor-duplication form such as `1>&2` and demote the descriptor number
|
||||
/// into an argument.
|
||||
fn join_redirect_suffix(rewritten: &str, redirect_suffix: &str) -> String {
|
||||
if redirect_suffix.is_empty() || redirect_suffix.starts_with(char::is_whitespace) {
|
||||
format!("{}{}", rewritten, redirect_suffix)
|
||||
} else {
|
||||
format!("{} {}", rewritten, redirect_suffix)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an operand is safe to hand to `rtk read` as one concrete file.
|
||||
///
|
||||
/// One whitespace-delimited token is not one shell operand: `*.rs`, `{a,b}` and
|
||||
/// `$FILES` each expand to several at execution time, and `rtk read`
|
||||
/// concatenates files where `head`/`tail` print `==> name <==` banners.
|
||||
///
|
||||
/// The token is raw shell source, not the argument the callee receives, so
|
||||
/// character-class blocklists kept missing cases: `'--'` and `\--help` hide an
|
||||
/// option behind a quote or backslash, and a leading `#` opens a comment that
|
||||
/// swallows the flags this rewrite appends. Hence an allowlist: only characters
|
||||
/// that cannot change the operand's word count or turn it into an option are
|
||||
/// accepted, and anything else is left to the native binary. `~` is the one
|
||||
/// shell-active character kept, because tilde expansion yields exactly one word
|
||||
/// and the operand is passed through unchanged. Unicode alphanumerics stay
|
||||
/// eligible so non-ASCII filenames still route.
|
||||
///
|
||||
/// The cost is deliberate: a quoted literal like `'literal*.txt'` also stays
|
||||
/// native even though the quoting would prevent expansion. Losing a rewrite is
|
||||
/// recoverable; changing what the user's command does is not.
|
||||
fn is_single_file_operand(operand: &str) -> bool {
|
||||
if operand.is_empty() || operand.starts_with('-') {
|
||||
return false;
|
||||
}
|
||||
operand.chars().all(|c| {
|
||||
c.is_alphanumeric()
|
||||
|| matches!(c, '.' | '_' | '/' | '-' | '~' | '+' | '@' | ':' | ',' | '=')
|
||||
})
|
||||
}
|
||||
static TAIL_N: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^tail\s+-(\d+)\s+(\S+)$").unwrap());
|
||||
static TAIL_N_SPACE: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"^tail\s+-n\s+(\d+)\s+(\S+)$").unwrap());
|
||||
@@ -1242,14 +1299,23 @@ fn rewrite_compound(
|
||||
}
|
||||
|
||||
fn rewrite_line_range(cmd: &str) -> Option<String> {
|
||||
for re in [&*HEAD_N, &*HEAD_LINES] {
|
||||
for re in [&*HEAD_N, &*HEAD_LINES, &*HEAD_N_SPACE, &*HEAD_LINES_SPACE] {
|
||||
if let Some(caps) = re.captures(cmd) {
|
||||
let n = caps.get(1)?.as_str();
|
||||
let file = caps.get(2)?.as_str();
|
||||
return Some(format!("rtk read {} --max-lines {}", file, n));
|
||||
if is_single_file_operand(file) {
|
||||
return Some(format!("rtk read {} --head-lines {}", file, n));
|
||||
}
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if cmd.starts_with("head -") {
|
||||
if let Some(caps) = HEAD_BARE.captures(cmd) {
|
||||
let file = caps.get(1)?.as_str();
|
||||
if is_single_file_operand(file) {
|
||||
return Some(format!("rtk read {} --head-lines 10", file));
|
||||
}
|
||||
}
|
||||
if cmd.starts_with("head") {
|
||||
return None;
|
||||
}
|
||||
for re in [
|
||||
@@ -1261,7 +1327,10 @@ fn rewrite_line_range(cmd: &str) -> Option<String> {
|
||||
if let Some(caps) = re.captures(cmd) {
|
||||
let n = caps.get(1)?.as_str();
|
||||
let file = caps.get(2)?.as_str();
|
||||
return Some(format!("rtk read {} --tail-lines {}", file, n));
|
||||
if is_single_file_operand(file) {
|
||||
return Some(format!("rtk read {} --tail-lines {}", file, n));
|
||||
}
|
||||
return None;
|
||||
}
|
||||
}
|
||||
None
|
||||
@@ -1578,7 +1647,7 @@ fn rewrite_segment_inner(
|
||||
}
|
||||
|
||||
if context == RewriteContext::Normal
|
||||
&& (cmd_part.starts_with("head -") || cmd_part.starts_with("tail "))
|
||||
&& (cmd_part.starts_with("head ") || cmd_part.starts_with("tail "))
|
||||
{
|
||||
// head/tail rewrite to `rtk read`, so honour exclude_commands here too:
|
||||
// this branch returns before the checks below. Any env prefix has already
|
||||
@@ -1586,7 +1655,7 @@ fn rewrite_segment_inner(
|
||||
if is_excluded(cmd_part, excluded) {
|
||||
return None;
|
||||
}
|
||||
return rewrite_line_range(cmd_part).map(|r| format!("{}{}", r, redirect_suffix));
|
||||
return rewrite_line_range(cmd_part).map(|r| join_redirect_suffix(&r, redirect_suffix));
|
||||
}
|
||||
|
||||
// Most cat flags (-v, -A, -e, -t, -s, -b, --show-all, etc.) have different
|
||||
@@ -2417,6 +2486,7 @@ mod tests {
|
||||
assert_eq!(
|
||||
safe_rules,
|
||||
vec![
|
||||
"rtk ast-grep",
|
||||
"rtk brew",
|
||||
"rtk bundle",
|
||||
"rtk cargo",
|
||||
@@ -3831,7 +3901,7 @@ mod tests {
|
||||
// A non-excluded inner command still rewrites through the wrapper.
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("uv run head -20 src/main.rs", &["cat".to_string()]),
|
||||
Some("uv run rtk read src/main.rs --max-lines 20".into())
|
||||
Some("uv run rtk read src/main.rs --head-lines 20".into())
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3839,33 +3909,211 @@ mod tests {
|
||||
fn test_head_tail_rewrite_when_not_excluded() {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("head -20 src/main.rs", &["cat".to_string()]),
|
||||
Some("rtk read src/main.rs --max-lines 20".into())
|
||||
Some("rtk read src/main.rs --head-lines 20".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_head_numeric_flag() {
|
||||
// head -20 file → rtk read file --max-lines 20 (not rtk read -20 file)
|
||||
// head -20 file → rtk read file --head-lines 20 (not rtk read -20 file)
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("head -20 src/main.rs", &[]),
|
||||
Some("rtk read src/main.rs --max-lines 20".into())
|
||||
Some("rtk read src/main.rs --head-lines 20".into())
|
||||
);
|
||||
}
|
||||
|
||||
/// A single token that the shell expands into several operands must stay
|
||||
/// native: `rtk read` concatenates files, losing `head`'s `==> name <==`
|
||||
/// banners. Covers the newly added `-n N` / `--lines N` routes, which had
|
||||
/// no matcher at all before and so were native by accident.
|
||||
#[test]
|
||||
fn test_rewrite_head_expanding_operand_stays_native() {
|
||||
for cmd in [
|
||||
"head src/core/*.rs",
|
||||
"head -1 src/core/*.rs",
|
||||
"head -n 1 src/core/*.rs",
|
||||
"head --lines 1 src/core/*.rs",
|
||||
"head --lines=1 src/core/*.rs",
|
||||
"head -n 1 src/core/{a,b}.rs",
|
||||
"head -n 1 $FILES",
|
||||
"head -n 1 src/core/?.rs",
|
||||
] {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes(cmd, &[]),
|
||||
None,
|
||||
"expanding operand must stay native: {}",
|
||||
cmd
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `head -n 1 --help` must reach `head`, not print `rtk read`'s help. The
|
||||
/// quoted and escaped spellings matter as much as the bare one: the matcher
|
||||
/// sees shell source, so `'--'` and `\--help` slip past a leading-`-` test
|
||||
/// while still reaching the tool as options.
|
||||
#[test]
|
||||
fn test_rewrite_head_option_operand_stays_native() {
|
||||
for cmd in [
|
||||
"head -n 1 --help",
|
||||
"head --lines 1 --version",
|
||||
"head --help",
|
||||
"head -n 1 '--'",
|
||||
"head -n 1 \"--\"",
|
||||
"head -n 1 '--help'",
|
||||
"head -n 1 \"--help\"",
|
||||
"head -n 1 \\--help",
|
||||
"head '--'",
|
||||
"head -n 1 #comment",
|
||||
"head #comment",
|
||||
"head -n 1 a|b",
|
||||
"head -n 1 (x)",
|
||||
] {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes(cmd, &[]),
|
||||
None,
|
||||
"option-like operand must stay native: {}",
|
||||
cmd
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The same expansion hazard applied to `tail`, which shared the code path.
|
||||
#[test]
|
||||
fn test_rewrite_tail_expanding_operand_stays_native() {
|
||||
for cmd in [
|
||||
"tail -20 src/core/*.rs",
|
||||
"tail -n 20 src/core/*.rs",
|
||||
"tail --lines 20 $FILES",
|
||||
"tail -n 1 '--'",
|
||||
"tail -n 1 \\--help",
|
||||
"tail -n 1 #comment",
|
||||
] {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes(cmd, &[]),
|
||||
None,
|
||||
"expanding operand must stay native: {}",
|
||||
cmd
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `;` and `&` are operators the lexer splits on before the operand is ever
|
||||
/// examined, so the trailing text is a separate command and the real operand
|
||||
/// is just `f`. These rewrite, and should: the allowlist only has to judge
|
||||
/// characters that survive segmentation.
|
||||
#[test]
|
||||
fn test_rewrite_head_operand_after_operator_split() {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("head -n 1 f;rm", &[]),
|
||||
Some("rtk read f --head-lines 1; rm".into())
|
||||
);
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("head -n 1 a&b", &[]),
|
||||
Some("rtk read a --head-lines 1 & b".into())
|
||||
);
|
||||
}
|
||||
|
||||
/// A trailing redirect is stripped before the operand is judged, so `a>b`
|
||||
/// rewrites with operand `a` — but the suffix must not fuse onto the numeric
|
||||
/// flag value, or the shell reads `1>b` as an fd-1 redirect and
|
||||
/// `--head-lines` loses its argument.
|
||||
#[test]
|
||||
fn test_rewrite_head_redirect_suffix_keeps_flag_value() {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("head -n 1 a>b", &[]),
|
||||
Some("rtk read a --head-lines 1 >b".into())
|
||||
);
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("tail -n 1 a>b", &[]),
|
||||
Some("rtk read a --tail-lines 1 >b".into())
|
||||
);
|
||||
// An already-spaced suffix must not gain a second space.
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("head -n 1 a > b", &[]),
|
||||
Some("rtk read a --head-lines 1 > b".into())
|
||||
);
|
||||
}
|
||||
|
||||
/// Shapes the allowlist must keep accepting, including a non-ASCII name.
|
||||
#[test]
|
||||
fn test_rewrite_head_accepts_ordinary_paths() {
|
||||
for (cmd, want) in [
|
||||
(
|
||||
"head -10 /tmp/seq.txt",
|
||||
"rtk read /tmp/seq.txt --head-lines 10",
|
||||
),
|
||||
("head ./a-b_c.txt", "rtk read ./a-b_c.txt --head-lines 10"),
|
||||
("head ~/x.txt", "rtk read ~/x.txt --head-lines 10"),
|
||||
(
|
||||
"head /tmp/a.b.c-d_e.txt",
|
||||
"rtk read /tmp/a.b.c-d_e.txt --head-lines 10",
|
||||
),
|
||||
(
|
||||
"head src/日本語.rs",
|
||||
"rtk read src/日本語.rs --head-lines 10",
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes(cmd, &[]),
|
||||
Some(want.into()),
|
||||
"must still rewrite: {}",
|
||||
cmd
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_tail_plain_operand_still_rewrites() {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("tail -20 src/main.rs", &[]),
|
||||
Some("rtk read src/main.rs --tail-lines 20".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_head_n_space_flag() {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("head -n 50 src/lib.rs", &[]),
|
||||
Some("rtk read src/lib.rs --head-lines 50".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_head_lines_space_flag() {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("head --lines 50 src/lib.rs", &[]),
|
||||
Some("rtk read src/lib.rs --head-lines 50".into())
|
||||
);
|
||||
}
|
||||
|
||||
/// Multi-file and optioned bare forms stay native: the rewrite emits one
|
||||
/// path (see `is_single_file_operand`), and `head` prints `==> name <==`
|
||||
/// banners for several files, which a concatenated read cannot reproduce.
|
||||
#[test]
|
||||
fn test_rewrite_head_bare_multifile_stays_native() {
|
||||
assert_eq!(rewrite_command_no_prefixes("head a.txt b.txt", &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_head_unsupported_option_stays_native() {
|
||||
assert_eq!(rewrite_command_no_prefixes("head -c 10 f.bin", &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_head_lines_long_flag() {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("head --lines=50 src/lib.rs", &[]),
|
||||
Some("rtk read src/lib.rs --max-lines 50".into())
|
||||
Some("rtk read src/lib.rs --head-lines 50".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_head_no_flag_still_rewrites() {
|
||||
// plain `head file` → `rtk read file` (no numeric flag)
|
||||
// plain `head file` means ten lines, so the rewrite must bound the read
|
||||
// rather than dumping the whole file.
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("head src/main.rs", &[]),
|
||||
Some("rtk read src/main.rs".into())
|
||||
Some("rtk read src/main.rs --head-lines 10".into())
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3925,7 +4173,8 @@ mod tests {
|
||||
|
||||
// --- Issue #1362: head/tail with multiple files falls back to native command ---
|
||||
//
|
||||
// `rtk read <file> --max-lines N` only accepts a single positional file path in
|
||||
// The head/tail rewrite emits a single positional path (see
|
||||
// `is_single_file_operand`), even though `rtk read` itself accepts several, in
|
||||
// a shape that maps cleanly to `head -N`. Rewriting `head -N a b c` to
|
||||
// `rtk read a b c --max-lines N` previously produced a command where `rtk read`
|
||||
// would concatenate the files without the `==> name <==` banners that native
|
||||
|
||||
@@ -147,6 +147,18 @@ pub const RULES: &[RtkRule] = &[
|
||||
savings_pct: 75.0,
|
||||
..RtkRule::DEFAULT
|
||||
},
|
||||
RtkRule {
|
||||
pattern: r"^ast-grep\s+",
|
||||
rtk_cmd: "rtk ast-grep",
|
||||
// Unlike grep/rg, `rtk ast-grep`'s run() execs with stdin null (no
|
||||
// piped-stdin support yet), so it must not be rewritten as a
|
||||
// pipeline's final stage — that would silently drop the pipe input.
|
||||
pipeline_safety: PipelineSafety::ProducerOnly,
|
||||
rewrite_prefixes: &["ast-grep"],
|
||||
category: "Files",
|
||||
savings_pct: 85.0,
|
||||
..RtkRule::DEFAULT
|
||||
},
|
||||
RtkRule {
|
||||
pattern: r"^ls(\s|$)",
|
||||
rtk_cmd: "rtk ls",
|
||||
|
||||
+35
-8
@@ -24,8 +24,8 @@ use cmds::ruby::{rake_cmd, rspec_cmd, rubocop_cmd};
|
||||
use cmds::rust::{cargo_cmd, runner};
|
||||
use cmds::scala::sbt_cmd;
|
||||
use cmds::system::{
|
||||
ctest_cmd, deps, env_cmd, find_cmd, format_cmd, json_cmd, local_llm, log_cmd, ls, pipe_cmd,
|
||||
read, search, summary, tree, wc_cmd,
|
||||
ast_grep_cmd, ctest_cmd, deps, env_cmd, find_cmd, format_cmd, json_cmd, local_llm, log_cmd, ls,
|
||||
pipe_cmd, read, search, summary, tree, wc_cmd,
|
||||
};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
@@ -111,11 +111,16 @@ enum Commands {
|
||||
/// Filter: none (default, full content), minimal, aggressive
|
||||
#[arg(short, long, default_value = "none")]
|
||||
level: core::filter::FilterLevel,
|
||||
/// Max lines
|
||||
#[arg(short, long, conflicts_with = "tail_lines")]
|
||||
/// Structural preview capped at N lines (keeps signatures and imports;
|
||||
/// not the first N lines — use --head-lines for that)
|
||||
#[arg(short, long, conflicts_with_all = ["head_lines", "tail_lines"])]
|
||||
max_lines: Option<usize>,
|
||||
/// Keep only the first N lines (byte-exact at the default --level none
|
||||
/// with -n off; --level and -n still transform the window)
|
||||
#[arg(long, conflicts_with_all = ["max_lines", "tail_lines"])]
|
||||
head_lines: Option<usize>,
|
||||
/// Keep only last N lines
|
||||
#[arg(long, conflicts_with = "max_lines")]
|
||||
#[arg(long, conflicts_with_all = ["max_lines", "head_lines"])]
|
||||
tail_lines: Option<usize>,
|
||||
/// Show line numbers
|
||||
#[arg(short = 'n', long)]
|
||||
@@ -355,6 +360,13 @@ enum Commands {
|
||||
extra_args: Vec<String>,
|
||||
},
|
||||
|
||||
/// Compact ast-grep - runs ast-grep natively, groups matches by file
|
||||
AstGrep {
|
||||
/// ast-grep subcommand, pattern, path, and any flags (e.g. run -p '$$$', --json)
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
extra_args: Vec<String>,
|
||||
},
|
||||
|
||||
/// Initialize rtk instructions for assistant CLI usage
|
||||
Init {
|
||||
/// Add to global assistant config directory instead of local project file
|
||||
@@ -1850,8 +1862,11 @@ fn run_cli() -> Result<i32> {
|
||||
};
|
||||
|
||||
// Warn if installed hook is outdated/missing (1/day, non-blocking).
|
||||
// Skip for Gain — it shows its own inline hook warning.
|
||||
if !matches!(cli.command, Commands::Gain { .. }) {
|
||||
// Skip for Gain (shows its own inline warning), Init/Verify (manage the hook themselves).
|
||||
if !matches!(
|
||||
cli.command,
|
||||
Commands::Gain { .. } | Commands::Init { .. } | Commands::Verify { .. }
|
||||
) {
|
||||
hooks::hook_check::maybe_warn();
|
||||
}
|
||||
|
||||
@@ -1872,6 +1887,7 @@ fn run_cli() -> Result<i32> {
|
||||
files,
|
||||
level,
|
||||
max_lines,
|
||||
head_lines,
|
||||
tail_lines,
|
||||
line_numbers,
|
||||
} => {
|
||||
@@ -1884,12 +1900,20 @@ fn run_cli() -> Result<i32> {
|
||||
continue;
|
||||
}
|
||||
stdin_seen = true;
|
||||
read::run_stdin(level, max_lines, tail_lines, line_numbers, cli.verbose)
|
||||
read::run_stdin(
|
||||
level,
|
||||
max_lines,
|
||||
head_lines,
|
||||
tail_lines,
|
||||
line_numbers,
|
||||
cli.verbose,
|
||||
)
|
||||
} else {
|
||||
read::run(
|
||||
file,
|
||||
level,
|
||||
max_lines,
|
||||
head_lines,
|
||||
tail_lines,
|
||||
line_numbers,
|
||||
cli.verbose,
|
||||
@@ -2250,6 +2274,7 @@ fn run_cli() -> Result<i32> {
|
||||
&extra_args,
|
||||
cli.verbose,
|
||||
)?,
|
||||
Commands::AstGrep { extra_args } => ast_grep_cmd::run(&extra_args)?,
|
||||
Commands::Rg { extra_args } => {
|
||||
search::run(search::Engine::Rg, 80, 200, false, &extra_args, cli.verbose)?
|
||||
}
|
||||
@@ -3123,6 +3148,7 @@ fn is_operational_command(cmd: &Commands) -> bool {
|
||||
| Commands::Summary { .. }
|
||||
| Commands::Grep { .. }
|
||||
| Commands::Rg { .. }
|
||||
| Commands::AstGrep { .. }
|
||||
| Commands::Wget { .. }
|
||||
| Commands::Vitest { .. }
|
||||
| Commands::Ctest { .. }
|
||||
@@ -3596,6 +3622,7 @@ mod tests {
|
||||
"tree",
|
||||
"read",
|
||||
"rg",
|
||||
"ast-grep",
|
||||
"git",
|
||||
"gh",
|
||||
"glab",
|
||||
|
||||
+3674
File diff suppressed because it is too large.
Load diff
+387
@@ -0,0 +1,387 @@
|
||||
src/learn/detector.rs:51:static UNKNOWN_FLAG_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/learn/detector.rs:52: Regex::new(
|
||||
src/learn/detector.rs:53: r"(?i)(unexpected argument|unknown (option|flag)|unrecognized (option|flag)|invalid (option|flag))"
|
||||
src/learn/detector.rs:54: ).unwrap()
|
||||
src/learn/detector.rs:55:});
|
||||
src/learn/detector.rs:57:static CMD_NOT_FOUND_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/learn/detector.rs:58: Regex::new(
|
||||
src/learn/detector.rs:59: r"(?i)(command not found|not recognized as an internal|no such file or directory.*command)",
|
||||
src/learn/detector.rs:60: )
|
||||
src/learn/detector.rs:61: .unwrap()
|
||||
src/learn/detector.rs:62:});
|
||||
src/learn/detector.rs:64:static WRONG_PATH_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/learn/detector.rs:65: Regex::new(r"(?i)(no such file or directory|cannot find the path|file not found)").unwrap()
|
||||
src/learn/detector.rs:66:});
|
||||
src/learn/detector.rs:68:static MISSING_ARG_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/learn/detector.rs:69: Regex::new(
|
||||
src/learn/detector.rs:70: r"(?i)(requires a value|requires an argument|missing (required )?argument|expected.*argument)"
|
||||
src/learn/detector.rs:71: ).unwrap()
|
||||
src/learn/detector.rs:72:});
|
||||
src/learn/detector.rs:75: LazyLock::new(|| Regex::new(r"(?i)(permission denied|access denied|not permitted)").unwrap());
|
||||
src/learn/detector.rs:78:static USER_REJECTION_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/learn/detector.rs:79: Regex::new(
|
||||
src/learn/detector.rs:80: r"(?i)(user (doesn't want|declined|rejected|cancelled)|operation (cancelled|aborted) by user)"
|
||||
src/learn/detector.rs:81: ).unwrap()
|
||||
src/learn/detector.rs:82:});
|
||||
src/cmds/git/gh_cmd.rs:16:static HTML_COMMENT_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?s)<!--.*?-->").unwrap());
|
||||
src/cmds/git/gh_cmd.rs:18: LazyLock::new(|| Regex::new(r"(?m)^\s*\[!\[[^\]]*\]\([^)]*\)\]\([^)]*\)\s*$").unwrap());
|
||||
src/cmds/git/gh_cmd.rs:20: LazyLock::new(|| Regex::new(r"(?m)^\s*!\[[^\]]*\]\([^)]*\)\s*$").unwrap());
|
||||
src/cmds/git/gh_cmd.rs:22: LazyLock::new(|| Regex::new(r"(?m)^\s*(?:---+|\*\*\*+|___+)\s*$").unwrap());
|
||||
src/cmds/git/gh_cmd.rs:23:static MULTI_BLANK_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\n{3,}").unwrap());
|
||||
src/cmds/system/ctest_cmd.rs:24:static TEST_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/system/ctest_cmd.rs:25: Regex::new(
|
||||
src/cmds/system/ctest_cmd.rs:26: r"(?s)^\s*(?:\d+/(\d+)\s+)?Test\s+#(\d+):\s+(.+?)\s+\.{2,}\s*(?:\*{3})?\s*(.+?)\s+([\d.]+)\s+sec\s*$",
|
||||
src/cmds/system/ctest_cmd.rs:27: )
|
||||
src/cmds/system/ctest_cmd.rs:28: .expect("invalid ctest result regex")
|
||||
src/cmds/system/ctest_cmd.rs:29:});
|
||||
src/cmds/system/ctest_cmd.rs:30:static RESULT_PREFIX_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/system/ctest_cmd.rs:31: Regex::new(r"^\s*(?:\d+/\d+\s+)?Test\s+#\d+:")
|
||||
src/cmds/system/ctest_cmd.rs:32: .expect("invalid ctest result prefix regex")
|
||||
src/cmds/system/ctest_cmd.rs:33:});
|
||||
src/cmds/system/ctest_cmd.rs:34:static RESULT_TERMINATOR_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/system/ctest_cmd.rs:35: Regex::new(r"[\d.]+\s+sec\s*$").expect("invalid ctest result terminator regex")
|
||||
src/cmds/system/ctest_cmd.rs:36:});
|
||||
src/cmds/system/ctest_cmd.rs:37:static START_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/system/ctest_cmd.rs:38: Regex::new(r"^\s*Start\s+(\d+):\s*(.*?)\s*$").expect("invalid ctest start regex")
|
||||
src/cmds/system/ctest_cmd.rs:39:});
|
||||
src/cmds/system/ctest_cmd.rs:40:static SUMMARY_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/system/ctest_cmd.rs:41: Regex::new(r"^\s*\d+%\s+tests passed,\s+(\d+)\s+tests failed out of\s+(\d+)")
|
||||
src/cmds/system/ctest_cmd.rs:42: .expect("invalid ctest summary regex")
|
||||
src/cmds/system/ctest_cmd.rs:43:});
|
||||
src/cmds/system/ctest_cmd.rs:44:static TIME_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/system/ctest_cmd.rs:45: Regex::new(r"^\s*Total Test time \(real\)\s+=\s+([\d.]+)\s+sec")
|
||||
src/cmds/system/ctest_cmd.rs:46: .expect("invalid ctest time regex")
|
||||
src/cmds/system/ctest_cmd.rs:47:});
|
||||
src/cmds/git/glab_cmd.rs:23:static HTML_COMMENT_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?s)<!--.*?-->").unwrap());
|
||||
src/cmds/git/glab_cmd.rs:25: LazyLock::new(|| Regex::new(r"(?m)^\s*\[!\[[^\]]*\]\([^)]*\)\]\([^)]*\)\s*$").unwrap());
|
||||
src/cmds/git/glab_cmd.rs:27: LazyLock::new(|| Regex::new(r"(?m)^\s*!\[[^\]]*\]\([^)]*\)\s*$").unwrap());
|
||||
src/cmds/git/glab_cmd.rs:29: LazyLock::new(|| Regex::new(r"(?m)^\s*(?:---+|\*\*\*+|___+)\s*$").unwrap());
|
||||
src/cmds/git/glab_cmd.rs:30:static MULTI_BLANK_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\n{3,}").unwrap());
|
||||
src/cmds/git/glab_cmd.rs:32: LazyLock::new(|| Regex::new(r"/-/merge_requests/(\d+)").unwrap());
|
||||
src/cmds/git/glab_cmd.rs:34:static SECTION_MARKER_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/git/glab_cmd.rs:35: Regex::new(r"section_(?:start|end):\d+:[a-z0-9_]+(?:\x1b\[0K|\[0K)*").unwrap()
|
||||
src/cmds/git/glab_cmd.rs:36:});
|
||||
src/cmds/git/glab_cmd.rs:38:static BARE_ANSI_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\[[\d;]+[A-Za-z]").unwrap());
|
||||
src/cmds/ruby/rake_cmd.rs:168: LazyLock::new(|| regex::Regex::new(r"^\d+\)\s+(Failure|Error):$").unwrap());
|
||||
src/cmds/system/ls.rs:14:static LS_DATE_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/system/ls.rs:15: Regex::new(
|
||||
src/cmds/system/ls.rs:16: r"\s+(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+\d{1,2}\s+(?:\d{4}|\d{2}:\d{2})\s+"
|
||||
src/cmds/system/ls.rs:17: )
|
||||
src/cmds/system/ls.rs:18: .unwrap()
|
||||
src/cmds/system/ls.rs:19:});
|
||||
src/cmds/git/gt_cmd.rs:13: LazyLock::new(|| Regex::new(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b").unwrap());
|
||||
src/cmds/git/gt_cmd.rs:14:static BRANCH_NAME_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/git/gt_cmd.rs:15: Regex::new(
|
||||
src/cmds/git/gt_cmd.rs:16: r#"(?:Created|Pushed|pushed|Deleted|deleted)\s+branch\s+[`"']?([a-zA-Z0-9/_.\-+@]+)"#,
|
||||
src/cmds/git/gt_cmd.rs:17: )
|
||||
src/cmds/git/gt_cmd.rs:18: .unwrap()
|
||||
src/cmds/git/gt_cmd.rs:19:});
|
||||
src/cmds/git/gt_cmd.rs:20:static PR_LINE_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/git/gt_cmd.rs:21: Regex::new(r"(Created|Updated)\s+pull\s+request\s+#(\d+)\s+for\s+([^\s:]+)(?::\s*(\S+))?")
|
||||
src/cmds/git/gt_cmd.rs:22: .unwrap()
|
||||
src/cmds/git/gt_cmd.rs:23:});
|
||||
src/cmds/system/search.rs:739: LazyLock::new(|| Regex::new(r"^([^\x00]+)\x00(\d+)([:-])(.*)$").unwrap());
|
||||
src/discover/registry.rs:54:static REGEX_SET: LazyLock<RegexSet> = LazyLock::new(|| {
|
||||
src/discover/registry.rs:55: RegexSet::new(RULES.iter().map(|r| r.pattern)).expect("invalid regex patterns")
|
||||
src/discover/registry.rs:56:});
|
||||
src/discover/registry.rs:57:static COMPILED: LazyLock<Vec<Regex>> = LazyLock::new(|| {
|
||||
src/discover/registry.rs:58: RULES
|
||||
src/discover/registry.rs:59: .iter()
|
||||
src/discover/registry.rs:60: .map(|r| Regex::new(r.pattern).expect("invalid regex"))
|
||||
src/discover/registry.rs:61: .collect()
|
||||
src/discover/registry.rs:62:});
|
||||
src/discover/registry.rs:63:static ENV_PREFIX: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/discover/registry.rs:64: let double_quoted = r#""(?:[^"\\]|\\.)*""#;
|
||||
src/discover/registry.rs:65: let single_quoted = r#"'(?:[^'\\]|\\.)*'"#;
|
||||
src/discover/registry.rs:66: let unquoted = r#"[^\s]*"#;
|
||||
src/discover/registry.rs:67: let env_value = format!("(?:{}|{}|{})", double_quoted, single_quoted, unquoted);
|
||||
src/discover/registry.rs:68: let env_assign = format!(r#"[A-Z_][A-Z0-9_]*={}"#, env_value);
|
||||
src/discover/registry.rs:69: Regex::new(&format!(r#"^(?:sudo\s+|env\s+|{}\s+)+"#, env_assign)).unwrap()
|
||||
src/discover/registry.rs:70:});
|
||||
src/discover/registry.rs:73:static GIT_GLOBAL_OPT: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/discover/registry.rs:74: Regex::new(r"^(?:(?:-C\s+\S+|-c\s+\S+|--git-dir(?:=\S+|\s+\S+)|--work-tree(?:=\S+|\s+\S+)|--no-pager|--no-optional-locks|--bare|--literal-pathspecs)\s+)+").unwrap()
|
||||
src/discover/registry.rs:75:});
|
||||
src/discover/registry.rs:80:static HEAD_N: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^head\s+-(\d+)\s+(\S+)$").unwrap());
|
||||
src/discover/registry.rs:82: LazyLock::new(|| Regex::new(r"^head\s+--lines=(\d+)\s+(\S+)$").unwrap());
|
||||
src/discover/registry.rs:83:static TAIL_N: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^tail\s+-(\d+)\s+(\S+)$").unwrap());
|
||||
src/discover/registry.rs:85: LazyLock::new(|| Regex::new(r"^tail\s+-n\s+(\d+)\s+(\S+)$").unwrap());
|
||||
src/discover/registry.rs:87: LazyLock::new(|| Regex::new(r"^tail\s+--lines=(\d+)\s+(\S+)$").unwrap());
|
||||
src/discover/registry.rs:89: LazyLock::new(|| Regex::new(r"^tail\s+--lines\s+(\d+)\s+(\S+)$").unwrap());
|
||||
src/discover/registry.rs:539: LazyLock::new(|| Regex::new(r"(?m)[ \t\x0B\x0C]*\\\r?\n[ \t\x0B\x0C]*").unwrap());
|
||||
src/discover/registry.rs:541:static BASH_JOIN_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\\\r?\n").unwrap());
|
||||
src/cmds/system/log_cmd.rs:14:static TIMESTAMP_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/system/log_cmd.rs:15: Regex::new(r"^\d{4}[-/]\d{2}[-/]\d{2}[T ]\d{2}:\d{2}:\d{2}[.,]?\d*\s*").unwrap()
|
||||
src/cmds/system/log_cmd.rs:16:});
|
||||
src/cmds/system/log_cmd.rs:17:static UUID_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/system/log_cmd.rs:18: Regex::new(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")
|
||||
src/cmds/system/log_cmd.rs:19: .unwrap()
|
||||
src/cmds/system/log_cmd.rs:20:});
|
||||
src/cmds/system/log_cmd.rs:21:static HEX_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"0x[0-9a-fA-F]+").unwrap());
|
||||
src/cmds/system/log_cmd.rs:22:static NUM_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\b\d{4,}\b").unwrap());
|
||||
src/cmds/system/log_cmd.rs:23:static PATH_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"/[\w./\-]+").unwrap());
|
||||
src/cmds/ruby/rspec_cmd.rs:22: LazyLock::new(|| Regex::new(r"(?i)running via spring preloader").unwrap());
|
||||
src/cmds/ruby/rspec_cmd.rs:23:static RE_SIMPLECOV: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/ruby/rspec_cmd.rs:24: Regex::new(r"(?i)(coverage report|simplecov|coverage/|\.simplecov|All Files.*Lines)").unwrap()
|
||||
src/cmds/ruby/rspec_cmd.rs:25:});
|
||||
src/cmds/ruby/rspec_cmd.rs:27: LazyLock::new(|| Regex::new(r"^DEPRECATION WARNING:").unwrap());
|
||||
src/cmds/ruby/rspec_cmd.rs:28:static RE_FINISHED_IN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^Finished in \d").unwrap());
|
||||
src/cmds/ruby/rspec_cmd.rs:30: LazyLock::new(|| Regex::new(r"saved screenshot to (.+)").unwrap());
|
||||
src/cmds/ruby/rspec_cmd.rs:32: LazyLock::new(|| Regex::new(r"(\d+) examples?, (\d+) failures?").unwrap());
|
||||
src/cmds/js/playwright_cmd.rs:168: LazyLock::new(|| Regex::new(r"(\d+)\s+(passed|failed|flaky|skipped)").unwrap());
|
||||
src/cmds/js/playwright_cmd.rs:170: LazyLock::new(|| Regex::new(r"\((\d+(?:\.\d+)?)(ms|s|m)\)").unwrap());
|
||||
src/cmds/js/playwright_cmd.rs:220: LazyLock::new(|| Regex::new(r"[×✗]\s+.*?›\s+([^›]+\.spec\.[tj]sx?)").unwrap());
|
||||
src/cmds/js/next_cmd.rs:45: static BUNDLE_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/js/next_cmd.rs:46: Regex::new(r"^[○●◐λ✓]\s+([\w/\-\.]+)\s+(\d+(?:\.\d+)?)\s*(kB|B)\s+(\d+(?:\.\d+)?)\s*(kB|B)")
|
||||
src/cmds/js/next_cmd.rs:47: .unwrap()
|
||||
src/cmds/js/next_cmd.rs:48: });
|
||||
src/cmds/js/next_cmd.rs:172: LazyLock::new(|| Regex::new(r"(\d+(?:\.\d+)?)\s*(s|ms)").unwrap());
|
||||
src/cmds/php/artisan_cmd.rs:8:static BOX_CHARS_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/php/artisan_cmd.rs:9: Regex::new(r"[\u{2500}-\u{257F}\u{2580}-\u{259F}\u{25A0}-\u{25FF}\u{27A0}-\u{27BF}]+").unwrap()
|
||||
src/cmds/php/artisan_cmd.rs:10:});
|
||||
src/cmds/php/artisan_cmd.rs:11:static DOTS_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\.{3,}").unwrap());
|
||||
src/cmds/php/artisan_cmd.rs:12:static MULTI_SPACE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[ \t]{2,}").unwrap());
|
||||
src/cmds/php/artisan_cmd.rs:13:static MULTI_BLANK_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\n{3,}").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:13:static TASK_LINE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^> Task :").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:15: LazyLock::new(|| Regex::new(r"^\* Try:|^> Run with --|^> Get more help at").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:17: LazyLock::new(|| Regex::new(r"^BUILD (SUCCESSFUL|FAILED)").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:19: LazyLock::new(|| Regex::new(r"^\d+ actionable tasks?").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:180: static DAEMON_LINE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/jvm/gradlew_cmd.rs:181: Regex::new(
|
||||
src/cmds/jvm/gradlew_cmd.rs:182: r"^(Starting a Gradle Daemon|Daemon will be stopped|Reusing configuration cache|Calculating task graph|> Configure project|Deprecated Gradle features|You can use|For more on this|Configuration cache entry)"
|
||||
src/cmds/jvm/gradlew_cmd.rs:183: )
|
||||
src/cmds/jvm/gradlew_cmd.rs:184: .unwrap()
|
||||
src/cmds/jvm/gradlew_cmd.rs:185: });
|
||||
src/cmds/jvm/gradlew_cmd.rs:186: static PROGRESS: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/jvm/gradlew_cmd.rs:187: Regex::new(r"^\s*\d+%|^Downloading|^Configuring|^Resolving|^\[Incubating\]|^Wrote HTML report|^class \S+ could not|^\[android-")
|
||||
src/cmds/jvm/gradlew_cmd.rs:188: .unwrap()
|
||||
src/cmds/jvm/gradlew_cmd.rs:189: });
|
||||
src/cmds/jvm/gradlew_cmd.rs:190: static ERROR_LINE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/jvm/gradlew_cmd.rs:191: Regex::new(
|
||||
src/cmds/jvm/gradlew_cmd.rs:192: r"(?i)(^FAILURE:|^\* What went wrong:|^\* Where:|> Could not|e: |error:|^Execution failed|Lint found \d+ error)"
|
||||
src/cmds/jvm/gradlew_cmd.rs:193: )
|
||||
src/cmds/jvm/gradlew_cmd.rs:194: .unwrap()
|
||||
src/cmds/jvm/gradlew_cmd.rs:195: });
|
||||
src/cmds/jvm/gradlew_cmd.rs:198: LazyLock::new(|| Regex::new(r"^(w: |warning:|Warning:|WARNING:)").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:200: LazyLock::new(|| Regex::new(r"gradle\.com/s/|Publishing build scan").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:234: LazyLock::new(|| Regex::new(r"FAILED$| FAILED ").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:236: LazyLock::new(|| Regex::new(r" PASSED$| SKIPPED$").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:237: static SUMMARY_LINE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/jvm/gradlew_cmd.rs:238: Regex::new(
|
||||
src/cmds/jvm/gradlew_cmd.rs:239: r"\d+ tests? completed|\d+ tests? failed|There were failing tests|See the report at",
|
||||
src/cmds/jvm/gradlew_cmd.rs:240: )
|
||||
src/cmds/jvm/gradlew_cmd.rs:241: .unwrap()
|
||||
src/cmds/jvm/gradlew_cmd.rs:242: });
|
||||
src/cmds/jvm/gradlew_cmd.rs:312: LazyLock::new(|| Regex::new(r"^INSTRUMENTATION_STATUS[_CODE]*:").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:314: LazyLock::new(|| Regex::new(r"^INSTRUMENTATION_RESULT:").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:316: LazyLock::new(|| Regex::new(r"^INSTRUMENTATION_CODE:").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:318: LazyLock::new(|| Regex::new(r"^Starting \d+ tests? on ").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:320: LazyLock::new(|| Regex::new(r"^Installing APK").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:363: LazyLock::new(|| Regex::new(r"[^:]+:\d+:.*[Ee]rror:.*\[").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:366: LazyLock::new(|| Regex::new(r"[^:]+:\d+:.*[Ww]arning:.*\[").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:369: LazyLock::new(|| Regex::new(r"[^:]+:\d+:\d+:.*[Ll]int").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:372: LazyLock::new(|| Regex::new(r"[^:]+:\d+:\d+:.*error").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:375: LazyLock::new(|| Regex::new(r"\d+ (issues?|errors?|warnings?)").unwrap());
|
||||
src/cmds/jvm/gradlew_cmd.rs:377: static REPORT_LINE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/jvm/gradlew_cmd.rs:378: Regex::new(r"Wrote (HTML|XML|text) report|file://|/build/reports/lint").unwrap()
|
||||
src/cmds/jvm/gradlew_cmd.rs:379: });
|
||||
src/cmds/php/utils.rs:7:static ANSI_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\x1b\[[0-9;]*[A-Za-z]").unwrap());
|
||||
src/cmds/php/utils.rs:9: LazyLock::new(|| Regex::new(r"[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]").unwrap());
|
||||
src/cmds/cloud/psql_cmd.rs:17: LazyLock::new(|| Regex::new(r"-\[ RECORD \d+ \]-").unwrap());
|
||||
src/cmds/cloud/psql_cmd.rs:18:static SEPARATOR: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[-+]+$").unwrap());
|
||||
src/cmds/cloud/psql_cmd.rs:19:static ROW_COUNT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\(\d+ rows?\)$").unwrap());
|
||||
src/cmds/cloud/psql_cmd.rs:21: LazyLock::new(|| Regex::new(r"^-\[ RECORD (\d+) \]-").unwrap());
|
||||
src/cmds/php/phpunit_cmd.rs:20:static FAILURE_HEADING_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\d+\) \S").unwrap());
|
||||
src/cmds/rust/runner.rs:13:static ERROR_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
|
||||
src/cmds/rust/runner.rs:14: vec![
|
||||
src/cmds/rust/runner.rs:15: // Generic errors
|
||||
src/cmds/rust/runner.rs:16: Regex::new(r"(?i)^.*error[\s:\[].*$").unwrap(),
|
||||
src/cmds/rust/runner.rs:17: Regex::new(r"(?i)^.*\berr\b.*$").unwrap(),
|
||||
src/cmds/rust/runner.rs:18: Regex::new(r"(?i)^.*warning[\s:\[].*$").unwrap(),
|
||||
src/cmds/rust/runner.rs:19: Regex::new(r"(?i)^.*\bwarn\b.*$").unwrap(),
|
||||
src/cmds/rust/runner.rs:20: Regex::new(r"(?i)^.*failed.*$").unwrap(),
|
||||
src/cmds/rust/runner.rs:21: Regex::new(r"(?i)^.*failure.*$").unwrap(),
|
||||
src/cmds/rust/runner.rs:22: Regex::new(r"(?i)^.*exception.*$").unwrap(),
|
||||
src/cmds/rust/runner.rs:23: Regex::new(r"(?i)^.*panic.*$").unwrap(),
|
||||
src/cmds/rust/runner.rs:24: // Rust specific
|
||||
src/cmds/rust/runner.rs:25: Regex::new(r"^error\[E\d+\]:.*$").unwrap(),
|
||||
src/cmds/rust/runner.rs:26: Regex::new(r"^\s*--> .*:\d+:\d+$").unwrap(),
|
||||
src/cmds/rust/runner.rs:27: // Python
|
||||
src/cmds/rust/runner.rs:28: Regex::new(r"^Traceback.*$").unwrap(),
|
||||
src/cmds/rust/runner.rs:29: Regex::new(r#"^\s*File ".*", line \d+.*$"#).unwrap(),
|
||||
src/cmds/rust/runner.rs:30: // JavaScript/TypeScript
|
||||
src/cmds/rust/runner.rs:31: Regex::new(r"^\s*at .*:\d+:\d+.*$").unwrap(),
|
||||
src/cmds/rust/runner.rs:32: // Go
|
||||
src/cmds/rust/runner.rs:33: Regex::new(r"^.*\.go:\d+:.*$").unwrap(),
|
||||
src/cmds/rust/runner.rs:34: ]
|
||||
src/cmds/rust/runner.rs:35:});
|
||||
src/cmds/js/vitest_cmd.rs:121: LazyLock::new(|| Regex::new(r"Tests\s+(?:(\d+)\s+failed\s+\|\s+)?(\d+)\s+passed").unwrap());
|
||||
src/cmds/js/vitest_cmd.rs:123: LazyLock::new(|| Regex::new(r"Duration\s+([\d.]+)(ms|s)").unwrap());
|
||||
src/cmds/dotnet/binlog.rs:55:static ISSUE_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/dotnet/binlog.rs:56: Regex::new(
|
||||
src/cmds/dotnet/binlog.rs:57: r"(?m)^\s*(?P<file>[^\r\n:(]+)\((?P<line>\d+),(?P<column>\d+)\):\s*(?P<kind>error|warning)\s*(?:(?P<code>[A-Za-z]+\d+)\s*:\s*)?(?P<msg>.*)$"
|
||||
src/cmds/dotnet/binlog.rs:58: )
|
||||
src/cmds/dotnet/binlog.rs:59: .expect("valid regex")
|
||||
src/cmds/dotnet/binlog.rs:60:});
|
||||
src/cmds/dotnet/binlog.rs:61:static BUILD_SUMMARY_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/dotnet/binlog.rs:62: Regex::new(r"(?mi)^\s*(?P<count>\d+)\s+(?P<kind>warning|error)\(s\)").expect("valid regex")
|
||||
src/cmds/dotnet/binlog.rs:63:});
|
||||
src/cmds/dotnet/binlog.rs:65: LazyLock::new(|| Regex::new(r"(?i)\b(?P<count>\d+)\s+error\(s\)").expect("valid regex"));
|
||||
src/cmds/dotnet/binlog.rs:67: LazyLock::new(|| Regex::new(r"(?i)\b(?P<count>\d+)\s+warning\(s\)").expect("valid regex"));
|
||||
src/cmds/dotnet/binlog.rs:68:static FALLBACK_ERROR_LINE_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/dotnet/binlog.rs:69: Regex::new(r"(?mi)^.+\(\d+,\d+\):\s*error(?:\s+[A-Za-z]{2,}\d{3,})?(?:\s*:.*)?$")
|
||||
src/cmds/dotnet/binlog.rs:70: .expect("valid regex")
|
||||
src/cmds/dotnet/binlog.rs:71:});
|
||||
src/cmds/dotnet/binlog.rs:72:static FALLBACK_WARNING_LINE_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/dotnet/binlog.rs:73: Regex::new(r"(?mi)^.+\(\d+,\d+\):\s*warning(?:\s+[A-Za-z]{2,}\d{3,})?(?:\s*:.*)?$")
|
||||
src/cmds/dotnet/binlog.rs:74: .expect("valid regex")
|
||||
src/cmds/dotnet/binlog.rs:75:});
|
||||
src/cmds/dotnet/binlog.rs:76:static DURATION_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/dotnet/binlog.rs:77: Regex::new(r"(?m)^\s*Time Elapsed\s+(?P<duration>[^\r\n]+)$").expect("valid regex")
|
||||
src/cmds/dotnet/binlog.rs:78:});
|
||||
src/cmds/dotnet/binlog.rs:79:static TEST_RESULT_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/dotnet/binlog.rs:80: Regex::new(
|
||||
src/cmds/dotnet/binlog.rs:81: r"(?m)(?:Passed!|Failed!)\s*-\s*Failed:\s*(?P<failed>\d+),\s*Passed:\s*(?P<passed>\d+),\s*Skipped:\s*(?P<skipped>\d+),\s*Total:\s*(?P<total>\d+),\s*Duration:\s*(?P<duration>[^\r\n-]+)"
|
||||
src/cmds/dotnet/binlog.rs:82: )
|
||||
src/cmds/dotnet/binlog.rs:83: .expect("valid regex")
|
||||
src/cmds/dotnet/binlog.rs:84:});
|
||||
src/cmds/dotnet/binlog.rs:85:static TEST_SUMMARY_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/dotnet/binlog.rs:86: Regex::new(
|
||||
src/cmds/dotnet/binlog.rs:87: r"(?mi)^\s*Test summary:\s*total:\s*(?P<total>\d+),\s*failed:\s*(?P<failed>\d+),\s*(?:succeeded|passed):\s*(?P<passed>\d+),\s*skipped:\s*(?P<skipped>\d+),\s*duration:\s*(?P<duration>[^\r\n]+)$"
|
||||
src/cmds/dotnet/binlog.rs:88: )
|
||||
src/cmds/dotnet/binlog.rs:89: .expect("valid regex")
|
||||
src/cmds/dotnet/binlog.rs:90:});
|
||||
src/cmds/dotnet/binlog.rs:91:static FAILED_TEST_HEAD_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/dotnet/binlog.rs:92: Regex::new(r"(?m)^\s*Failed\s+(?P<name>[^\r\n\[]+)\s+\[[^\]\r\n]+\]\s*$").expect("valid regex")
|
||||
src/cmds/dotnet/binlog.rs:93:});
|
||||
src/cmds/dotnet/binlog.rs:95: LazyLock::new(|| Regex::new(r"(?m)^\s*Restored\s+.+\.csproj\s*\(").expect("valid regex"));
|
||||
src/cmds/dotnet/binlog.rs:96:static RESTORE_DIAGNOSTIC_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/dotnet/binlog.rs:97: Regex::new(
|
||||
src/cmds/dotnet/binlog.rs:98: r"(?mi)^\s*(?:(?P<file>.+?)\s+:\s+)?(?P<kind>warning|error)\s+(?P<code>[A-Za-z]{2,}\d{3,})\s*:\s*(?P<msg>.+)$"
|
||||
src/cmds/dotnet/binlog.rs:99: )
|
||||
src/cmds/dotnet/binlog.rs:100: .expect("valid regex")
|
||||
src/cmds/dotnet/binlog.rs:101:});
|
||||
src/cmds/dotnet/binlog.rs:102:static PROJECT_PATH_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/dotnet/binlog.rs:103: Regex::new(r"(?m)^\s*([A-Za-z]:)?[^\r\n]*\.csproj(?:\s|$)").expect("valid regex")
|
||||
src/cmds/dotnet/binlog.rs:104:});
|
||||
src/cmds/dotnet/binlog.rs:106: LazyLock::new(|| Regex::new(r"[\x20-\x7E]{5,}").expect("valid regex"));
|
||||
src/cmds/dotnet/binlog.rs:108: LazyLock::new(|| Regex::new(r"^[A-Za-z]{2,}\d{3,}$").expect("valid regex"));
|
||||
src/cmds/dotnet/binlog.rs:110: LazyLock::new(|| Regex::new(r"(?i)([A-Za-z]:)?[/\\][^\s]+\.(cs|vb|fs)").expect("valid regex"));
|
||||
src/cmds/dotnet/binlog.rs:111:static SENSITIVE_ENV_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/dotnet/binlog.rs:112: let keys = SENSITIVE_ENV_VARS
|
||||
src/cmds/dotnet/binlog.rs:113: .iter()
|
||||
src/cmds/dotnet/binlog.rs:114: .map(|key| regex::escape(key))
|
||||
src/cmds/dotnet/binlog.rs:115: .collect::<Vec<_>>()
|
||||
src/cmds/dotnet/binlog.rs:116: .join("|");
|
||||
src/cmds/dotnet/binlog.rs:117: Regex::new(&format!(
|
||||
src/cmds/dotnet/binlog.rs:118: r"(?P<prefix>\b(?:{})\s*(?:=|:)\s*)(?P<value>[^\s;]+)",
|
||||
src/cmds/dotnet/binlog.rs:119: keys
|
||||
src/cmds/dotnet/binlog.rs:120: ))
|
||||
src/cmds/dotnet/binlog.rs:121: .expect("valid regex")
|
||||
src/cmds/dotnet/binlog.rs:122:});
|
||||
src/cmds/jvm/mvn_cmd.rs:34:static RUNNING: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\[INFO\] Running ").unwrap());
|
||||
src/cmds/jvm/mvn_cmd.rs:45: LazyLock::new(|| Regex::new(r"^\[INFO\] Running \S+\s*$").unwrap());
|
||||
src/cmds/jvm/mvn_cmd.rs:55:static CLOSE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/jvm/mvn_cmd.rs:56: Regex::new(
|
||||
src/cmds/jvm/mvn_cmd.rs:57: r"^\[(?:INFO|ERROR|WARNING)\] Tests run: \d+, Failures: (\d+), Errors: (\d+), Skipped: \d+, Time elapsed: [^ ]+ s(?:\s+<<<\s*(?:FAILURE|ERROR)!)?\s+--?\s+in (.+)$"
|
||||
src/cmds/jvm/mvn_cmd.rs:58: ).unwrap()
|
||||
src/cmds/jvm/mvn_cmd.rs:59:});
|
||||
src/cmds/jvm/mvn_cmd.rs:63: LazyLock::new(|| Regex::new(r"^\[(?:INFO|ERROR)\] BUILD (?:SUCCESS|FAILURE)$").unwrap());
|
||||
src/cmds/jvm/mvn_cmd.rs:66:static RESULTS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\[INFO\] Results:\s*$").unwrap());
|
||||
src/cmds/jvm/mvn_cmd.rs:69:static AGG: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/jvm/mvn_cmd.rs:70: Regex::new(r"^\[(?:INFO|ERROR)\] Tests run: \d+, Failures: \d+, Errors: \d+, Skipped: \d+\s*$")
|
||||
src/cmds/jvm/mvn_cmd.rs:71: .unwrap()
|
||||
src/cmds/jvm/mvn_cmd.rs:72:});
|
||||
src/cmds/jvm/mvn_cmd.rs:76: LazyLock::new(|| Regex::new(r"^\[INFO\] --- .* @ .* ---$").unwrap());
|
||||
src/cmds/jvm/mvn_cmd.rs:109:static TEST_PLUGIN_BANNER: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/jvm/mvn_cmd.rs:110: Regex::new(r"^\[INFO\] --- (?:maven-)?(surefire|failsafe)(?:-plugin)?:\S+ \([^)]*\) @ .* ---$")
|
||||
src/cmds/jvm/mvn_cmd.rs:111: .unwrap()
|
||||
src/cmds/jvm/mvn_cmd.rs:112:});
|
||||
src/cmds/jvm/mvn_cmd.rs:125: LazyLock::new(|| Regex::new(r"^\[INFO\] Building .*\[\d+/\d+\]\s*$").unwrap());
|
||||
src/cmds/jvm/mvn_cmd.rs:129: LazyLock::new(|| Regex::new(r"^\[INFO\] -+< .+ >-+$").unwrap());
|
||||
src/cmds/jvm/mvn_cmd.rs:134: LazyLock::new(|| Regex::new(r"^\[INFO\] Reactor Summary for ").unwrap());
|
||||
src/cmds/jvm/mvn_cmd.rs:138: LazyLock::new(|| Regex::new(r"/[^:]+\.java:\[\d+,\d+\]").unwrap());
|
||||
src/cmds/php/phpt_cmd.rs:163: static STATUS_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/php/phpt_cmd.rs:164: // Matches a status line. Anchor: either start-of-line ("FAIL desc [x.phpt]")
|
||||
src/cmds/php/phpt_cmd.rs:165: // or immediately after the test bracket ("TEST N/M [x.phpt]PASS desc [x.phpt]").
|
||||
src/cmds/php/phpt_cmd.rs:166: // We only accept the token after `]` or at line start so that prose like
|
||||
src/cmds/php/phpt_cmd.rs:167: // "FAILED TEST SUMMARY" does not match.
|
||||
src/cmds/php/phpt_cmd.rs:168: Regex::new(
|
||||
src/cmds/php/phpt_cmd.rs:169: r"(?:^|\])(PASS|FAIL|SKIP|BORK|WARN|XLEAK|LEAK|XFAIL)\s+(.*?)\s*\[([^\[\]]+\.phpt)\]",
|
||||
src/cmds/php/phpt_cmd.rs:170: )
|
||||
src/cmds/php/phpt_cmd.rs:171: .unwrap()
|
||||
src/cmds/php/phpt_cmd.rs:172: });
|
||||
src/cmds/php/phpt_cmd.rs:173: static STAT_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/php/phpt_cmd.rs:174: Regex::new(
|
||||
src/cmds/php/phpt_cmd.rs:175: r"^\s*(Tests passed|Tests failed|Tests skipped|Tests warned|Expected fail|Expected leak|Tests leaked|Tests borked)\s*:\s*(\d+)",
|
||||
src/cmds/php/phpt_cmd.rs:176: )
|
||||
src/cmds/php/phpt_cmd.rs:177: .unwrap()
|
||||
src/cmds/php/phpt_cmd.rs:178: });
|
||||
src/cmds/php/phpt_cmd.rs:180: LazyLock::new(|| Regex::new(r"^\s*Number of tests\s*:\s*(\d+)").unwrap());
|
||||
src/cmds/php/phpt_cmd.rs:182: LazyLock::new(|| Regex::new(r"^\s*Time taken\s*:\s*([0-9.]+)").unwrap());
|
||||
src/cmds/cloud/aws_cmd.rs:1327: LazyLock::new(|| Regex::new(r"^(upload|download|delete|copy|move):").unwrap());
|
||||
src/cmds/js/tsc_cmd.rs:22:static TSC_ERROR: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/js/tsc_cmd.rs:23: Regex::new(r"^(.+?)\((\d+),(\d+)\):\s+(error|warning)\s+(TS\d+):\s+(.+)$").unwrap()
|
||||
src/cmds/js/tsc_cmd.rs:24:});
|
||||
src/cmds/js/tsc_cmd.rs:26:static TSC_PRETTY_ERROR: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/js/tsc_cmd.rs:27: Regex::new(r"^(.+?):(\d+):(\d+)\s+-\s+(error|warning)\s+(TS\d+):\s+(.+)$").unwrap()
|
||||
src/cmds/js/tsc_cmd.rs:28:});
|
||||
src/cmds/js/tsc_cmd.rs:30: LazyLock::new(|| Regex::new(r"^(error|warning)\s+(TS\d+):\s+(.+)$").unwrap());
|
||||
src/core/utils.rs:54: LazyLock::new(|| Regex::new(r"\x1b\[[0-9;]*[a-zA-Z]").unwrap());
|
||||
src/cmds/python/uv_cmd.rs:20: LazyLock::new(|| Regex::new(r#"^\s*File ".*", line \d+.*$"#).unwrap());
|
||||
src/cmds/python/uv_cmd.rs:22: LazyLock::new(|| Regex::new(r"^\s*[A-Za-z_][A-Za-z0-9_.]*(?:Error|Exception):").unwrap());
|
||||
src/cmds/python/uv_cmd.rs:24: LazyLock::new(|| Regex::new(r"^\s*at .+:\d+:\d+.*$").unwrap());
|
||||
src/cmds/python/uv_cmd.rs:25:static ERROR_START_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
|
||||
src/cmds/python/uv_cmd.rs:26: vec![
|
||||
src/cmds/python/uv_cmd.rs:27: Regex::new(r"(?i)\berror\b").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:28: Regex::new(r"(?i)\bfailed\b").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:29: Regex::new(r"(?i)\bfailure\b").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:30: Regex::new(r"(?i)\bexception\b").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:31: Regex::new(r"(?i)\bpanic\b").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:32: Regex::new(r"(?i)\bwarn(?:ing)?\b").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:33: Regex::new(r"(?i)\bassert(?:ion)?\b").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:34: Regex::new(r"^\s*FAILED\b").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:35: Regex::new(r"^\s*ERROR\b").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:36: Regex::new(r"^\s*E\s+").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:37: Regex::new(r"^\s*Caused by:").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:38: Regex::new(r"^\s*note:").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:39: Regex::new(r"^\s*help:").unwrap(),
|
||||
src/cmds/python/uv_cmd.rs:40: ]
|
||||
src/cmds/python/uv_cmd.rs:41:});
|
||||
src/core/filter.rs:158:static MULTIPLE_BLANK_LINES: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\n{3,}").unwrap());
|
||||
src/core/filter.rs:233: LazyLock::new(|| Regex::new(r"^(use |import |from |require\(|#include)").unwrap());
|
||||
src/core/filter.rs:234:static FUNC_SIGNATURE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/core/filter.rs:235: Regex::new(
|
||||
src/core/filter.rs:236: r"^(pub\s+)?(async\s+)?(fn|def|function|func|class|struct|enum|trait|interface|type)\s+\w+",
|
||||
src/core/filter.rs:237: )
|
||||
src/core/filter.rs:238: .unwrap()
|
||||
src/core/filter.rs:239:});
|
||||
src/cmds/rust/cargo_cmd.rs:1050: static RE: LazyLock<regex::Regex> = LazyLock::new(|| {
|
||||
src/cmds/rust/cargo_cmd.rs:1051: regex::Regex::new(
|
||||
src/cmds/rust/cargo_cmd.rs:1052: r"test result: (\w+)\.\s+(\d+) passed;\s+(\d+) failed;\s+(\d+) ignored;\s+(\d+) measured;\s+(\d+) filtered out(?:;\s+finished in ([\d.]+)s)?"
|
||||
src/cmds/rust/cargo_cmd.rs:1053: ).unwrap()
|
||||
src/cmds/rust/cargo_cmd.rs:1054: });
|
||||
src/cmds/python/mypy_cmd.rs:57: static MYPY_DIAG: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/python/mypy_cmd.rs:58: Regex::new(r"^(.+?):(\d+)(?::\d+)?: (error|warning|note): (.+?)(?:\s+\[(.+)\])?$").unwrap()
|
||||
src/cmds/python/mypy_cmd.rs:59: });
|
||||
src/cmds/scala/sbt_cmd.rs:10:static TEST_SUMMARY_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/scala/sbt_cmd.rs:11: Regex::new(
|
||||
src/cmds/scala/sbt_cmd.rs:12: r"Tests: succeeded (\d+), failed (\d+), canceled (\d+), ignored (\d+), pending (\d+)",
|
||||
src/cmds/scala/sbt_cmd.rs:13: )
|
||||
src/cmds/scala/sbt_cmd.rs:14: .unwrap()
|
||||
src/cmds/scala/sbt_cmd.rs:15:});
|
||||
src/cmds/scala/sbt_cmd.rs:20:static MUNIT_SUMMARY_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/scala/sbt_cmd.rs:21: Regex::new(r"^\[info\] (?:Passed|Failed): Total \d+, Failed (\d+), Errors (\d+), Passed (\d+)")
|
||||
src/cmds/scala/sbt_cmd.rs:22: .unwrap()
|
||||
src/cmds/scala/sbt_cmd.rs:23:});
|
||||
src/cmds/scala/sbt_cmd.rs:28: LazyLock::new(|| Regex::new(r"Suites: completed (\d+), aborted (\d+)").unwrap());
|
||||
src/cmds/scala/sbt_cmd.rs:32: LazyLock::new(|| Regex::new(r"Run completed in (\d+) seconds?").unwrap());
|
||||
src/cmds/scala/sbt_cmd.rs:36: LazyLock::new(|| Regex::new(r"\[info\] Compiling (\d+) Scala source").unwrap());
|
||||
src/cmds/scala/sbt_cmd.rs:40: LazyLock::new(|| Regex::new(r"\[success\] Total time: (\d+) s").unwrap());
|
||||
src/cmds/scala/sbt_cmd.rs:43:static ERROR_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\[error\]").unwrap());
|
||||
src/cmds/scala/sbt_cmd.rs:46:static NOISE_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
src/cmds/scala/sbt_cmd.rs:47: Regex::new(
|
||||
src/cmds/scala/sbt_cmd.rs:48: r"^\[info\] (welcome to sbt|loading |set current project|Updating |Resolved |Fetching |downloading |Done )"
|
||||
src/cmds/scala/sbt_cmd.rs:49: ).unwrap()
|
||||
src/cmds/scala/sbt_cmd.rs:50:});
|
||||
src/core/toml_filter.rs:399:static REGISTRY: LazyLock<TomlFilterRegistry> = LazyLock::new(TomlFilterRegistry::load);
|
||||
src/core/toml_filter.rs:422:static MATCH_SET: LazyLock<RegexSet> = LazyLock::new(build_match_set);
|
||||
@@ -0,0 +1,139 @@
|
||||
//! `gh pr checks` exits non-zero as a normal result: 1 when a check failed, 8 while
|
||||
//! checks are still pending. Its stdout is complete and valid in both cases, so
|
||||
//! skipping the filter there dropped the whole table on the user exactly when they
|
||||
//! were asking why CI was red. These pin that the summary survives a non-zero exit
|
||||
//! without swallowing the exit code, the diagnostics on stderr, or a check row.
|
||||
|
||||
#![cfg(unix)]
|
||||
|
||||
use std::fs;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Output};
|
||||
|
||||
/// Writes an executable `name` in `dir` that runs `body`.
|
||||
fn fake_tool(dir: &Path, name: &str, body: &str) {
|
||||
let path = dir.join(name);
|
||||
fs::write(&path, format!("#!/bin/sh\n{}\n", body)).expect("write fake tool");
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).expect("chmod fake tool");
|
||||
}
|
||||
|
||||
/// Runs rtk with `dir` first on PATH, so the fake tool shadows any real one.
|
||||
fn rtk_with(dir: &Path, args: &[&str]) -> Output {
|
||||
let path = format!(
|
||||
"{}:{}",
|
||||
dir.display(),
|
||||
std::env::var("PATH").unwrap_or_default()
|
||||
);
|
||||
Command::new(env!("CARGO_BIN_EXE_rtk"))
|
||||
.args(args)
|
||||
.env("PATH", path)
|
||||
.output()
|
||||
.expect("run rtk")
|
||||
}
|
||||
|
||||
/// A `gh` whose `pr checks` prints `table` and exits `code`, the way it does when
|
||||
/// checks failed (1) or are still running (8).
|
||||
fn fake_gh(dir: &Path, table: &str, code: i32) {
|
||||
let path = dir.join("checks.txt");
|
||||
fs::write(&path, table).expect("write table");
|
||||
fake_tool(dir, "gh", &format!("cat {}\nexit {}", path.display(), code));
|
||||
}
|
||||
|
||||
/// Rows as `gh` 2.46 prints them: tab-separated name, state, elapsed, url, description.
|
||||
const RED_TABLE: &str = "doc review\tfail\t13s\thttps://example.test/job/1\t\n\
|
||||
fmt\tfail\t7s\thttps://example.test/job/2\t\n\
|
||||
Analyze (rust)\tpass\t4m17s\thttps://example.test/job/3\t\n\
|
||||
check\tpass\t5s\thttps://example.test/job/4\t\n";
|
||||
|
||||
#[test]
|
||||
fn failing_checks_are_summarised_not_dumped_raw() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
fake_gh(dir.path(), RED_TABLE, 1);
|
||||
|
||||
let out = rtk_with(dir.path(), &["gh", "pr", "checks", "123"]);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
|
||||
assert!(
|
||||
stdout.contains("CI Checks Summary:"),
|
||||
"filter must run on a non-zero exit, got:\n{stdout}"
|
||||
);
|
||||
assert!(stdout.contains("Passed: 2"), "got:\n{stdout}");
|
||||
assert!(stdout.contains("Failed: 2"), "got:\n{stdout}");
|
||||
assert!(
|
||||
stdout.contains("doc review") && stdout.contains("fmt"),
|
||||
"the failed checks are the reason the user ran this, got:\n{stdout}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_red_run_still_propagates_the_exit_code() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
fake_gh(dir.path(), RED_TABLE, 1);
|
||||
|
||||
let out = rtk_with(dir.path(), &["gh", "pr", "checks", "123"]);
|
||||
assert_eq!(out.status.code(), Some(1), "gh's exit code must survive");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_checks_are_counted_and_exit_eight_survives() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
fake_gh(
|
||||
dir.path(),
|
||||
"test (ubuntu)\tpending\t0\thttps://example.test/job/5\t\n\
|
||||
test (macos)\tpending\t0\thttps://example.test/job/6\t\n\
|
||||
test (windows)\tpending\t0\thttps://example.test/job/7\t\n\
|
||||
clippy\tpass\t31s\thttps://example.test/job/8\t\n",
|
||||
8,
|
||||
);
|
||||
|
||||
let out = rtk_with(dir.path(), &["gh", "pr", "checks", "123"]);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
assert!(stdout.contains("Pending: 3"), "got:\n{stdout}");
|
||||
assert_eq!(out.status.code(), Some(8), "gh exits 8 while checks pend");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancelled_run_does_not_read_as_nothing_wrong() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
fake_gh(
|
||||
dir.path(),
|
||||
"build\tcancelled\t45s\thttps://example.test/job/1\t\n\
|
||||
test (ubuntu)\tcancelled\t44s\thttps://example.test/job/2\t\n\
|
||||
Security Scan\tskipping\t0\thttps://example.test/job/3\t\n",
|
||||
1,
|
||||
);
|
||||
|
||||
let out = rtk_with(dir.path(), &["gh", "pr", "checks", "123"]);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
|
||||
assert!(
|
||||
stdout.contains("Skipped/cancelled: 3"),
|
||||
"a cancelled run must not summarise to all zeros, got:\n{stdout}"
|
||||
);
|
||||
assert_eq!(out.status.code(), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_error_with_empty_stdout_does_not_become_an_all_zero_summary() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
fake_tool(
|
||||
dir.path(),
|
||||
"gh",
|
||||
"echo 'GraphQL: Could not resolve to a Repository' >&2\nexit 1",
|
||||
);
|
||||
|
||||
let out = rtk_with(dir.path(), &["gh", "pr", "checks", "123"]);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
|
||||
assert!(
|
||||
!stdout.contains("Passed: 0"),
|
||||
"a failed lookup must not read as a PR with zero checks, got:\n{stdout}"
|
||||
);
|
||||
assert!(
|
||||
stderr.contains("Could not resolve to a Repository"),
|
||||
"the real diagnostic must reach the user, got:\n{stderr}"
|
||||
);
|
||||
assert_eq!(out.status.code(), Some(1));
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
//! The "hook missing/outdated" reminder is a once-a-day nudge, so where it is
|
||||
//! spent matters: a command the user ran to inspect or install the hook would
|
||||
//! both duplicate that command's own reporting and burn the daily marker,
|
||||
//! leaving the next filtered command silent.
|
||||
//!
|
||||
//! Unix only: the check resolves the Claude directory through the home
|
||||
//! directory, and only Unix takes that from `$HOME`.
|
||||
#![cfg(unix)]
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
const REMINDER: &str = "No hook installed";
|
||||
|
||||
/// Runs `rtk <args>` against a home directory whose Claude config directory
|
||||
/// exists but registers no hook, and returns stderr.
|
||||
fn run(home: &Path, args: &[&str]) -> String {
|
||||
let out = Command::new(env!("CARGO_BIN_EXE_rtk"))
|
||||
.args(args)
|
||||
.env("HOME", home)
|
||||
.env("RTK_DB_PATH", home.join("rtk.db"))
|
||||
.output()
|
||||
.expect("run rtk");
|
||||
String::from_utf8_lossy(&out.stderr).into_owned()
|
||||
}
|
||||
|
||||
fn fresh_home() -> tempfile::TempDir {
|
||||
let home = tempfile::tempdir().expect("tempdir");
|
||||
// Absent, the status check reports "not applicable"; present-but-empty is
|
||||
// what makes a missing hook detectable.
|
||||
std::fs::create_dir_all(home.path().join(".claude")).expect("claude dir");
|
||||
home
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_that_report_hook_state_do_not_repeat_the_reminder() {
|
||||
for args in [
|
||||
vec!["init", "-g"],
|
||||
vec!["verify"],
|
||||
vec!["verify", "--filter", "cargo"],
|
||||
vec!["gain"],
|
||||
] {
|
||||
let home = fresh_home();
|
||||
let stderr = run(home.path(), &args);
|
||||
assert!(
|
||||
!stderr.contains(&format!("[rtk] /!\\ {REMINDER}")),
|
||||
"rtk {} must not print the daily reminder: {stderr}",
|
||||
args.join(" ")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filtered_commands_still_get_the_reminder() {
|
||||
for args in [vec!["ls"], vec!["git", "status"]] {
|
||||
let home = fresh_home();
|
||||
let stderr = run(home.path(), &args);
|
||||
assert!(
|
||||
stderr.contains(REMINDER),
|
||||
"rtk {} must still warn: {stderr}",
|
||||
args.join(" ")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_meta_command_leaves_the_daily_reminder_for_the_next_filtered_command() {
|
||||
// The regression this guards: `maybe_warn` touches the once-a-day marker,
|
||||
// so warning on a meta command would spend the reminder there and leave
|
||||
// the next filtered command — the one that should have been hooked —
|
||||
// silent for 24 hours.
|
||||
let home = fresh_home();
|
||||
run(home.path(), &["verify", "--filter", "cargo"]);
|
||||
let stderr = run(home.path(), &["ls"]);
|
||||
assert!(
|
||||
stderr.contains(REMINDER),
|
||||
"the reminder must survive a preceding meta command: {stderr}"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::process::{Command, Output, Stdio};
|
||||
|
||||
fn read_stdin(input: &[u8], args: &[&str]) -> Output {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_rtk"))
|
||||
.args(["read", "-"])
|
||||
.args(args)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("run rtk read from stdin");
|
||||
child
|
||||
.stdin
|
||||
.take()
|
||||
.expect("piped stdin")
|
||||
.write_all(input)
|
||||
.expect("write stdin");
|
||||
child.wait_with_output().expect("wait for rtk read")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_windows_preserve_non_utf8_files() {
|
||||
let dir = tempfile::tempdir().expect("create test directory");
|
||||
let file = dir.path().join("binary.log");
|
||||
fs::write(&file, b"\xff\xfe bad\nline2\nline3\n").expect("write binary file");
|
||||
|
||||
for (flag, expected) in [
|
||||
("--head-lines", b"\xff\xfe bad\nline2\n".as_slice()),
|
||||
("--tail-lines", b"line2\nline3\n".as_slice()),
|
||||
] {
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_rtk"))
|
||||
.arg("read")
|
||||
.arg(&file)
|
||||
.args([flag, "2"])
|
||||
.output()
|
||||
.expect("run rtk read");
|
||||
|
||||
assert!(output.status.success(), "{flag}: {:?}", output.stderr);
|
||||
assert_eq!(output.stdout, expected, "{flag}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_windows_preserve_binary_boundaries_for_files_and_stdin() {
|
||||
let dir = tempfile::tempdir().expect("create test directory");
|
||||
let file = dir.path().join("binary.log");
|
||||
for input in [
|
||||
b"\xff\r\nvalid\n\0\xfe".as_slice(),
|
||||
b"\xff\r\nvalid\n\0\xfe\n".as_slice(),
|
||||
] {
|
||||
fs::write(&file, input).expect("write binary file");
|
||||
let last = if input.ends_with(b"\n") {
|
||||
b"\0\xfe\n".as_slice()
|
||||
} else {
|
||||
b"\0\xfe".as_slice()
|
||||
};
|
||||
for (flag, count, expected) in [
|
||||
("--head-lines", "0", b"".as_slice()),
|
||||
("--tail-lines", "0", b"".as_slice()),
|
||||
("--head-lines", "1", b"\xff\r\n".as_slice()),
|
||||
("--tail-lines", "1", last),
|
||||
("--head-lines", "99", input),
|
||||
("--tail-lines", "99", input),
|
||||
] {
|
||||
let from_file = Command::new(env!("CARGO_BIN_EXE_rtk"))
|
||||
.arg("read")
|
||||
.arg(&file)
|
||||
.args([flag, count])
|
||||
.output()
|
||||
.expect("run rtk read");
|
||||
let from_stdin = read_stdin(input, &[flag, count]);
|
||||
for output in [from_file, from_stdin] {
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{flag} {count}: {:?}",
|
||||
output.stderr
|
||||
);
|
||||
assert_eq!(output.stdout, expected, "{flag} {count}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_windows_accept_invalid_bytes_outside_the_selected_window() {
|
||||
for (input, flag) in [
|
||||
(b"valid\n\xff\n".as_slice(), "--head-lines"),
|
||||
(b"\xff\nvalid\n".as_slice(), "--tail-lines"),
|
||||
] {
|
||||
let output = read_stdin(input, &[flag, "1"]);
|
||||
assert!(output.status.success(), "{flag}: {:?}", output.stderr);
|
||||
assert_eq!(output.stdout, b"valid\n");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_windows_still_apply_text_filtering_and_line_numbers() {
|
||||
let input = b"// comment\nfn alpha() {}\nfn beta() {}\nfn gamma() {}\n";
|
||||
for (args, expected) in [
|
||||
(
|
||||
["--head-lines", "1", "--level", "minimal"].as_slice(),
|
||||
"fn alpha() {}\n",
|
||||
),
|
||||
(
|
||||
["--tail-lines", "1", "--level", "minimal"].as_slice(),
|
||||
"fn gamma() {}",
|
||||
),
|
||||
(
|
||||
["--head-lines", "1", "--line-numbers"].as_slice(),
|
||||
"1 │ // comment\n",
|
||||
),
|
||||
(
|
||||
["--tail-lines", "1", "--line-numbers"].as_slice(),
|
||||
"1 │ fn gamma() {}\n",
|
||||
),
|
||||
] {
|
||||
let output = read_stdin(input, args);
|
||||
assert!(output.status.success(), "{args:?}: {:?}", output.stderr);
|
||||
assert_eq!(output.stdout, expected.as_bytes(), "{args:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn rewritten_head_spellings_match_native_on_non_utf8_files() {
|
||||
let dir = tempfile::tempdir().expect("create test directory");
|
||||
let claude_dir = dir.path().join(".claude");
|
||||
fs::create_dir(&claude_dir).expect("create isolated Claude config directory");
|
||||
let config_dir = dir.path().join("config");
|
||||
fs::create_dir(&config_dir).expect("create isolated rtk config directory");
|
||||
let file = dir.path().join("binary.log");
|
||||
fs::write(&file, b"\xff\xfe bad\nline2\nline3\n").expect("write binary file");
|
||||
for flags in ["-2", "-n 2", "--lines 2", "--lines=2", ""] {
|
||||
let command = format!("head {flags} {}", file.display());
|
||||
let rewrite = Command::new(env!("CARGO_BIN_EXE_rtk"))
|
||||
.current_dir(dir.path())
|
||||
.env("CLAUDE_CONFIG_DIR", &claude_dir)
|
||||
.env("XDG_CONFIG_HOME", &config_dir)
|
||||
.args(["rewrite", &command])
|
||||
.output()
|
||||
.expect("rewrite head command");
|
||||
assert_eq!(
|
||||
rewrite.status.code(),
|
||||
Some(3),
|
||||
"{command}: {:?}",
|
||||
rewrite.stderr
|
||||
);
|
||||
let rewritten = String::from_utf8(rewrite.stdout).expect("UTF-8 command");
|
||||
let count = if flags.is_empty() { "10" } else { "2" };
|
||||
assert_eq!(
|
||||
rewritten.trim(),
|
||||
format!("rtk read {} --head-lines {count}", file.display())
|
||||
);
|
||||
let actual = Command::new(env!("CARGO_BIN_EXE_rtk"))
|
||||
.args(
|
||||
rewritten
|
||||
.trim()
|
||||
.strip_prefix("rtk ")
|
||||
.expect("rtk rewrite prefix")
|
||||
.split_whitespace(),
|
||||
)
|
||||
.output()
|
||||
.expect("execute rewritten head");
|
||||
let native = Command::new("head")
|
||||
.args(flags.split_whitespace())
|
||||
.arg(&file)
|
||||
.output()
|
||||
.expect("run native head");
|
||||
assert!(native.status.success(), "{command}: {:?}", native.stderr);
|
||||
assert_eq!(actual.status.code(), native.status.code(), "{command}");
|
||||
assert_eq!(actual.stdout, native.stdout, "{command}");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user