use std::fmt;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Block {
lines: Vec<String>,
}
impl Block {
pub fn new() -> Self {
Self::default()
}
pub fn push(&mut self, line: impl Into<String>) {
self.lines.push(line.into());
}
pub fn extend(&mut self, other: Block) {
self.lines.extend(other.lines);
}
pub fn lines(&self) -> &[String] {
&self.lines
}
pub fn into_lines(self) -> Vec<String> {
self.lines
}
pub fn len(&self) -> usize {
self.lines.len()
}
pub fn is_empty(&self) -> bool {
self.lines.is_empty()
}
pub fn plain(&self) -> String {
crate::text::strip_ansi(&self.to_string())
}
pub fn print(&self) {
if crate::output::json() {
return self.emit();
}
if crate::display::print_above(&self.lines, false) {
return;
}
crate::output::write(&self.lines.iter().map(|l| format!("{l}\n")).collect::<String>());
}
pub fn eprint(&self) {
if crate::output::json() {
return self.emit();
}
if crate::display::print_above(&self.lines, true) {
return;
}
for line in &self.lines {
crate::output::err_line(line);
}
}
}
impl Block {
pub fn page(&self) {
self.page_with(std::env::var("PAGER").ok(), std::env::var_os("LESS").is_some());
}
fn page_with(&self, pager: Option<String>, less_set: bool) {
use std::io::Write;
let paged = crate::output::target() == crate::Target::Stdout && crate::output::is_terminal();
if crate::output::json() || !paged || self.len() < crate::term::height() {
return self.print();
}
let pager = pager.filter(|p| !p.trim().is_empty());
let default = if cfg!(windows) { "more" } else { "less" };
let command = pager.unwrap_or_else(|| default.to_string());
let mut words = command.split_whitespace();
let program = words.next().unwrap_or(default);
let mut cmd = std::process::Command::new(program);
cmd.args(words).stdin(std::process::Stdio::piped());
if program.ends_with("less") && !less_set {
cmd.env("LESS", "-RFX");
}
let Ok(mut child) = cmd.spawn() else {
return self.print();
};
let _ = child
.stdin
.take()
.map(|mut stdin| stdin.write_all(format!("{self}\n").as_bytes()));
let _ = child.wait();
}
pub fn html(&self) -> String {
self.frame().html()
}
pub fn html_pre(&self) -> String {
self.frame().html_pre()
}
fn frame(&self) -> crate::app::Frame {
let width = self.lines.iter().map(|l| crate::text::width(l)).max().unwrap_or(0);
let mut frame = crate::app::Frame::new(width, self.len());
frame.lines(frame.area(), self);
frame
}
fn emit(&self) {
let lines: Vec<String> = self.lines.iter().map(|l| crate::text::strip_ansi(l)).collect();
crate::output::emit("block", &[("lines", crate::output::Val::List(&lines))]);
}
}
impl fmt::Display for Block {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.lines.join("\n"))
}
}
impl From<Vec<String>> for Block {
fn from(lines: Vec<String>) -> Self {
Block { lines }
}
}
impl FromIterator<String> for Block {
fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> Self {
Block {
lines: iter.into_iter().collect(),
}
}
}
impl IntoIterator for Block {
type Item = String;
type IntoIter = std::vec::IntoIter<String>;
fn into_iter(self) -> Self::IntoIter {
self.lines.into_iter()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::output::{Output, capture, with_output, with_terminal};
fn two() -> Block {
Block::from(vec!["b-one".to_string(), "b-two".to_string()])
}
#[test]
fn prints_as_lines_or_one_event() {
assert!(capture(|| two().print()).contains("b-one\nb-two\n"));
two().eprint();
let json = capture(|| with_output(Output::Json, || two().print()));
assert!(
json.contains(r#"{"event":"block","lines":["b-one","b-two"]}"#),
"{json}"
);
let json = capture(|| with_output(Output::Json, || two().eprint()));
assert!(json.contains(r#""lines":["b-one","b-two"]"#), "{json}");
}
#[test]
fn short_blocks_and_pipes_arent_paged() {
assert!(capture(|| two().page()).contains("b-one\n"));
assert!(capture(|| with_terminal(true, || two().page())).contains("b-one\n"));
let json = capture(|| with_output(Output::Json, || two().page()));
assert!(json.contains(r#""event":"block""#));
}
#[test]
fn blocks_are_built_and_taken_apart() {
let mut b = Block::new();
assert!(b.is_empty());
b.push("x");
b.extend(two());
assert_eq!(b.len(), 3);
assert_eq!(b.clone().into_lines(), ["x", "b-one", "b-two"]);
let back: Block = b.clone().into_iter().collect();
assert_eq!(back, b);
}
#[test]
fn tall_blocks_on_a_terminal_go_through_the_pager() {
let tall: Block = (0..crate::term::height() + 1).map(|i| format!("tall-{i}")).collect();
let shown = capture(|| with_terminal(true, || tall.page_with(Some("true".into()), true)));
assert!(cfg!(windows) || !shown.contains("tall-0"), "{shown}");
let missing = Some("/nonexistent/less -S".into());
assert!(capture(|| with_terminal(true, || tall.page_with(missing, false))).contains("tall-0\n"));
}
}