Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f0e1e81948 | ||
|
|
e3e5df621a | ||
|
|
b276eb05ca | ||
|
|
73ad3635a4 | ||
|
|
6a876571b3 | ||
|
|
cf543092d5 | ||
|
|
2060de4644 | ||
|
|
fb4acd7518 |
No files matched your search
@@ -141,8 +141,9 @@ rewrite_compound(cmd, excluded) [src/discover/registry.rs]
|
||||
|
|
||||
| Step 2 — Split on operators, rewrite each segment
|
||||
| Operator (&&, ||, ;) → rewrite both sides
|
||||
| Pipe (|) → rewrite left side only, keep right side raw
|
||||
| exception: find/fd before pipe → skip rewrite
|
||||
| Pipe (|, |&) → producer rewritten only if all downstream stages
|
||||
| are display-only (head/tail/cat); final stage
|
||||
| rewritten if stdin-safe (grep/rg); middle stays raw
|
||||
| Shellism (&) → rewrite both sides (background)
|
||||
|
|
||||
| Calls rewrite_segment() per segment:
|
||||
@@ -205,7 +206,7 @@ LLM Agent executes rewritten command
|
||||
Key design decisions:
|
||||
- **Lexer-based tokenization**: A single-pass state machine (`lexer.rs`) handles all shell constructs (quotes, escapes, redirects, operators). Used for both compound splitting and redirect stripping.
|
||||
- **Segment-level rewriting**: Compound commands are split by operators, each segment rewritten independently. Bash recombines them at execution time.
|
||||
- **Pipe semantics**: Only the left side of `|` is rewritten. The pipe consumer (grep, head, wc) runs raw. `find`/`fd` before a pipe is never rewritten (output format incompatible with xargs).
|
||||
- **Pipe semantics**: The producer is rewritten only when every downstream stage is display-only (`head`, `tail` without follow, `cat`) — otherwise rtk's reshaped output would feed a program that parses it (`grep | wc -l` miscounted, #2962; `find | xargs`, #439) and the producer stays raw. The final stage — agent-facing stdout — is rewritten when its filter is stdin-safe (`STDIN_SAFE_FINAL`: `grep`, `rg`); intermediate stages always run raw.
|
||||
- **Double env prefix handling**: `classify_command()` strips env prefixes to match the underlying command against rules. `rewrite_segment()` extracts the same prefix separately to re-prepend it to the rewritten command.
|
||||
- **Fallback contract**: If any segment fails to match, it stays raw. `rewrite_command()` returns `None` only when zero segments were rewritten.
|
||||
|
||||
|
||||
+1
-2
@@ -199,9 +199,8 @@ The registry (`src/discover/registry.rs`) handles command patterns across these
|
||||
|
||||
The registry handles `&&`, `||`, `;`, `|`, and `&` operators:
|
||||
|
||||
- **Pipe** (`|`): Only the left side is rewritten (right side consumes output format)
|
||||
- **Pipe** (`|`, `|&`): A stage feeding a pipe is rewritten only when every downstream stage is display-only (`head`, `tail` without follow, `cat`) — then the agent is still the real reader. Any content-consuming stage (`wc`, `xargs`, …) keeps the producer raw, because rtk's reshaped output corrupts programs that parse it (#2962). The **final** stage — whose stdout goes to the agent — is rewritten when its filter is stdin-safe (`grep`, `rg`: streams, preserves exit codes), e.g. `cargo test | grep FAILED` → `cargo test | rtk grep FAILED`. Intermediate stages always run raw.
|
||||
- **And/Or/Semicolon** (`&&`, `||`, `;`): Both sides rewritten independently
|
||||
- **find/fd in pipes**: Never rewritten (output format incompatible with xargs/wc/grep)
|
||||
|
||||
Example: `cargo fmt --all && cargo test` becomes `rtk cargo fmt --all && rtk cargo test`
|
||||
|
||||
|
||||
+259
-1
@@ -6,7 +6,7 @@
|
||||
//! used (see `Engine`); the compression is identical because both emit the same
|
||||
//! `file:line:content` shape.
|
||||
|
||||
use crate::core::stream::{exec_capture, exec_capture_stdin, CaptureResult};
|
||||
use crate::core::stream::{exec_capture, exec_capture_stdin, status_to_exit_code, CaptureResult};
|
||||
use crate::core::tracking;
|
||||
use crate::core::utils::{resolved_command, strip_ansi};
|
||||
use crate::core::{args_utils, config};
|
||||
@@ -287,6 +287,16 @@ impl Engine {
|
||||
Engine::Rg => &["-n", "--with-filename", "--null"],
|
||||
}
|
||||
}
|
||||
|
||||
/// Stdin is one explicit input, not a tree to skim: forcing `-I` there
|
||||
/// flipped binary-stream exit codes (silence + 1 where grep reports the
|
||||
/// match + 0).
|
||||
fn stdin_parse_flags(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
Engine::Grep => &["-n", "-H", "--null"],
|
||||
Engine::Rg => &["-n", "--with-filename", "--null"],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the agent's exact engine + flags for the grouping path, appending only the
|
||||
@@ -353,6 +363,193 @@ fn has_context_flag(flags: &[String]) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// Tracking-metrics buffer bound: best-effort on unbounded stdin.
|
||||
const STREAM_BUFFER_CAP: usize = 65_536;
|
||||
|
||||
fn stdin_only_paths(paths: &[String]) -> bool {
|
||||
paths.is_empty() || paths.iter().all(|p| p == "-")
|
||||
}
|
||||
|
||||
struct StdinStream<'a> {
|
||||
engine: Engine,
|
||||
extra_args: &'a [String],
|
||||
patterns: &'a [String],
|
||||
pattern_display: &'a str,
|
||||
real_cmd: &'a str,
|
||||
rtk_label: &'a str,
|
||||
max_line_len: usize,
|
||||
max_results: usize,
|
||||
context_only: bool,
|
||||
}
|
||||
|
||||
fn spawn_stdin_engine(s: &StdinStream) -> Result<std::process::Child> {
|
||||
let mut cmd = resolved_command(s.engine.bin());
|
||||
cmd.args(s.engine.stdin_parse_flags());
|
||||
for a in s.extra_args {
|
||||
cmd.arg(a);
|
||||
}
|
||||
for p in s.patterns {
|
||||
cmd.args(["-e", p]);
|
||||
}
|
||||
cmd.arg("--");
|
||||
cmd.stdin(std::process::Stdio::inherit());
|
||||
cmd.stdout(std::process::Stdio::piped());
|
||||
// Inherited stderr stays real-time and avoids a two-pipe read deadlock.
|
||||
cmd.stderr(std::process::Stdio::inherit());
|
||||
cmd.spawn().context("failed to spawn search engine")
|
||||
}
|
||||
|
||||
fn render_stream_line(
|
||||
line: &str,
|
||||
s: &StdinStream,
|
||||
show_file: bool,
|
||||
show_line: bool,
|
||||
context_re: Option<&Regex>,
|
||||
) -> String {
|
||||
match parse_match_line(line) {
|
||||
Some((file, line_num, is_match, content)) => {
|
||||
let cleaned = clean_line(content, s.max_line_len, context_re, s.pattern_display);
|
||||
let sep = if is_match { ':' } else { '-' };
|
||||
let mut r = String::new();
|
||||
if show_file {
|
||||
r.push_str(&compact_path(&file));
|
||||
r.push(sep);
|
||||
}
|
||||
if show_line {
|
||||
r.push_str(&line_num.to_string());
|
||||
r.push(sep);
|
||||
}
|
||||
r.push_str(&cleaned);
|
||||
r
|
||||
}
|
||||
// Unknown shapes pass through verbatim, minus the --null parse aid.
|
||||
None => line.replace('\0', ":"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Emits each match as it arrives: capture-to-EOF delivered nothing when a
|
||||
/// pipeline like `tail -f log | rtk grep ERROR` was killed (#2962). No upfront
|
||||
/// header — the total is unknowable mid-stream, which also means the
|
||||
/// never-worse output guard cannot apply here.
|
||||
fn run_streamed_stdin(timer: &tracking::TimedExecution, s: &StdinStream) -> Result<i32> {
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
|
||||
let mut child = spawn_stdin_engine(s)?;
|
||||
let Some(child_out) = child.stdout.take() else {
|
||||
let code = child.wait().map(status_to_exit_code).unwrap_or(1);
|
||||
return Ok(code);
|
||||
};
|
||||
|
||||
let context_re = if s.context_only {
|
||||
Regex::new(&format!(
|
||||
"(?i).{{0,20}}{}.*",
|
||||
regex::escape(s.pattern_display)
|
||||
))
|
||||
.ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let show_file = has_short_flag(s.extra_args, 'H')
|
||||
|| has_short_flag(s.extra_args, 'r')
|
||||
|| has_short_flag(s.extra_args, 'R')
|
||||
|| s.extra_args
|
||||
.iter()
|
||||
.any(|f| f == "--with-filename" || f == "--recursive");
|
||||
let show_line = !has_short_flag(s.extra_args, 'N')
|
||||
&& !s.extra_args.iter().any(|f| f == "--no-line-number");
|
||||
|
||||
// stdin is one pseudo-file: apply the same per-file cap as file mode.
|
||||
let cap = s.max_results.min(config::limits().grep_max_per_file);
|
||||
|
||||
let stdout = std::io::stdout();
|
||||
let mut out = stdout.lock();
|
||||
let mut reader = BufReader::new(child_out);
|
||||
let mut buf: Vec<u8> = Vec::new();
|
||||
let mut emitted: usize = 0;
|
||||
let mut total: usize = 0;
|
||||
let mut tee: Option<crate::core::tee::TeeStream> = None;
|
||||
let mut tracked = String::new();
|
||||
let mut output = String::new();
|
||||
|
||||
loop {
|
||||
buf.clear();
|
||||
// Byte-level read + lossy decode, matching the capture path's
|
||||
// from_utf8_lossy: one non-UTF-8 line must not abort the stream.
|
||||
match reader.read_until(b'\n', &mut buf) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(_) => {}
|
||||
}
|
||||
if buf.last() == Some(&b'\n') {
|
||||
buf.pop();
|
||||
if buf.last() == Some(&b'\r') {
|
||||
buf.pop();
|
||||
}
|
||||
}
|
||||
let line = String::from_utf8_lossy(&buf);
|
||||
// The tee and savings baseline hold what the engine printed
|
||||
// (parse aid normalized), not the compacted render.
|
||||
let raw = line.replace('\0', ":");
|
||||
let rendered = render_stream_line(&line, s, show_file, show_line, context_re.as_ref());
|
||||
total += 1;
|
||||
if tracked.len() < STREAM_BUFFER_CAP {
|
||||
tracked.push_str(&raw);
|
||||
tracked.push('\n');
|
||||
}
|
||||
|
||||
if total <= cap {
|
||||
// Downstream closed early: stop emitting, never fail the command.
|
||||
if writeln!(out, "{}", rendered).is_err() {
|
||||
break;
|
||||
}
|
||||
emitted += 1;
|
||||
if output.len() < STREAM_BUFFER_CAP {
|
||||
output.push_str(&rendered);
|
||||
output.push('\n');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// The hint must go out at cap time — a followed stream never reaches
|
||||
// EOF, and a cap without a live recovery path mutes the monitor.
|
||||
if total == cap + 1 {
|
||||
tee = crate::core::tee::TeeStream::create(&format!("{}_stdin", s.engine.label()));
|
||||
if let Some(ref mut t) = tee {
|
||||
for h in tracked.lines().take(cap) {
|
||||
t.write_line(h);
|
||||
}
|
||||
let hint = format!(" +more in (standard input) {}", t.tail_hint(emitted + 1));
|
||||
if writeln!(out, "{}", hint).is_err() {
|
||||
break;
|
||||
}
|
||||
let _ = out.flush();
|
||||
output.push_str(&hint);
|
||||
output.push('\n');
|
||||
}
|
||||
}
|
||||
match tee {
|
||||
Some(ref mut t) => t.write_line(&raw),
|
||||
// No tee means no recovery path, so capping would hide data.
|
||||
None => {
|
||||
if writeln!(out, "{}", rendered).is_err() {
|
||||
break;
|
||||
}
|
||||
emitted += 1;
|
||||
if output.len() < STREAM_BUFFER_CAP {
|
||||
output.push_str(&rendered);
|
||||
output.push('\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(out);
|
||||
|
||||
let exit_code = child.wait().map(status_to_exit_code).unwrap_or(1);
|
||||
|
||||
timer.track(s.real_cmd, s.rtk_label, &tracked, &output);
|
||||
Ok(exit_code)
|
||||
}
|
||||
|
||||
pub fn run(
|
||||
engine: Engine,
|
||||
max_line_len: usize,
|
||||
@@ -408,6 +605,23 @@ pub fn run(
|
||||
return passthrough(&timer, engine, &args, &real_cmd);
|
||||
}
|
||||
|
||||
if stdin_only_paths(&paths) {
|
||||
return run_streamed_stdin(
|
||||
&timer,
|
||||
&StdinStream {
|
||||
engine,
|
||||
extra_args: &extra_args,
|
||||
patterns: &patterns,
|
||||
pattern_display: &pattern_display,
|
||||
real_cmd: &real_cmd,
|
||||
rtk_label: &rtk_label,
|
||||
max_line_len,
|
||||
max_results,
|
||||
context_only,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let result = engine_capture(engine, &extra_args, &patterns, &paths)?;
|
||||
|
||||
let exit_code = result.exit_code;
|
||||
@@ -1428,4 +1642,48 @@ mod tests {
|
||||
assert!(f(&["--context=1"]));
|
||||
assert!(!f(&["--color", "auto"]));
|
||||
}
|
||||
|
||||
// --- streamed stdin mode (#2962) ---
|
||||
|
||||
#[test]
|
||||
fn test_stdin_only_paths() {
|
||||
assert!(stdin_only_paths(&[]));
|
||||
assert!(stdin_only_paths(&["-".to_string()]));
|
||||
assert!(!stdin_only_paths(&["file.txt".to_string()]));
|
||||
assert!(!stdin_only_paths(&["-".to_string(), "file.txt".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_render_stream_line() {
|
||||
let s = StdinStream {
|
||||
engine: Engine::Grep,
|
||||
extra_args: &[],
|
||||
patterns: &[],
|
||||
pattern_display: "match",
|
||||
real_cmd: "grep match",
|
||||
rtk_label: "rtk grep",
|
||||
max_line_len: 80,
|
||||
max_results: 200,
|
||||
context_only: false,
|
||||
};
|
||||
assert_eq!(
|
||||
render_stream_line("(standard input)\u{0}7:match here", &s, false, true, None),
|
||||
"7:match here"
|
||||
);
|
||||
assert_eq!(
|
||||
render_stream_line("(standard input)\u{0}8-context here", &s, false, true, None),
|
||||
"8-context here"
|
||||
);
|
||||
assert_eq!(
|
||||
render_stream_line("(standard input)\u{0}7:match here", &s, false, false, None),
|
||||
"match here"
|
||||
);
|
||||
// Unparsed shapes (context separators, engine notices) pass through
|
||||
// verbatim, minus the --null parse aid.
|
||||
assert_eq!(render_stream_line("--", &s, false, true, None), "--");
|
||||
assert_eq!(
|
||||
render_stream_line("odd\u{0}shape", &s, false, true, None),
|
||||
"odd:shape"
|
||||
);
|
||||
}
|
||||
}
|
||||
+102
-9
@@ -188,24 +188,24 @@ pub fn tee_and_hint(raw: &str, command_slug: &str, exit_code: i32) -> Option<Str
|
||||
Some(format_hint(&path))
|
||||
}
|
||||
|
||||
fn force_tee_path(content: &str, command_slug: &str) -> Option<PathBuf> {
|
||||
fn enabled_tee_dir() -> Option<(Config, PathBuf)> {
|
||||
if std::env::var("RTK_TEE").ok().as_deref() == Some("0") {
|
||||
return None;
|
||||
}
|
||||
|
||||
if content.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let config = Config::load().ok()?;
|
||||
|
||||
if !config.tee.enabled {
|
||||
return None;
|
||||
}
|
||||
|
||||
let tee_dir = get_tee_dir(&config)?;
|
||||
let tee_dir = std::fs::create_dir_all(&tee_dir).ok().and(Some(tee_dir))?;
|
||||
std::fs::create_dir_all(&tee_dir).ok()?;
|
||||
Some((config, tee_dir))
|
||||
}
|
||||
|
||||
fn force_tee_path(content: &str, command_slug: &str) -> Option<PathBuf> {
|
||||
if content.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (config, tee_dir) = enabled_tee_dir()?;
|
||||
write_tee_file(
|
||||
content,
|
||||
command_slug,
|
||||
@@ -235,6 +235,66 @@ pub fn force_tee_tail_hint(
|
||||
))
|
||||
}
|
||||
|
||||
/// Write-through tee: each line is flushed on arrival so the recovery file
|
||||
/// survives a killed pipeline (#2962).
|
||||
pub struct TeeStream {
|
||||
file: std::fs::File,
|
||||
path: PathBuf,
|
||||
written: usize,
|
||||
max_bytes: usize,
|
||||
capped: bool,
|
||||
}
|
||||
|
||||
impl TeeStream {
|
||||
pub fn create(command_slug: &str) -> Option<TeeStream> {
|
||||
let (config, tee_dir) = enabled_tee_dir()?;
|
||||
let epoch = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.ok()?
|
||||
.as_secs();
|
||||
let path = tee_dir.join(format!("{}_{}.log", epoch, sanitize_slug(command_slug)));
|
||||
let stream = TeeStream::new_at(path, config.tee.max_file_size)?;
|
||||
cleanup_old_files(&tee_dir, config.tee.max_files);
|
||||
Some(stream)
|
||||
}
|
||||
|
||||
fn new_at(path: PathBuf, max_bytes: usize) -> Option<TeeStream> {
|
||||
let file = std::fs::File::create(&path).ok()?;
|
||||
Some(TeeStream {
|
||||
file,
|
||||
path,
|
||||
written: 0,
|
||||
max_bytes,
|
||||
capped: false,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn write_line(&mut self, line: &str) {
|
||||
use std::io::Write;
|
||||
if self.capped {
|
||||
return;
|
||||
}
|
||||
if self.written + line.len() + 1 > self.max_bytes {
|
||||
self.capped = true;
|
||||
let _ = writeln!(self.file, "\n--- truncated at {} bytes ---", self.written);
|
||||
let _ = self.file.flush();
|
||||
return;
|
||||
}
|
||||
if writeln!(self.file, "{}", line).is_ok() {
|
||||
self.written += line.len() + 1;
|
||||
let _ = self.file.flush();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn tail_hint(&self, line_offset: usize) -> String {
|
||||
format!(
|
||||
"[see remaining: tail -n +{} {}]",
|
||||
line_offset,
|
||||
display_path(&self.path)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// TeeMode controls when tee writes files.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
@@ -524,4 +584,37 @@ directory = "/tmp/rtk-tee"
|
||||
assert!(hint.ends_with(']'));
|
||||
assert!(hint.contains("123_docker_images.log"));
|
||||
}
|
||||
|
||||
// --- TeeStream (write-through streaming tee, #2962) ---
|
||||
|
||||
#[test]
|
||||
fn test_tee_stream_writes_lines_and_hint() {
|
||||
let path = std::env::temp_dir().join(format!("rtk_tee_stream_{}.log", std::process::id()));
|
||||
let mut t = TeeStream::new_at(path.clone(), 1024).expect("create stream");
|
||||
t.write_line("one");
|
||||
t.write_line("two");
|
||||
let content = std::fs::read_to_string(&path).expect("read tee file");
|
||||
assert_eq!(content, "one\ntwo\n");
|
||||
let hint = t.tail_hint(2);
|
||||
assert!(hint.starts_with("[see remaining: tail -n +2 "));
|
||||
assert!(hint.ends_with(']'));
|
||||
// nosemgrep: filesystem-deletion
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tee_stream_caps_at_max_bytes_with_marker() {
|
||||
let path = std::env::temp_dir().join(format!("rtk_tee_cap_{}.log", std::process::id()));
|
||||
let mut t = TeeStream::new_at(path.clone(), 10).expect("create stream");
|
||||
t.write_line("12345678");
|
||||
t.write_line("overflow line");
|
||||
t.write_line("ignored after cap");
|
||||
let content = std::fs::read_to_string(&path).expect("read tee file");
|
||||
assert!(content.starts_with("12345678\n"));
|
||||
assert!(content.contains("truncated at 9 bytes"));
|
||||
assert!(!content.contains("overflow line"));
|
||||
assert!(!content.contains("ignored after cap"));
|
||||
// nosemgrep: filesystem-deletion
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ When a hook sends `cargo fmt --all && cargo test 2>&1 | tail -20`:
|
||||
→ [Arg("cargo"), Arg("test"), Redirect("2>&1"), Operator("&&"), Arg("git"), Arg("status")]
|
||||
```
|
||||
|
||||
**Compound splitting** — The rewrite engine walks the tokens, splitting on `Operator` (`&&`, `||`, `;`) and `Pipe` (`|`). Each segment is rewritten independently. For pipes, only the left side is rewritten (the pipe consumer like `grep` or `head` runs raw). `find`/`fd` before a pipe is never rewritten because rtk's grouped output format breaks pipe consumers like `xargs`.
|
||||
**Compound splitting** — The rewrite engine walks the tokens, splitting on `Operator` (`&&`, `||`, `;`) and `Pipe` (`|`, `|&`). Each segment is rewritten independently. A stage feeding a pipe is rewritten only when every downstream stage is display-only (`head`, `tail` without a follow flag, `cat`): those stages just bound what the agent reads, so rtk-shaped output is still fine. Any content-consuming stage (`wc`, `xargs`, …) keeps the producer raw — rtk's reshaped output corrupts programs that parse it (#2962, #1560, #439). The **final** stage of a pipe group is the exception: its stdout goes to the agent, so it is rewritten when its resolved command is in `STDIN_SAFE_FINAL` (`grep`, `rg` — filters that read stdin, stream instead of buffering to EOF, and preserve exit codes). Stage identity is resolved through the same wrapper stripping as the rewriter itself (sudo/env, shell builtins, transparent_prefixes, absolute paths), so `command wc -l` cannot bypass the check and `command grep` still qualifies. Intermediate stages are never rewritten.
|
||||
|
||||
**Per-segment rewriting** — Each segment goes through:
|
||||
|
||||
|
||||
@@ -118,6 +118,15 @@ fn tokenize_inner(input: &str, emit_newline: bool) -> Vec<ParsedToken> {
|
||||
value: "||".into(),
|
||||
offset: start,
|
||||
});
|
||||
} else if chars.peek() == Some(&'&') {
|
||||
// Tokenizing `|&` as pipe + `&` made the rewriter emit `| &`.
|
||||
chars.next();
|
||||
byte_pos += 1;
|
||||
tokens.push(ParsedToken {
|
||||
kind: TokenKind::Pipe,
|
||||
value: "|&".into(),
|
||||
offset: start,
|
||||
});
|
||||
} else {
|
||||
tokens.push(ParsedToken {
|
||||
kind: TokenKind::Pipe,
|
||||
@@ -652,6 +661,29 @@ mod tests {
|
||||
assert!(!tokens.iter().any(|t| t.kind == TokenKind::Pipe));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stderr_pipe_single_token() {
|
||||
let tokens = tokenize("grep x f |& wc -l");
|
||||
let pipes: Vec<_> = tokens
|
||||
.iter()
|
||||
.filter(|t| t.kind == TokenKind::Pipe)
|
||||
.collect();
|
||||
assert_eq!(pipes.len(), 1);
|
||||
assert_eq!(pipes[0].value, "|&");
|
||||
assert!(!tokens
|
||||
.iter()
|
||||
.any(|t| t.kind == TokenKind::Shellism && t.value == "&"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stderr_pipe_not_confused_with_background() {
|
||||
let tokens = tokenize("cmd1 & cmd2");
|
||||
assert!(tokens
|
||||
.iter()
|
||||
.any(|t| t.kind == TokenKind::Shellism && t.value == "&"));
|
||||
assert!(!tokens.iter().any(|t| t.kind == TokenKind::Pipe));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_multiple_pipes() {
|
||||
let tokens = tokenize("a | b | c");
|
||||
|
||||
+346
-45
@@ -5,7 +5,7 @@ use lazy_static::lazy_static;
|
||||
use regex::{Regex, RegexSet};
|
||||
use std::path::Path;
|
||||
|
||||
use super::lexer::{split_on_operators, tokenize, TokenKind};
|
||||
use super::lexer::{split_on_operators, tokenize, ParsedToken, TokenKind};
|
||||
use super::rules::{IGNORED_EXACT, IGNORED_PREFIXES, RULES};
|
||||
|
||||
const PHP_TOOL_NAMES: [&str; 6] = ["phpunit", "phpstan", "ecs", "pest", "paratest", "pint"];
|
||||
@@ -595,6 +595,111 @@ pub fn rewrite_command(
|
||||
rewrite_compound(trimmed, &compiled, &normalized_prefixes)
|
||||
}
|
||||
|
||||
/// Strips the same wrapper layers as `rewrite_segment_inner` so eligibility
|
||||
/// checks cannot be bypassed by `command grep`, `sudo grep`, or
|
||||
/// `/usr/bin/grep` (#2962).
|
||||
fn resolve_stage_command<'a>(seg: &'a str, transparent_prefixes: &[String]) -> &'a str {
|
||||
let mut current = seg.trim();
|
||||
for _ in 0..MAX_PREFIX_DEPTH {
|
||||
let mut next = current;
|
||||
if let Some(m) = ENV_PREFIX.find(next) {
|
||||
next = next[m.end()..].trim_start();
|
||||
}
|
||||
if let Some(rest) = strip_one_wrapper(next, transparent_prefixes) {
|
||||
next = rest.trim_start();
|
||||
}
|
||||
let first = next.split(char::is_whitespace).next().unwrap_or("");
|
||||
if let Some(pos) = first.rfind('/') {
|
||||
if pos + 1 < first.len() {
|
||||
next = &next[pos + 1..];
|
||||
}
|
||||
}
|
||||
if next == current {
|
||||
break;
|
||||
}
|
||||
current = next;
|
||||
}
|
||||
current
|
||||
}
|
||||
|
||||
/// Shared by `rewrite_segment_inner` and `resolve_stage_command` so the
|
||||
/// rewriter and the eligibility checks cannot drift on what a wrapper is.
|
||||
fn strip_one_wrapper<'a>(cmd: &'a str, transparent_prefixes: &[String]) -> Option<&'a str> {
|
||||
for &prefix in BUILTIN_TRANSPARENT_PREFIXES {
|
||||
if let Some(rest) = strip_word_prefix(cmd, prefix) {
|
||||
return Some(rest);
|
||||
}
|
||||
}
|
||||
for prefix in transparent_prefixes {
|
||||
if let Some(rest) = strip_word_prefix(cmd, prefix) {
|
||||
return Some(rest);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Display-only stages bound stdin for the agent without parsing content.
|
||||
/// `tail -f` waits on stdin forever, so follow flags disqualify it.
|
||||
fn is_display_only_stage(seg: &str, transparent_prefixes: &[String]) -> bool {
|
||||
let resolved = resolve_stage_command(seg, transparent_prefixes);
|
||||
let mut words = resolved.split_whitespace();
|
||||
let cmd = words.next().unwrap_or("");
|
||||
match cmd {
|
||||
"head" | "cat" => true,
|
||||
"tail" => !words.any(|arg| {
|
||||
arg == "-F"
|
||||
|| arg.starts_with("--follow")
|
||||
|| (arg.starts_with('-') && !arg.starts_with("--") && arg[1..].contains(['f', 'F']))
|
||||
}),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Entries must read stdin, stream instead of buffering to EOF, and preserve
|
||||
/// the engine's exit codes — verify all three before adding one.
|
||||
const STDIN_SAFE_FINAL: &[&str] = &["grep", "rg"];
|
||||
|
||||
fn is_stdin_safe_final_stage(seg: &str, transparent_prefixes: &[String]) -> bool {
|
||||
let resolved = resolve_stage_command(seg, transparent_prefixes);
|
||||
let cmd = resolved.split_whitespace().next().unwrap_or("");
|
||||
STDIN_SAFE_FINAL.contains(&cmd)
|
||||
}
|
||||
|
||||
/// One span per pipe token; the producer before the first pipe is excluded.
|
||||
fn pipe_group_stage_spans(
|
||||
tokens: &[ParsedToken],
|
||||
pipe_offset: usize,
|
||||
group_end: usize,
|
||||
) -> Vec<(usize, usize)> {
|
||||
let pipes: Vec<&ParsedToken> = tokens
|
||||
.iter()
|
||||
.filter(|t| t.kind == TokenKind::Pipe && t.offset >= pipe_offset && t.offset < group_end)
|
||||
.collect();
|
||||
pipes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, p)| {
|
||||
let start = p.offset + p.value.len();
|
||||
let end = pipes.get(i + 1).map(|n| n.offset).unwrap_or(group_end);
|
||||
(start, end)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A content-consuming stage (`wc`, `xargs`, …) parses the producer's stdout,
|
||||
/// so rtk-shaped output would corrupt it (#2962, #1560, #439).
|
||||
fn pipe_tail_display_only(
|
||||
cmd: &str,
|
||||
spans: &[(usize, usize)],
|
||||
transparent_prefixes: &[String],
|
||||
) -> bool {
|
||||
!spans.is_empty()
|
||||
&& spans.iter().all(|&(start, end)| {
|
||||
let stage = cmd[start..end].trim();
|
||||
!stage.is_empty() && is_display_only_stage(stage, transparent_prefixes)
|
||||
})
|
||||
}
|
||||
|
||||
/// Rewrite a compound command (with `&&`, `||`, `;`, `|`) by rewriting each segment.
|
||||
fn rewrite_compound(
|
||||
cmd: &str,
|
||||
@@ -637,36 +742,62 @@ fn rewrite_compound(
|
||||
}
|
||||
TokenKind::Pipe => {
|
||||
let seg = cmd[seg_start..tok.offset].trim();
|
||||
let is_pipe_incompatible = seg.starts_with("find ")
|
||||
|| seg == "find"
|
||||
|| seg.starts_with("fd ")
|
||||
|| seg == "fd";
|
||||
let rewritten = if is_pipe_incompatible {
|
||||
seg.to_string()
|
||||
} else {
|
||||
rewrite_segment(seg, excluded, transparent_prefixes)
|
||||
.unwrap_or_else(|| seg.to_string())
|
||||
};
|
||||
if rewritten != seg {
|
||||
any_changed = true;
|
||||
}
|
||||
result.push_str(&rewritten);
|
||||
|
||||
let pipe_group_end = tokens.iter().find(|t| {
|
||||
t.offset > tok.offset
|
||||
&& (t.kind == TokenKind::Operator
|
||||
|| (t.kind == TokenKind::Shellism && t.value == "&"))
|
||||
});
|
||||
|
||||
let group_end_off = pipe_group_end.map(|t| t.offset).unwrap_or(cmd.len());
|
||||
let spans = pipe_group_stage_spans(&tokens, tok.offset, group_end_off);
|
||||
let all_display = pipe_tail_display_only(cmd, &spans, transparent_prefixes);
|
||||
let rewritten = if all_display {
|
||||
rewrite_segment(seg, excluded, transparent_prefixes)
|
||||
.unwrap_or_else(|| seg.to_string())
|
||||
} else {
|
||||
seg.to_string()
|
||||
};
|
||||
if rewritten != seg {
|
||||
any_changed = true;
|
||||
}
|
||||
result.push_str(&rewritten);
|
||||
|
||||
// The final stage's stdout goes to the agent, not a program —
|
||||
// the one pipe position where filtering is safe.
|
||||
let mut tail: Option<String> = None;
|
||||
if !all_display {
|
||||
if let Some(&(fs, fe)) = spans.last() {
|
||||
let final_seg = cmd[fs..fe].trim();
|
||||
if !final_seg.is_empty()
|
||||
&& is_stdin_safe_final_stage(final_seg, transparent_prefixes)
|
||||
{
|
||||
if let Some(rf) =
|
||||
rewrite_segment(final_seg, excluded, transparent_prefixes)
|
||||
{
|
||||
if rf != final_seg {
|
||||
tail = Some(format!("{} {}", cmd[tok.offset..fs].trim(), rf));
|
||||
any_changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match pipe_group_end {
|
||||
Some(next_op) => {
|
||||
result.push(' ');
|
||||
result.push_str(cmd[tok.offset..next_op.offset].trim());
|
||||
match tail {
|
||||
Some(t) => result.push_str(&t),
|
||||
None => result.push_str(cmd[tok.offset..next_op.offset].trim()),
|
||||
}
|
||||
seg_start = next_op.offset;
|
||||
}
|
||||
None => {
|
||||
result.push(' ');
|
||||
result.push_str(cmd[tok.offset..].trim_start());
|
||||
match tail {
|
||||
Some(t) => result.push_str(&t),
|
||||
None => result.push_str(cmd[tok.offset..].trim_start()),
|
||||
}
|
||||
return if any_changed { Some(result) } else { None };
|
||||
}
|
||||
}
|
||||
@@ -833,26 +964,13 @@ fn rewrite_segment_inner(
|
||||
return Some(format!("{}{}", env_prefix, rewritten));
|
||||
}
|
||||
|
||||
for &prefix in BUILTIN_TRANSPARENT_PREFIXES {
|
||||
if let Some(rest) = strip_word_prefix(trimmed, prefix) {
|
||||
if rest.is_empty() {
|
||||
return None;
|
||||
}
|
||||
return rewrite_segment_inner(rest, excluded, transparent_prefixes, depth + 1)
|
||||
.map(|rewritten| format!("{} {}", prefix, rewritten));
|
||||
}
|
||||
}
|
||||
|
||||
// User-configured wrapper prefixes (e.g. `docker exec mycontainer`). Same
|
||||
// strip-recurse-reprepend contract as the builtin list above.
|
||||
for prefix in transparent_prefixes {
|
||||
if let Some(rest) = strip_word_prefix(trimmed, prefix) {
|
||||
if rest.is_empty() {
|
||||
return None;
|
||||
}
|
||||
return rewrite_segment_inner(rest, excluded, transparent_prefixes, depth + 1)
|
||||
.map(|rewritten| format!("{} {}", prefix, rewritten));
|
||||
if let Some(rest) = strip_one_wrapper(trimmed, transparent_prefixes) {
|
||||
if rest.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let prefix = trimmed[..trimmed.len() - rest.len()].trim_end();
|
||||
return rewrite_segment_inner(rest, excluded, transparent_prefixes, depth + 1)
|
||||
.map(|rewritten| format!("{} {}", prefix, rewritten));
|
||||
}
|
||||
|
||||
// Strip trailing stderr/stdout redirects before matching (#530)
|
||||
@@ -1693,10 +1811,13 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_pipe_first_only() {
|
||||
// After a pipe, the filter command stays raw
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("git log -10 | grep feat", &[]),
|
||||
Some("rtk git log -10 | grep feat".into())
|
||||
Some("git log -10 | rtk grep feat".into())
|
||||
);
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("git log -10 | head -5", &[]),
|
||||
Some("rtk git log -10 | head -5".into())
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3549,10 +3670,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_compound_pipe_raw_filter() {
|
||||
// Pipe: rewrite first segment only, pass through rest unchanged
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("cargo test | grep FAILED", &[]),
|
||||
Some("rtk cargo test | grep FAILED".into())
|
||||
Some("cargo test | rtk grep FAILED".into())
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3560,7 +3680,7 @@ mod tests {
|
||||
fn test_rewrite_compound_pipe_git_grep() {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("git log -10 | grep feat", &[]),
|
||||
Some("rtk git log -10 | grep feat".into())
|
||||
Some("git log -10 | rtk grep feat".into())
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4288,6 +4408,187 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
// --- Pipe-feeding stages stay raw unless tail is display-only (#2962, #1560, #439) ---
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_pipe_content_consumers_stay_raw() {
|
||||
// grep|wc counted 28 for 60 real matches (#2962).
|
||||
for cmd in [
|
||||
"grep -n match sixty.txt | wc -l",
|
||||
"git status --short | wc -l",
|
||||
"git diff --name-only | xargs wc -l",
|
||||
"find . -name '*.rs' | xargs grep TODO",
|
||||
] {
|
||||
assert_eq!(rewrite_command_no_prefixes(cmd, &[]), None, "cmd: {cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_pipe_final_grep_rewritten() {
|
||||
for (cmd, expected) in [
|
||||
("git branch | grep feat", "git branch | rtk grep feat"),
|
||||
("ls -la | grep rs", "ls -la | rtk grep rs"),
|
||||
("cat f.txt | grep x", "cat f.txt | rtk grep x"),
|
||||
("ps aux | grep python", "ps aux | rtk grep python"),
|
||||
("cargo test | rg FAIL", "cargo test | rtk rg FAIL"),
|
||||
("grep a f.txt | grep b", "grep a f.txt | rtk grep b"),
|
||||
(
|
||||
"git log | head -5 | grep fix",
|
||||
"git log | head -5 | rtk grep fix",
|
||||
),
|
||||
(
|
||||
"tail -f app.log | grep ERROR",
|
||||
"tail -f app.log | rtk grep ERROR",
|
||||
),
|
||||
("make 2>&1 |& grep error", "make 2>&1 |& rtk grep error"),
|
||||
(
|
||||
"git log | command grep fix",
|
||||
"git log | command rtk grep fix",
|
||||
),
|
||||
("git log | sudo grep fix", "git log | sudo rtk grep fix"),
|
||||
] {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes(cmd, &[]),
|
||||
Some(expected.into()),
|
||||
"cmd: {cmd}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_pipe_final_grep_multi_group() {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("git log | grep a && ls | grep b", &[]),
|
||||
Some("git log | rtk grep a && ls | rtk grep b".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_pipe_final_grep_respects_exclusions() {
|
||||
let excluded = vec!["grep".to_string()];
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("git log | grep fix", &excluded),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_pipe_final_bare_grep_not_rewritten() {
|
||||
assert_eq!(rewrite_command_no_prefixes("git log | grep", &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_pipe_display_only_tail_keeps_rewrite() {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("git log --oneline | head -20", &[]),
|
||||
Some("rtk git log --oneline | head -20".into())
|
||||
);
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("ls -t | head -1", &[]),
|
||||
Some("rtk ls -t | head -1".into())
|
||||
);
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("git log | tail -50", &[]),
|
||||
Some("rtk git log | tail -50".into())
|
||||
);
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("git log | head -20 | cat", &[]),
|
||||
Some("rtk git log | head -20 | cat".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_pipe_find_subsumed_by_general_rule() {
|
||||
// The find/fd carve-out (#439) is subsumed by the general rule.
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("find . -name '*.rs' | xargs grep TODO", &[]),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("find . -name '*.rs' | head -20", &[]),
|
||||
Some("rtk find . -name '*.rs' | head -20".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_pipe_mixed_tail_stays_raw() {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("git log | head -20 | wc -l", &[]),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_pipe_tail_follow_not_display_only() {
|
||||
// tail -f waits on stdin forever; it must never gate a rewrite.
|
||||
assert_eq!(rewrite_command_no_prefixes("git log | tail -f", &[]), None);
|
||||
assert_eq!(rewrite_command_no_prefixes("git log | tail -F", &[]), None);
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("git log | tail --follow", &[]),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("git log | tail -fn 10", &[]),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_pipe_tail_wrapper_prefix_no_bypass() {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("git log | command wc -l", &[]),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("git log | command head -5", &[]),
|
||||
Some("rtk git log | command head -5".into())
|
||||
);
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("git log | /usr/bin/wc -l", &[]),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("sudo git log | head -5", &[]),
|
||||
Some("sudo rtk git log | head -5".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_pipe_transparent_prefix_tail_resolved() {
|
||||
let prefixes = vec!["direnv exec .".to_string()];
|
||||
assert_eq!(
|
||||
super::rewrite_command("git log | direnv exec . wc -l", &[], &prefixes),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_stderr_pipe_not_mangled() {
|
||||
// `|&` used to be reassembled as `| &`, a bash syntax error.
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("grep x f.txt |& wc -l", &[]),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("git status && grep x f.txt |& wc -l", &[]),
|
||||
Some("rtk git status && grep x f.txt |& wc -l".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_pipe_trailing_empty_stage() {
|
||||
assert_eq!(rewrite_command_no_prefixes("git log |", &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_pipe_display_tail_respects_exclusions() {
|
||||
let excluded = vec!["git".to_string()];
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("git log | head -5", &excluded),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
// --- Pipe + operator rewrite ---
|
||||
|
||||
#[test]
|
||||
@@ -4310,7 +4611,7 @@ mod tests {
|
||||
fn test_rewrite_pipe_then_or() {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("cargo test | grep FAIL || git stash", &[]),
|
||||
Some("rtk cargo test | grep FAIL || rtk git stash".into())
|
||||
Some("cargo test | rtk grep FAIL || rtk git stash".into())
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4321,7 +4622,7 @@ mod tests {
|
||||
"RUST_BACKTRACE=1 cargo test 2>&1 | grep FAILED && git stash",
|
||||
&[]
|
||||
),
|
||||
Some("RUST_BACKTRACE=1 rtk cargo test 2>&1 | grep FAILED && rtk git stash".into())
|
||||
Some("RUST_BACKTRACE=1 cargo test 2>&1 | rtk grep FAILED && rtk git stash".into())
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4329,7 +4630,7 @@ mod tests {
|
||||
fn test_rewrite_and_then_pipe() {
|
||||
assert_eq!(
|
||||
rewrite_command_no_prefixes("git status && cargo test | grep FAIL", &[]),
|
||||
Some("rtk git status && rtk cargo test | grep FAIL".into())
|
||||
Some("rtk git status && cargo test | rtk grep FAIL".into())
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -117,6 +117,17 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_pipe_inside_substitution_passthrough() {
|
||||
// Load-bearing for final-stage pipe rewrites: inside $(...) the
|
||||
// pipeline feeds the shell, not the agent, so this guard is what
|
||||
// keeps `rtk grep`'s reshaped output out of substitutions.
|
||||
assert_eq!(
|
||||
evaluate("echo $(git log | grep fix)", &[], &[]),
|
||||
RewriteOutcome::Passthrough
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_file_redirect_passthrough() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
//! Streaming stdin behavior of `rtk grep` (#2962 phase 2): matches must be
|
||||
//! emitted as they arrive, capped with a recovery hint at cap time, and the
|
||||
//! engine's exit codes preserved.
|
||||
|
||||
use std::io::Write;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
fn rtk() -> Command {
|
||||
let tmp = std::env::temp_dir().join("rtk_stream_test");
|
||||
let mut c = Command::new(env!("CARGO_BIN_EXE_rtk"));
|
||||
c.env("RTK_TEE_DIR", tmp.join("tee"));
|
||||
c.env("RTK_DB_PATH", tmp.join("test.db"));
|
||||
c
|
||||
}
|
||||
|
||||
fn run_with_stdin_bytes(args: &[&str], input: &[u8]) -> (String, i32) {
|
||||
let mut child = rtk()
|
||||
.args(args)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.expect("spawn rtk");
|
||||
child
|
||||
.stdin
|
||||
.take()
|
||||
.expect("child stdin")
|
||||
.write_all(input)
|
||||
.expect("write stdin");
|
||||
let out = child.wait_with_output().expect("wait rtk");
|
||||
(
|
||||
String::from_utf8_lossy(&out.stdout).into_owned(),
|
||||
out.status.code().unwrap_or(-1),
|
||||
)
|
||||
}
|
||||
|
||||
fn run_with_stdin(args: &[&str], input: &str) -> (String, i32) {
|
||||
run_with_stdin_bytes(args, input.as_bytes())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdin_grep_caps_with_hint_at_cap_time() {
|
||||
let input: String = (1..=60).map(|i| format!("match line {}\n", i)).collect();
|
||||
let (stdout, code) = run_with_stdin(&["grep", "line"], &input);
|
||||
assert_eq!(code, 0);
|
||||
let lines: Vec<&str> = stdout.lines().collect();
|
||||
assert_eq!(lines.len(), 26, "25 matches + hint, got:\n{}", stdout);
|
||||
assert!(lines[0].starts_with("1:"));
|
||||
assert!(lines[25].contains("+more in (standard input)"));
|
||||
assert!(lines[25].contains("tail -n +26"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdin_grep_small_stream_uncapped_no_hint() {
|
||||
let input = "a match\nno hit\nanother match\n";
|
||||
let (stdout, code) = run_with_stdin(&["grep", "match"], input);
|
||||
assert_eq!(code, 0);
|
||||
assert_eq!(stdout.lines().count(), 2);
|
||||
assert!(!stdout.contains("+more"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdin_grep_non_utf8_line_does_not_abort_stream() {
|
||||
// A single invalid byte used to end the stream: 1 of 3 lines delivered
|
||||
// with exit 0.
|
||||
let (stdout, code) = run_with_stdin_bytes(
|
||||
&["grep", "-a", "match"],
|
||||
b"match A\nmatch B \xff\nmatch C\n",
|
||||
);
|
||||
assert_eq!(code, 0);
|
||||
assert_eq!(stdout.lines().count(), 3, "got:\n{}", stdout);
|
||||
assert!(stdout.contains("match C"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdin_grep_binary_stream_keeps_engine_exit_code() {
|
||||
// Forcing -I flipped this to silence + exit 1; real grep reports the
|
||||
// match and exits 0.
|
||||
let (_, code) = run_with_stdin_bytes(&["grep", "match"], b"some match\x00data\n");
|
||||
assert_eq!(code, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdin_grep_exit_codes_preserved() {
|
||||
let (stdout, code) = run_with_stdin(&["grep", "absent"], "nothing here\n");
|
||||
assert_eq!(code, 1);
|
||||
assert!(stdout.is_empty());
|
||||
|
||||
let (_, code) = run_with_stdin(&["grep", "here"], "something here\n");
|
||||
assert_eq!(code, 0);
|
||||
}
|
||||
|
||||
/// A killed pipeline must still have delivered the capped head + hint, and
|
||||
/// the write-through tee must hold the overflow (buffer-to-EOF delivered
|
||||
/// nothing, #2962).
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
#[ignore] // timing-sensitive; run with: cargo test --ignored
|
||||
fn stdin_grep_delivers_before_eof_and_tee_survives_kill() {
|
||||
let tee_dir = std::env::temp_dir().join(format!("rtk_stream_kill_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&tee_dir);
|
||||
// Page the binary in so a cold start cannot consume the kill window.
|
||||
let _ = Command::new(env!("CARGO_BIN_EXE_rtk"))
|
||||
.arg("--version")
|
||||
.output();
|
||||
let pipeline = format!(
|
||||
"(for i in $(seq 1 4000); do echo \"tick $i ERROR padpadpadpadpadpad\"; sleep 0.005; done) | '{}' grep ERROR",
|
||||
env!("CARGO_BIN_EXE_rtk")
|
||||
);
|
||||
let out = Command::new("timeout")
|
||||
.args(["8", "bash", "-c", &pipeline])
|
||||
.env("RTK_TEE_DIR", &tee_dir)
|
||||
.env(
|
||||
"RTK_DB_PATH",
|
||||
std::env::temp_dir().join("rtk_stream_test").join("test.db"),
|
||||
)
|
||||
.output()
|
||||
.expect("run pipeline");
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
assert!(
|
||||
stdout.lines().count() >= 26,
|
||||
"head + hint must be delivered before EOF, got:\n{}",
|
||||
stdout
|
||||
);
|
||||
assert!(stdout.contains("+more in (standard input)"));
|
||||
|
||||
let tee_files: Vec<_> = std::fs::read_dir(&tee_dir)
|
||||
.expect("tee dir exists")
|
||||
.flatten()
|
||||
.collect();
|
||||
assert_eq!(tee_files.len(), 1, "one write-through tee file expected");
|
||||
let tee = std::fs::read_to_string(tee_files[0].path()).expect("tee content");
|
||||
// More lines than the emitted cap proves write-through of the overflow.
|
||||
assert!(
|
||||
tee.lines().count() > 25,
|
||||
"tee must capture overflow while streaming, got {} lines",
|
||||
tee.lines().count()
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&tee_dir);
|
||||
}
|
||||
Reference in new issue
Block a user