- Terminal: undo an inherited "ignore Ctrl+C" flag before starting a ConPTY shell (lutra_proc::enable_ctrl_c). Lutra started by the lutra CLI (CREATE_NEW_PROCESS_GROUP) passed it to every shell, so Ctrl+C stopped nothing. Test reruns itself with that flag. - Engine: an edited .gitignore/.ignore reports TreeChanged for its folder, so the tree greys newly ignored files (Add to .gitignore). - Find: "1 match", "1 file" instead of "1 files". - docs/alpha-checklist.md: steps corrected after the Windows dry run. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
310 lines
9.7 KiB
Rust
310 lines
9.7 KiB
Rust
//! Sessions with a real shell: `cmd.exe` on Windows, `/bin/sh` elsewhere.
|
|
//!
|
|
//! ConPTY asks for the cursor position (`ESC[6n`) when it starts and waits
|
|
//! for the answer; xterm.js gives it in the app, [`drive`] gives it here.
|
|
|
|
#![allow(
|
|
clippy::unwrap_used,
|
|
clippy::expect_used,
|
|
clippy::panic,
|
|
clippy::indexing_slicing
|
|
)]
|
|
|
|
use std::ffi::OsString;
|
|
use std::time::{Duration, Instant};
|
|
|
|
use lutra_terminal::{Exit, OUTPUT_CAP, Session, Shell, SpawnOptions, TerminalError, find_in_path};
|
|
|
|
/// The platform's plain shell.
|
|
fn plain_shell() -> std::path::PathBuf {
|
|
if cfg!(windows) {
|
|
find_in_path("cmd.exe").unwrap()
|
|
} else {
|
|
"/bin/sh".into()
|
|
}
|
|
}
|
|
|
|
/// Runs a one-line command with `cmd /c` or `sh -c`.
|
|
fn command(windows: &[&str], unix: &str) -> Shell {
|
|
let args: Vec<OsString> = if cfg!(windows) {
|
|
std::iter::once("/c")
|
|
.chain(windows.iter().copied())
|
|
.map(OsString::from)
|
|
.collect()
|
|
} else {
|
|
vec!["-c".into(), unix.into()]
|
|
};
|
|
Shell {
|
|
program: plain_shell(),
|
|
args,
|
|
}
|
|
}
|
|
|
|
/// An interactive plain shell.
|
|
fn interactive() -> Shell {
|
|
let args = if cfg!(windows) {
|
|
vec![OsString::from("/q")]
|
|
} else {
|
|
Vec::new()
|
|
};
|
|
Shell {
|
|
program: plain_shell(),
|
|
args,
|
|
}
|
|
}
|
|
|
|
fn spawn(shell: Shell, cols: u16) -> Session {
|
|
Session::spawn(SpawnOptions {
|
|
shell,
|
|
cwd: std::env::temp_dir(),
|
|
cols,
|
|
rows: 24,
|
|
env: Vec::new(),
|
|
})
|
|
.unwrap()
|
|
}
|
|
|
|
/// Takes output until `done` holds for it or the session exited (then the
|
|
/// exit is returned), answering cursor-position queries, for at most 30 s.
|
|
fn drive(session: &Session, done: impl Fn(&str) -> bool) -> (String, Option<Exit>) {
|
|
let deadline = Instant::now() + Duration::from_secs(30);
|
|
let mut all = String::new();
|
|
let mut answered = 0;
|
|
loop {
|
|
all.push_str(&session.take_output(64 * 1024));
|
|
let asked = all.matches("\x1b[6n").count();
|
|
while answered < asked {
|
|
let _ = session.write(b"\x1b[1;1R");
|
|
answered += 1;
|
|
}
|
|
if let Some(exit) = session.exit() {
|
|
return (all, Some(exit));
|
|
}
|
|
if done(&all) || Instant::now() > deadline {
|
|
return (all, None);
|
|
}
|
|
std::thread::sleep(Duration::from_millis(10));
|
|
}
|
|
}
|
|
|
|
/// Drives the session to its end.
|
|
fn finish(session: &Session) -> (String, Exit) {
|
|
let (out, exit) = drive(session, |_| false);
|
|
(out, exit.expect("the session did not exit in time"))
|
|
}
|
|
|
|
#[test]
|
|
fn echo_output_and_exit_code() {
|
|
let s = spawn(command(&["echo", "lutra-ok"], "echo lutra-ok"), 80);
|
|
assert!(s.pid().is_some());
|
|
let (out, exit) = finish(&s);
|
|
assert!(out.contains("lutra-ok"), "{out:?}");
|
|
assert_eq!(exit.code, Some(0));
|
|
assert_eq!(s.write(b"x"), Err(TerminalError::Exited));
|
|
}
|
|
|
|
#[test]
|
|
fn reports_the_exit_code() {
|
|
let s = spawn(command(&["exit", "3"], "exit 3"), 80);
|
|
assert_eq!(finish(&s).1.code, Some(3));
|
|
}
|
|
|
|
#[test]
|
|
fn input_reaches_the_shell() {
|
|
let s = spawn(interactive(), 120);
|
|
s.write(b"echo lutra-in-%OS%-$0\r").unwrap();
|
|
let (out, exit) = drive(&s, |out| out.contains("lutra-in-"));
|
|
assert!(exit.is_none());
|
|
assert!(out.contains("lutra-in-"), "{out:?}");
|
|
s.write(b"exit 5\r").unwrap();
|
|
assert_eq!(finish(&s).1.code, Some(5));
|
|
}
|
|
|
|
#[test]
|
|
fn multibyte_output_survives_read_boundaries() {
|
|
let text = "äöü€".repeat(1500);
|
|
let s = spawn(
|
|
command(&["echo", &text], &format!("printf '%s' '{text}'")),
|
|
200,
|
|
);
|
|
let (out, exit) = finish(&s);
|
|
assert_eq!(exit.code, Some(0));
|
|
assert!(!out.contains('\u{fffd}'), "replacement character in output");
|
|
assert!(out.matches('€').count() >= 1500, "characters were lost");
|
|
}
|
|
|
|
/// Padding of each line in the backpressure test, so that the output is
|
|
/// well over twice [`OUTPUT_CAP`] even if ConPTY drops a few bytes.
|
|
const PAD: &str =
|
|
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
|
|
|
|
/// The shell prints a file of about 3 MB with `type` / `cat`, which is
|
|
/// fast, so the test depends on the buffer and not on how quickly a shell
|
|
/// loop runs on a busy machine.
|
|
#[test]
|
|
fn a_full_buffer_stops_the_shell_without_dropping_output() {
|
|
let lines = 30_000;
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let file = dir.path().join("lines.txt");
|
|
let text: String = (1..=lines)
|
|
.map(|i| {
|
|
format!(
|
|
"line-{i}-{PAD}
|
|
"
|
|
)
|
|
})
|
|
.collect();
|
|
assert!(
|
|
text.len() > 2 * OUTPUT_CAP,
|
|
"the output must overfill the buffer by far"
|
|
);
|
|
std::fs::write(&file, text).unwrap();
|
|
let path = file.to_string_lossy().into_owned();
|
|
let s = spawn(command(&["type", &path], &format!("cat '{path}'")), 200);
|
|
let (mut out, exit) = drive(&s, |out| out.contains("line-1-"));
|
|
assert!(exit.is_none(), "the shell ended early: {out:?}");
|
|
let deadline = Instant::now() + Duration::from_secs(60);
|
|
while s.buffered_bytes() < OUTPUT_CAP {
|
|
assert!(Instant::now() < deadline, "the buffer never filled");
|
|
std::thread::sleep(Duration::from_millis(20));
|
|
}
|
|
std::thread::sleep(Duration::from_millis(500));
|
|
let buffered = s.buffered_bytes();
|
|
assert!(
|
|
buffered <= OUTPUT_CAP + 64 * 1024,
|
|
"buffered {buffered} bytes"
|
|
);
|
|
assert!(
|
|
s.exit().is_none(),
|
|
"the shell went on while the buffer was full"
|
|
);
|
|
let first = s.take_output(10);
|
|
assert!(first.len() <= 10 && !first.is_empty());
|
|
out.push_str(&first);
|
|
let deadline = Instant::now() + Duration::from_secs(120);
|
|
let exit = loop {
|
|
out.push_str(&s.take_output(256 * 1024));
|
|
if let Some(exit) = s.exit() {
|
|
break exit;
|
|
}
|
|
assert!(Instant::now() < deadline, "the shell did not finish");
|
|
std::thread::sleep(Duration::from_millis(5));
|
|
};
|
|
assert_eq!(exit.code, Some(0));
|
|
assert!(
|
|
out.contains(&format!("line-{lines}-")),
|
|
"the last line is missing"
|
|
);
|
|
let seen = (1..=lines)
|
|
.step_by(997)
|
|
.filter(|i| out.contains(&format!("line-{i}-")))
|
|
.count();
|
|
assert_eq!(seen, (1..=lines).step_by(997).count(), "lines were dropped");
|
|
}
|
|
|
|
#[test]
|
|
fn resizes_and_rejects_bad_sizes() {
|
|
let s = spawn(interactive(), 80);
|
|
s.resize(120, 40).unwrap();
|
|
assert!(matches!(
|
|
s.resize(0, 10),
|
|
Err(TerminalError::InvalidSize { .. })
|
|
));
|
|
assert!(matches!(
|
|
s.resize(80, 1001),
|
|
Err(TerminalError::InvalidSize { .. })
|
|
));
|
|
let _ = drive(&s, |out| !out.is_empty());
|
|
s.write(b"exit\r").unwrap();
|
|
finish(&s);
|
|
assert_eq!(s.resize(80, 24), Err(TerminalError::Exited));
|
|
}
|
|
|
|
#[test]
|
|
fn kill_ends_the_session() {
|
|
let mut s = spawn(interactive(), 80);
|
|
let _ = drive(&s, |out| !out.is_empty());
|
|
s.kill();
|
|
assert_eq!(s.write(b"x"), Err(TerminalError::Exited));
|
|
let deadline = Instant::now() + Duration::from_secs(10);
|
|
while s.exit().is_none() {
|
|
assert!(Instant::now() < deadline, "no exit after kill");
|
|
std::thread::sleep(Duration::from_millis(20));
|
|
}
|
|
assert_eq!(s.buffered_bytes(), 0);
|
|
}
|
|
|
|
#[test]
|
|
fn spawn_errors() {
|
|
let options = |shell: Shell, cwd: std::path::PathBuf, cols| SpawnOptions {
|
|
shell,
|
|
cwd,
|
|
cols,
|
|
rows: 24,
|
|
env: Vec::new(),
|
|
};
|
|
let tmp = std::env::temp_dir();
|
|
assert!(matches!(
|
|
Session::spawn(options(interactive(), tmp.join("lutra-no-such-dir"), 80)),
|
|
Err(TerminalError::Spawn(_))
|
|
));
|
|
assert!(matches!(
|
|
Session::spawn(options(
|
|
Shell::new("lutra-no-such-shell-x"),
|
|
tmp.clone(),
|
|
80
|
|
)),
|
|
Err(TerminalError::Spawn(_))
|
|
));
|
|
assert!(matches!(
|
|
Session::spawn(options(interactive(), tmp, 0)),
|
|
Err(TerminalError::InvalidSize { cols: 0, rows: 24 })
|
|
));
|
|
}
|
|
|
|
/// Set for the copy of this test binary that
|
|
/// [`ctrl_c_stops_a_program_when_lutra_ignores_ctrl_c`] starts.
|
|
#[cfg(windows)]
|
|
const CTRL_C_CHILD: &str = "LUTRA_TERMINAL_CTRL_C_CHILD";
|
|
|
|
/// Ctrl+C in the terminal stops a running program even when Lutra was
|
|
/// started with `CREATE_NEW_PROCESS_GROUP` (as `lutra` starts it), which
|
|
/// makes a process and its children ignore Ctrl+C. Runs
|
|
/// [`ctrl_c_child`] in a copy of this test binary started that way.
|
|
#[cfg(windows)]
|
|
#[test]
|
|
fn ctrl_c_stops_a_program_when_lutra_ignores_ctrl_c() {
|
|
use std::os::windows::process::CommandExt;
|
|
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
|
|
let out = std::process::Command::new(std::env::current_exe().unwrap())
|
|
.args(["--exact", "ctrl_c_child", "--nocapture", "--test-threads=1"])
|
|
.env(CTRL_C_CHILD, "1")
|
|
.creation_flags(CREATE_NEW_PROCESS_GROUP)
|
|
.output()
|
|
.unwrap();
|
|
let text =
|
|
String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr);
|
|
assert!(out.status.success(), "{text}");
|
|
assert!(text.contains("1 passed"), "{text}");
|
|
}
|
|
|
|
/// The part of [`ctrl_c_stops_a_program_when_lutra_ignores_ctrl_c`] that
|
|
/// runs in the copy; does nothing in a normal test run.
|
|
#[cfg(windows)]
|
|
#[test]
|
|
fn ctrl_c_child() {
|
|
if std::env::var_os(CTRL_C_CHILD).is_none() {
|
|
return;
|
|
}
|
|
let s = spawn(interactive(), 120);
|
|
s.write(b"ping -n 60 127.0.0.1\r").unwrap();
|
|
let (out, exit) = drive(&s, |out| out.matches("127.0.0.1").count() >= 3);
|
|
assert!(exit.is_none(), "{out:?}");
|
|
s.write(b"\x03").unwrap();
|
|
s.write(b"echo lutra-after-%OS%\r").unwrap();
|
|
let started = Instant::now();
|
|
let (out, exit) = drive(&s, |out| out.contains("lutra-after-Windows"));
|
|
assert!(exit.is_none(), "{out:?}");
|
|
assert!(out.contains("lutra-after-Windows"), "{out:?}");
|
|
assert!(started.elapsed() < Duration::from_secs(20), "{out:?}");
|
|
}
|