bat/src/controller.rs

285 lines
9.4 KiB
Rust
Raw Normal View History

use std::io::{self, BufRead, Write};
2018-08-23 22:37:27 +02:00
use crate::assets::HighlightingAssets;
use crate::config::{Config, VisibleLines};
#[cfg(feature = "git")]
use crate::diff::{get_git_diff, LineChanges};
2020-04-22 21:45:47 +02:00
use crate::error::*;
use crate::input::{Input, InputReader, OpenedInput};
#[cfg(feature = "lessopen")]
use crate::lessopen::LessOpenPreprocessor;
#[cfg(feature = "git")]
use crate::line_range::LineRange;
use crate::line_range::{LineRanges, RangeCheckResult};
use crate::output::OutputType;
2020-04-22 22:54:33 +02:00
#[cfg(feature = "paging")]
use crate::paging::PagingMode;
use crate::printer::{InteractivePrinter, OutputHandle, Printer, SimplePrinter};
2018-08-23 22:37:27 +02:00
use clircle::{Clircle, Identifier};
2018-08-23 22:37:27 +02:00
pub struct Controller<'a> {
config: &'a Config<'a>,
assets: &'a HighlightingAssets,
#[cfg(feature = "lessopen")]
preprocessor: Option<LessOpenPreprocessor>,
2018-08-23 22:37:27 +02:00
}
impl<'b> Controller<'b> {
pub fn new<'a>(config: &'a Config, assets: &'a HighlightingAssets) -> Controller<'a> {
Controller {
config,
assets,
#[cfg(feature = "lessopen")]
preprocessor: LessOpenPreprocessor::new().ok(),
}
2018-08-23 22:37:27 +02:00
}
pub fn run(
&self,
inputs: Vec<Input>,
output_buffer: Option<&mut dyn std::fmt::Write>,
) -> Result<bool> {
self.run_with_error_handler(inputs, output_buffer, default_error_handler)
2020-03-21 19:51:59 +01:00
}
2020-04-21 21:14:44 +02:00
pub fn run_with_error_handler(
&self,
2020-04-21 21:19:06 +02:00
inputs: Vec<Input>,
output_buffer: Option<&mut dyn std::fmt::Write>,
2024-01-10 13:46:13 +01:00
mut handle_error: impl FnMut(&Error, &mut dyn Write),
2020-04-21 21:14:44 +02:00
) -> Result<bool> {
2020-03-30 22:18:41 +02:00
let mut output_type;
#[cfg(feature = "paging")]
{
use crate::input::InputKind;
2020-03-30 22:18:41 +02:00
use std::path::Path;
// Do not launch the pager if NONE of the input files exist
let mut paging_mode = self.config.paging_mode;
if self.config.paging_mode != PagingMode::Never {
let call_pager = inputs.iter().any(|input| {
2020-04-22 16:27:34 +02:00
if let InputKind::OrdinaryFile(ref path) = input.kind {
Path::new(path).exists()
2020-03-30 22:18:41 +02:00
} else {
true
2020-03-30 22:18:41 +02:00
}
});
if !call_pager {
paging_mode = PagingMode::Never;
}
}
let wrapping_mode = self.config.wrapping_mode;
output_type = OutputType::from_mode(paging_mode, wrapping_mode, self.config.pager)?;
2020-03-30 22:18:41 +02:00
}
#[cfg(not(feature = "paging"))]
{
output_type = OutputType::stdout();
}
let attached_to_pager = output_type.is_pager();
let stdout_identifier = if cfg!(windows) || attached_to_pager {
None
} else {
clircle::Identifier::stdout()
};
2023-07-09 03:00:01 +02:00
let mut writer = match output_buffer {
Some(buf) => OutputHandle::FmtWrite(buf),
None => OutputHandle::IoWrite(output_type.handle()?),
};
2018-08-23 22:37:27 +02:00
let mut no_errors: bool = true;
let stderr = io::stderr();
2020-05-12 02:57:51 +02:00
for (index, input) in inputs.into_iter().enumerate() {
let identifier = stdout_identifier.as_ref();
let is_first = index == 0;
let result = if input.is_stdin() {
2023-07-09 02:20:58 +02:00
self.print_input(input, &mut writer, io::stdin().lock(), identifier, is_first)
} else {
// Use dummy stdin since stdin is actually not used (#1902)
2023-07-09 02:20:58 +02:00
self.print_input(input, &mut writer, io::empty(), identifier, is_first)
};
if let Err(error) = result {
match writer {
2023-07-09 02:33:48 +02:00
// It doesn't make much sense to send errors straight to stderr if the user
// provided their own buffer, so we just return it.
OutputHandle::FmtWrite(_) => return Err(error),
2023-07-09 02:20:58 +02:00
OutputHandle::IoWrite(ref mut writer) => {
if attached_to_pager {
handle_error(&error, writer);
} else {
handle_error(&error, &mut stderr.lock());
}
}
}
no_errors = false;
}
}
Ok(no_errors)
}
2021-10-12 09:09:05 +02:00
fn print_input<R: BufRead>(
&self,
input: Input,
2023-07-09 02:20:58 +02:00
writer: &mut OutputHandle,
stdin: R,
stdout_identifier: Option<&Identifier>,
is_first: bool,
) -> Result<()> {
let mut opened_input = {
#[cfg(feature = "lessopen")]
match self.preprocessor {
Some(ref preprocessor) if self.config.use_lessopen => {
preprocessor.open(input, stdin, stdout_identifier)?
}
_ => input.open(stdin, stdout_identifier)?,
}
#[cfg(not(feature = "lessopen"))]
input.open(stdin, stdout_identifier)?
};
#[cfg(feature = "git")]
let line_changes = if self.config.visible_lines.diff_mode()
|| (!self.config.loop_through && self.config.style_components.changes())
{
match opened_input.kind {
crate::input::OpenedInputKind::OrdinaryFile(ref path) => {
let diff = get_git_diff(path);
// Skip files without Git modifications
if self.config.visible_lines.diff_mode()
&& diff
.as_ref()
.map(|changes| changes.is_empty())
.unwrap_or(false)
{
return Ok(());
}
diff
}
_ if self.config.visible_lines.diff_mode() => {
// Skip non-file inputs in diff mode
return Ok(());
}
_ => None,
2018-08-23 22:37:27 +02:00
}
} else {
None
};
2018-08-23 22:37:27 +02:00
let mut printer: Box<dyn Printer> = if self.config.loop_through {
Box::new(SimplePrinter::new(self.config))
} else {
Box::new(InteractivePrinter::new(
self.config,
self.assets,
&mut opened_input,
#[cfg(feature = "git")]
&line_changes,
)?)
};
self.print_file(
&mut *printer,
writer,
&mut opened_input,
!is_first,
#[cfg(feature = "git")]
&line_changes,
)
2018-08-23 22:37:27 +02:00
}
2020-11-05 22:29:04 +01:00
fn print_file(
&self,
2020-04-22 16:27:34 +02:00
printer: &mut dyn Printer,
2023-07-09 02:20:58 +02:00
writer: &mut OutputHandle,
2020-04-22 16:27:34 +02:00
input: &mut OpenedInput,
2020-05-12 02:57:51 +02:00
add_header_padding: bool,
#[cfg(feature = "git")] line_changes: &Option<LineChanges>,
) -> Result<()> {
2020-04-22 16:27:34 +02:00
if !input.reader.first_line.is_empty() || self.config.style_components.header() {
2020-05-12 02:57:51 +02:00
printer.print_header(writer, input, add_header_padding)?;
2020-02-26 20:53:58 +01:00
}
2020-04-22 16:27:34 +02:00
if !input.reader.first_line.is_empty() {
let line_ranges = match self.config.visible_lines {
VisibleLines::Ranges(ref line_ranges) => line_ranges.clone(),
#[cfg(feature = "git")]
VisibleLines::DiffContext(context) => {
let mut line_ranges: Vec<LineRange> = vec![];
if let Some(line_changes) = line_changes {
2021-09-10 21:56:40 +02:00
for &line in line_changes.keys() {
let line = line as usize;
line_ranges
.push(LineRange::new(line.saturating_sub(context), line + context));
}
}
LineRanges::from(line_ranges)
}
};
self.print_file_ranges(printer, writer, &mut input.reader, &line_ranges)?;
}
2020-04-22 16:27:34 +02:00
printer.print_footer(writer, input)?;
2018-08-23 22:37:27 +02:00
Ok(())
}
2020-04-22 16:27:34 +02:00
fn print_file_ranges(
2018-08-23 22:37:27 +02:00
&self,
2020-04-22 16:27:34 +02:00
printer: &mut dyn Printer,
2023-07-09 02:20:58 +02:00
writer: &mut OutputHandle,
2020-04-22 16:27:34 +02:00
reader: &mut InputReader,
2018-10-20 00:10:10 +02:00
line_ranges: &LineRanges,
2018-08-23 22:37:27 +02:00
) -> Result<()> {
let mut line_buffer = Vec::new();
2018-08-23 22:37:27 +02:00
let mut line_number: usize = 1;
let mut first_range: bool = true;
let mut mid_range: bool = false;
2020-12-02 09:29:49 +01:00
let style_snip = self.config.style_components.snip();
while reader.read_line(&mut line_buffer)? {
2018-10-20 00:10:10 +02:00
match line_ranges.check(line_number) {
2020-03-21 16:51:38 +01:00
RangeCheckResult::BeforeOrBetweenRanges => {
2018-10-20 00:10:10 +02:00
// Call the printer in case we need to call the syntax highlighter
// for this line. However, set `out_of_range` to `true`.
printer.print_line(true, writer, line_number, &line_buffer)?;
mid_range = false;
2018-08-23 22:37:27 +02:00
}
2018-10-20 00:10:10 +02:00
RangeCheckResult::InRange => {
2020-12-02 09:29:49 +01:00
if style_snip {
if first_range {
first_range = false;
mid_range = true;
} else if !mid_range {
mid_range = true;
printer.print_snip(writer)?;
}
}
2018-10-07 10:09:10 +02:00
printer.print_line(false, writer, line_number, &line_buffer)?;
}
2018-10-20 00:10:10 +02:00
RangeCheckResult::AfterLastRange => {
break;
}
2018-08-23 22:37:27 +02:00
}
2018-10-07 10:09:10 +02:00
line_number += 1;
line_buffer.clear();
2018-08-23 22:37:27 +02:00
}
Ok(())
}
}