Compare commits

...
Author SHA1 Message Date
Patrick szymkowiak e3e0d77733 fix: proxy quote-aware split, redirect detection scan all tokens, npm test routing
- Proxy: replace split_whitespace with shell_split() that respects quotes (#388)
  e.g. 'git log --format="%H %s"' no longer splits on space inside quotes
- Discover: scan all tokens for redirect operators, not just nth(1) (#315)
  e.g. 'cat file.txt > output.txt' now correctly detected as write
- npm: replace tautological test with actual routing logic verification

Signed-off-by: Patrick Szymkowiak <patrick.szymkowiak@rtk-ai.app>
2026-03-11 10:57:55 +01:00
Patrick szymkowiak 1f7274c992 fix: npm routing, discover cat redirect, proxy quoted args (#470, #315, #388)
#470: rtk npm now correctly routes npm subcommands (install, list,
audit, etc.) without injecting "run". Previously, `rtk npm install`
was executed as `npm run install`.

#315: discover no longer counts `cat >`, `cat >>`, `cat |` as missed
savings. These are write/pipe operations with no terminal output to
compress.

#388: rtk proxy now auto-splits a single quoted argument containing
spaces. `rtk proxy 'head -50 file.php'` now works like
`rtk proxy head -50 file.php`.

Signed-off-by: Patrick Szymkowiak <patrick.szymkowiak@rtk-ai.app>
2026-03-11 10:57:55 +01:00
3 changed files with 313 additions and 41 deletions

No files matched your search

+41
View File
@@ -76,6 +76,26 @@ pub fn classify_command(cmd: &str) -> Classification {
return Classification::Ignored;
}
// Exclude cat/head/tail with redirect operators — these are writes, not reads (#315)
if cmd_clean.starts_with("cat ")
|| cmd_clean.starts_with("head ")
|| cmd_clean.starts_with("tail ")
{
let has_redirect = cmd_clean
.split_whitespace()
.skip(1)
.any(|t| t.starts_with('>') || t == "<" || t.starts_with(">>"));
if has_redirect {
return Classification::Unsupported {
base_command: cmd_clean
.split_whitespace()
.next()
.unwrap_or("cat")
.to_string(),
};
}
}
// Fast check with RegexSet — take the last (most specific) match
let matches: Vec<usize> = REGEX_SET.matches(cmd_clean).into_iter().collect();
if let Some(&idx) = matches.last() {
@@ -592,6 +612,27 @@ mod tests {
);
}
#[test]
fn test_classify_cat_redirect_not_supported() {
// cat > file and cat >> file are writes, not reads — should not be classified as supported
let write_commands = [
"cat > /tmp/output.txt",
"cat >> /tmp/output.txt",
"cat file.txt > output.txt",
"cat -n file.txt >> log.txt",
"head -10 README.md > output.txt",
"tail -f app.log > /dev/null",
];
for cmd in &write_commands {
match classify_command(cmd) {
Classification::Supported { .. } => {
panic!("{} should NOT be classified as Supported", cmd)
}
_ => {} // Unsupported or Ignored is fine
}
}
}
#[test]
fn test_classify_cd_ignored() {
assert_eq!(classify_command("cd /tmp"), Classification::Ignored);
+84 -6
View File
@@ -1109,6 +1109,33 @@ enum GtCommands {
Other(Vec<OsString>),
}
/// Split a string into shell-like tokens, respecting single and double quotes.
/// e.g. `git log --format="%H %s"` → ["git", "log", "--format=%H %s"]
fn shell_split(input: &str) -> Vec<String> {
let mut tokens = Vec::new();
let mut current = String::new();
let mut chars = input.chars().peekable();
let mut in_single = false;
let mut in_double = false;
while let Some(c) = chars.next() {
match c {
'\'' if !in_double => in_single = !in_single,
'"' if !in_single => in_double = !in_double,
' ' | '\t' if !in_single && !in_double => {
if !current.is_empty() {
tokens.push(std::mem::take(&mut current));
}
}
_ => current.push(c),
}
}
if !current.is_empty() {
tokens.push(current);
}
tokens
}
fn main() -> Result<()> {
// Fire-and-forget telemetry ping (1/day, non-blocking)
telemetry::maybe_ping();
@@ -1857,17 +1884,35 @@ fn main() -> Result<()> {
let timer = tracking::TimedExecution::start();
let cmd_name = args[0].to_string_lossy();
let cmd_args: Vec<String> = args[1..]
.iter()
.map(|s| s.to_string_lossy().into_owned())
.collect();
// If a single quoted arg contains spaces, split it respecting quotes (#388).
// e.g. rtk proxy 'head -50 file.php' → cmd=head, args=["-50", "file.php"]
// e.g. rtk proxy 'git log --format="%H %s"' → cmd=git, args=["log", "--format=%H %s"]
let (cmd_name, cmd_args): (String, Vec<String>) = if args.len() == 1 {
let full = args[0].to_string_lossy();
let parts = shell_split(&full);
if parts.len() > 1 {
(
parts[0].clone(),
parts[1..].to_vec(),
)
} else {
(full.into_owned(), vec![])
}
} else {
(
args[0].to_string_lossy().into_owned(),
args[1..]
.iter()
.map(|s| s.to_string_lossy().into_owned())
.collect(),
)
};
if cli.verbose > 0 {
eprintln!("Proxy mode: {} {}", cmd_name, cmd_args.join(" "));
}
let mut child = Command::new(cmd_name.as_ref())
let mut child = Command::new(&cmd_name)
.args(&cmd_args)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
@@ -2266,4 +2311,37 @@ mod tests {
);
}
}
#[test]
fn test_shell_split_simple() {
assert_eq!(shell_split("head -50 file.php"), vec!["head", "-50", "file.php"]);
}
#[test]
fn test_shell_split_double_quotes() {
assert_eq!(
shell_split(r#"git log --format="%H %s""#),
vec!["git", "log", "--format=%H %s"]
);
}
#[test]
fn test_shell_split_single_quotes() {
assert_eq!(
shell_split("grep -r 'hello world' ."),
vec!["grep", "-r", "hello world", "."]
);
}
#[test]
fn test_shell_split_single_word() {
assert_eq!(shell_split("ls"), vec!["ls"]);
}
#[test]
fn test_shell_split_empty() {
let result: Vec<String> = shell_split("");
assert!(result.is_empty());
}
}
+188 -35
View File
@@ -6,12 +6,92 @@ pub fn run(args: &[String], verbose: u8, skip_env: bool) -> Result<()> {
let timer = tracking::TimedExecution::start();
let mut cmd = Command::new("npm");
cmd.arg("run");
// Strip leading "run" to avoid doubling (rtk npm run build → npm run build, not npm run run build)
let effective_args = if args.first().map(|s| s.as_str()) == Some("run") {
// Determine if this is "npm run <script>" or another npm subcommand (install, list, etc.)
// Only inject "run" when args look like a script name, not a known npm subcommand.
let npm_subcommands = [
"install",
"i",
"ci",
"uninstall",
"remove",
"rm",
"update",
"up",
"list",
"ls",
"outdated",
"init",
"create",
"publish",
"pack",
"link",
"audit",
"fund",
"exec",
"explain",
"why",
"search",
"view",
"info",
"show",
"config",
"set",
"get",
"cache",
"prune",
"dedupe",
"doctor",
"help",
"version",
"prefix",
"root",
"bin",
"bugs",
"docs",
"home",
"repo",
"ping",
"whoami",
"token",
"profile",
"team",
"access",
"owner",
"deprecate",
"dist-tag",
"star",
"stars",
"login",
"logout",
"adduser",
"unpublish",
"pkg",
"diff",
"rebuild",
"test",
"t",
"start",
"stop",
"restart",
];
let first_arg = args.first().map(|s| s.as_str());
let is_run_explicit = first_arg == Some("run");
let is_npm_subcommand = first_arg
.map(|a| npm_subcommands.contains(&a) || a.starts_with('-'))
.unwrap_or(false);
let effective_args = if is_run_explicit {
// "rtk npm run build" → "npm run build"
cmd.arg("run");
&args[1..]
} else if is_npm_subcommand {
// "rtk npm install express" → "npm install express"
args
} else {
// "rtk npm build" → "npm run build" (assume script name)
cmd.arg("run");
args
};
@@ -24,10 +104,10 @@ pub fn run(args: &[String], verbose: u8, skip_env: bool) -> Result<()> {
}
if verbose > 0 {
eprintln!("Running: npm run {}", effective_args.join(" "));
eprintln!("Running: npm {}", args.join(" "));
}
let output = cmd.output().context("Failed to run npm run")?;
let output = cmd.output().context("Failed to run npm")?;
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
@@ -36,8 +116,8 @@ pub fn run(args: &[String], verbose: u8, skip_env: bool) -> Result<()> {
println!("{}", filtered);
timer.track(
&format!("npm run {}", effective_args.join(" ")),
&format!("rtk npm run {}", effective_args.join(" ")),
&format!("npm {}", args.join(" ")),
&format!("rtk npm {}", args.join(" ")),
&raw,
&filtered,
);
@@ -108,36 +188,109 @@ npm notice
}
#[test]
fn test_strip_leading_run_from_args() {
// When user runs `rtk npm run build`, args = ["run", "build"]
// The "run" should be stripped since cmd.arg("run") already adds it
let args: Vec<String> = vec!["run".into(), "build".into()];
let effective_args = if args.first().map(|s| s.as_str()) == Some("run") {
&args[1..]
} else {
&args[..]
};
assert_eq!(effective_args, &["build"]);
fn test_npm_subcommand_routing() {
// Test the actual routing logic used in run()
let npm_subcommands = [
"install",
"i",
"ci",
"uninstall",
"remove",
"rm",
"update",
"up",
"list",
"ls",
"outdated",
"init",
"create",
"publish",
"pack",
"link",
"audit",
"fund",
"exec",
"explain",
"why",
"search",
"view",
"info",
"show",
"config",
"set",
"get",
"cache",
"prune",
"dedupe",
"doctor",
"help",
"version",
"prefix",
"root",
"bin",
"bugs",
"docs",
"home",
"repo",
"ping",
"whoami",
"token",
"profile",
"team",
"access",
"owner",
"deprecate",
"dist-tag",
"star",
"stars",
"login",
"logout",
"adduser",
"unpublish",
"pkg",
"diff",
"rebuild",
"test",
"t",
"start",
"stop",
"restart",
];
// Helper: simulate the routing logic from run()
fn needs_run_injection(args: &[&str], subcommands: &[&str]) -> bool {
let first = args.first().copied();
let is_run_explicit = first == Some("run");
let is_subcommand = first
.map(|a| subcommands.contains(&a) || a.starts_with('-'))
.unwrap_or(false);
// "run" injection happens when: explicit "run" OR unknown script name
!is_run_explicit && !is_subcommand
}
// When user runs `rtk npm build`, args = ["build"]
// No stripping needed
let args2: Vec<String> = vec!["build".into()];
let effective_args2 = if args2.first().map(|s| s.as_str()) == Some("run") {
&args2[1..]
} else {
&args2[..]
};
assert_eq!(effective_args2, &["build"]);
// Known subcommands should NOT get "run" injected
for subcmd in &npm_subcommands {
assert!(
!needs_run_injection(&[subcmd], &npm_subcommands),
"'npm {}' should NOT inject 'run'",
subcmd
);
}
// When user runs `rtk npm run`, args = ["run"]
// Strip "run" → empty args (npm run with no script)
let args3: Vec<String> = vec!["run".into()];
let effective_args3 = if args3.first().map(|s| s.as_str()) == Some("run") {
&args3[1..]
} else {
&args3[..]
};
assert!(effective_args3.is_empty());
// Script names SHOULD get "run" injected
for script in &["build", "dev", "lint", "typecheck", "deploy"] {
assert!(
needs_run_injection(&[script], &npm_subcommands),
"'npm {}' SHOULD inject 'run'",
script
);
}
// Flags should NOT get "run" injected
assert!(!needs_run_injection(&["--version"], &npm_subcommands));
assert!(!needs_run_injection(&["-h"], &npm_subcommands));
// Explicit "run" should NOT inject another "run"
assert!(!needs_run_injection(&["run", "build"], &npm_subcommands));
}
#[test]