use std::io::{self, IsTerminal, Write};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicU8, Ordering};
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Mode {
Auto,
Always,
Never,
}
static MODE: AtomicU8 = AtomicU8::new(0);
pub fn init(mode: Mode) {
MODE.store(
match mode {
Mode::Auto => 0,
Mode::Always => 1,
Mode::Never => 2,
},
Ordering::Relaxed,
);
}
pub fn out() -> Out {
Out::new(match MODE.load(Ordering::Relaxed) {
1 => Mode::Always,
2 => Mode::Never,
_ => Mode::Auto,
})
}
pub struct Out {
mode: Mode,
writer: Option<Box<dyn Write>>,
child: Option<Child>,
}
impl Out {
pub fn new(mode: Mode) -> Out {
Out {
mode,
writer: None,
child: None,
}
}
fn start(&mut self) {
if self.writer.is_some() {
return;
}
let wanted = match self.mode {
Mode::Never => false,
Mode::Always => true,
Mode::Auto => io::stdout().is_terminal(),
};
if wanted {
if let Some((child, stdin)) = spawn_pager() {
self.child = Some(child);
self.writer = Some(Box::new(io::BufWriter::with_capacity(32 * 1024, stdin)));
return;
}
}
self.writer = Some(Box::new(io::BufWriter::with_capacity(
32 * 1024,
io::stdout(),
)));
}
#[cfg(test)]
fn started(&self) -> bool {
self.writer.is_some()
}
pub fn finish(mut self) -> io::Result<()> {
let flushed = match self.writer.take() {
Some(mut w) => w.flush(),
None => Ok(()),
};
if let Some(mut child) = self.child.take() {
let _ = child.wait();
}
flushed
}
}
impl Write for Out {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.start();
match self.writer.as_mut() {
Some(w) => w.write(buf),
None => Ok(buf.len()),
}
}
fn flush(&mut self) -> io::Result<()> {
match self.writer.as_mut() {
None => Ok(()),
Some(w) => w.flush(),
}
}
}
impl Drop for Out {
fn drop(&mut self) {
drop(self.writer.take());
if let Some(child) = self.child.as_mut() {
let _ = child.wait();
}
}
}
fn spawn_pager() -> Option<(Child, std::process::ChildStdin)> {
let (program, args) = pager_command()?;
let mut cmd = Command::new(&program);
cmd.args(&args).stdin(Stdio::piped());
cmd.stdout(Stdio::inherit()).stderr(Stdio::inherit());
if program.contains("less") && std::env::var_os("LESS").is_none() {
cmd.env("LESS", "FRX");
}
let mut child = cmd.spawn().ok()?;
match child.stdin.take() {
Some(stdin) => Some((child, stdin)),
None => {
let _ = child.kill();
let _ = child.wait();
None
}
}
}
fn pager_command() -> Option<(String, Vec<String>)> {
let configured = std::env::var("GITLIMES_PAGER")
.or_else(|_| std::env::var("PAGER"))
.ok();
let line = match configured {
Some(s) if s.trim().is_empty() => return None,
Some(s) => s,
None => "less".to_string(),
};
split_pager(&line, |candidate| Path::new(candidate).is_file())
}
fn split_pager(line: &str, exists: impl Fn(&str) -> bool) -> Option<(String, Vec<String>)> {
let line = line.trim();
if line.is_empty() {
return None;
}
if let Some(rest) = line.strip_prefix('"') {
let (program, args) = match rest.split_once('"') {
Some((p, a)) => (p, a),
None => (rest, ""),
};
if program.is_empty() {
return None;
}
return Some((
program.to_string(),
args.split_whitespace().map(str::to_string).collect(),
));
}
let tokens: Vec<&str> = line.split_whitespace().collect();
for n in (1..=tokens.len()).rev() {
let candidate = tokens[..n].join(" ");
if exists(&candidate) {
return Some((
candidate,
tokens[n..].iter().map(|s| s.to_string()).collect(),
));
}
}
let mut parts = tokens.into_iter().map(str::to_string);
let program = parts.next()?;
Some((program, parts.collect()))
}
#[cfg(test)]
mod tests {
use super::*;
fn fake_exists(p: &str) -> bool {
p.contains("real") && p.ends_with(".exe")
}
fn split(line: &str) -> Option<(String, Vec<String>)> {
split_pager(line, fake_exists)
}
#[test]
fn a_bare_program_takes_no_arguments() {
let (p, args) = split("less").unwrap();
assert_eq!(p, "less");
assert!(args.is_empty());
}
#[test]
fn arguments_still_split_on_whitespace() {
let (p, args) = split("less -S -N").unwrap();
assert_eq!(p, "less");
assert_eq!(args, vec!["-S", "-N"]);
}
#[test]
fn an_existing_path_with_spaces_keeps_its_arguments() {
let (p, args) = split(r"C:\Program Files\real\less.exe -S").unwrap();
assert_eq!(p, r"C:\Program Files\real\less.exe");
assert_eq!(args, vec!["-S"], "arguments after a spaced path survive");
}
#[test]
fn an_existing_path_with_spaces_is_not_chopped_into_arguments() {
let (p, args) = split(r"C:\Program Files\real\less.exe").unwrap();
assert_eq!(p, r"C:\Program Files\real\less.exe");
assert!(args.is_empty(), "the path must not become arguments");
}
#[test]
fn a_quoted_program_may_still_take_arguments() {
let (p, args) = split(r#""C:\Program Files\x\less.exe" -S"#).unwrap();
assert_eq!(p, r"C:\Program Files\x\less.exe");
assert_eq!(args, vec!["-S"]);
}
#[test]
fn quoting_wins_even_when_the_path_does_not_exist() {
let (p, args) = split(r#""/no/such/pager" --flag"#).unwrap();
assert_eq!(p, "/no/such/pager");
assert_eq!(args, vec!["--flag"]);
}
#[test]
fn an_unterminated_quote_is_taken_whole_rather_than_dropped() {
let (p, args) = split(r#""C:\Program Files\less.exe"#).unwrap();
assert_eq!(p, r"C:\Program Files\less.exe");
assert!(args.is_empty());
}
#[test]
fn nothing_at_all_disables_paging() {
assert!(split("").is_none());
assert!(split(" ").is_none());
assert!(split(r#"""#).is_none());
}
#[test]
fn a_nonexistent_spaced_command_still_splits() {
let (p, args) = split("my-pager --wrap").unwrap();
assert_eq!(p, "my-pager");
assert_eq!(args, vec!["--wrap"]);
}
#[test]
fn nothing_is_spawned_until_something_is_written() {
let out = Out::new(Mode::Always);
assert!(
!out.started(),
"constructing an Out must not spawn anything"
);
assert!(out.finish().is_ok(), "finishing an unused Out is a no-op");
}
#[test]
fn writing_chooses_a_destination() {
let mut out = Out::new(Mode::Never);
assert!(!out.started());
out.write_all(b"x").unwrap();
assert!(out.started(), "the first write decides where output goes");
out.finish().unwrap();
}
}