Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d402152ffa | ||
|
|
06d538728c | ||
|
|
cfe248c1f6 | ||
|
|
784d347011 | ||
|
|
e224b159af | ||
|
|
23a1be622f | ||
|
|
6f4913b37b | ||
|
|
ed8480f3e2 | ||
|
|
3b4ab8735a |
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 ---
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 :**
|
||||
|
||||
+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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
+263
-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
|
||||
@@ -3832,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())
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3840,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())
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3926,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
|
||||
|
||||
+23
-6
@@ -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)]
|
||||
@@ -1857,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();
|
||||
}
|
||||
|
||||
@@ -1879,6 +1887,7 @@ fn run_cli() -> Result<i32> {
|
||||
files,
|
||||
level,
|
||||
max_lines,
|
||||
head_lines,
|
||||
tail_lines,
|
||||
line_numbers,
|
||||
} => {
|
||||
@@ -1891,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,
|
||||
|
||||
@@ -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