#![cfg(test)]
fn system32(exe: &str) -> String {
format!("%SystemRoot%\\System32\\{exe}")
}
fn path(file: &str) -> String {
if cfg!(windows) {
file.replace('/', "\\")
} else {
file.to_string()
}
}
pub(crate) fn classified(command: &str, marker: &str) -> String {
if cfg!(windows) {
format!("{command} && rem {marker}")
} else {
format!("{command} # {marker}")
}
}
pub(crate) const PASS: &str = "exit 0";
pub(crate) const FAIL: &str = "exit 1";
pub(crate) fn file_exists(file: &str) -> String {
if cfg!(windows) {
format!("if exist {} (exit 0) else (exit 1)", path(file))
} else {
format!("test -f {file}")
}
}
pub(crate) fn cat(file: &str) -> String {
if cfg!(windows) {
format!("type {}", path(file))
} else {
format!("cat {file}")
}
}
pub(crate) fn contains(needle: &str, file: &str) -> String {
debug_assert!(
!needle.chars().any(char::is_whitespace),
"contains() needle must be a single whitespace-free token; got {needle:?}"
);
if cfg!(windows) {
format!("{} {needle} {}", system32("findstr.exe"), path(file))
} else {
format!("grep -qF {needle} {file}")
}
}
pub(crate) fn files_equal(expected: &str, actual: &str) -> String {
if cfg!(windows) {
format!(
"{} /B {} {} >nul",
system32("fc.exe"),
path(expected),
path(actual)
)
} else {
format!("cmp -s {expected} {actual}")
}
}
pub(crate) fn contains_or_report(needle: &str, file: &str) -> String {
debug_assert!(
!needle.chars().any(char::is_whitespace),
"contains_or_report() needle must be a single token; got {needle:?}"
);
if cfg!(windows) {
format!(
"{} {needle} {} || (echo assertion failed & exit 1)",
system32("findstr.exe"),
path(file)
)
} else {
format!("grep -qF {needle} {file} || {{ echo 'assertion failed'; exit 1; }}")
}
}
pub(crate) fn touch(file: &str) -> String {
if cfg!(windows) {
format!("type nul > {}", path(file))
} else {
format!("touch {file}")
}
}
pub(crate) fn append_line(marker: &str, file: &str) -> String {
debug_assert!(
!marker.is_empty()
&& !marker.ends_with(|c: char| c.is_ascii_digit())
&& !marker
.chars()
.any(|c| matches!(c, '&' | '|' | '^' | '<' | '>' | '\'' | '\r' | '\n')),
"append_line() marker must be non-empty, must not end in a digit (cmd reads `echo \
v2>>f` as an fd-2 redirect), and must not contain shell metacharacters; got \
{marker:?}"
);
if cfg!(windows) {
format!("echo {marker}>> {}", path(file))
} else {
format!("printf '{marker}\\n' >> {file}")
}
}
pub(crate) fn print_cwd() -> String {
if cfg!(windows) { "cd" } else { "pwd" }.to_string()
}
pub(crate) fn sleep(secs: u32) -> String {
if cfg!(windows) {
format!("{} -n {} 127.0.0.1 >nul", system32("ping.exe"), secs + 1)
} else {
format!("sleep {secs}")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic(expected = "must not end in a digit")]
fn append_line_rejects_cmd_file_descriptor_suffixes() {
let _ = append_line("v2", "out.txt");
}
#[test]
#[should_panic(expected = "must not contain shell metacharacters")]
fn append_line_rejects_shell_metacharacters() {
let _ = append_line("left&right", "out.txt");
}
}