Completely refactor 'input' module

This commit is contained in:
sharkdp 2020-04-22 16:27:34 +02:00 committed by David Peter
parent b4d54106fe
commit 590960f7f5
9 changed files with 233 additions and 200 deletions

View File

@ -10,7 +10,7 @@ use syntect::parsing::{SyntaxReference, SyntaxSet, SyntaxSetBuilder};
use crate::assets_metadata::AssetsMetadata; use crate::assets_metadata::AssetsMetadata;
use crate::errors::*; use crate::errors::*;
use crate::input::{Input, InputReader}; use crate::input::{Input, InputKind, InputReader, OpenedInput, OpenedInputKind};
use crate::syntax_mapping::{MappingTarget, SyntaxMapping}; use crate::syntax_mapping::{MappingTarget, SyntaxMapping};
#[derive(Debug)] #[derive(Debug)]
@ -188,38 +188,46 @@ impl HighlightingAssets {
pub(crate) fn get_syntax( pub(crate) fn get_syntax(
&self, &self,
language: Option<&str>, language: Option<&str>,
input: &Input, input: &mut OpenedInput,
reader: &mut InputReader,
mapping: &SyntaxMapping, mapping: &SyntaxMapping,
) -> &SyntaxReference { ) -> &SyntaxReference {
let syntax = match (language, input) { let syntax = if let Some(language) = language {
(Some(language), _) => self.syntax_set.find_syntax_by_token(language), self.syntax_set.find_syntax_by_token(language)
(None, Input::Ordinary(ofile)) => { } else {
let path = Path::new(ofile.provided_path()); match input.kind {
let line_syntax = self.get_first_line_syntax(reader); OpenedInputKind::OrdinaryFile(ref actual_path) => {
let path_str = input
.metadata
.user_provided_name
.as_ref()
.unwrap_or(actual_path);
let path = Path::new(path_str);
let line_syntax = self.get_first_line_syntax(&mut input.reader);
let absolute_path = path.canonicalize().ok().unwrap_or(path.to_owned()); let absolute_path = path.canonicalize().ok().unwrap_or(path.to_owned());
match mapping.get_syntax_for(absolute_path) { match mapping.get_syntax_for(absolute_path) {
Some(MappingTarget::MapTo(syntax_name)) => { Some(MappingTarget::MapTo(syntax_name)) => {
// TODO: we should probably return an error here if this syntax can not be // TODO: we should probably return an error here if this syntax can not be
// found. Currently, we just fall back to 'plain'. // found. Currently, we just fall back to 'plain'.
self.syntax_set.find_syntax_by_name(syntax_name) self.syntax_set.find_syntax_by_name(syntax_name)
} }
Some(MappingTarget::MapToUnknown) => line_syntax, Some(MappingTarget::MapToUnknown) => line_syntax,
None => { None => {
let file_name = path.file_name().unwrap_or_default(); let file_name = path.file_name().unwrap_or_default();
self.get_extension_syntax(file_name).or(line_syntax) self.get_extension_syntax(file_name).or(line_syntax)
}
} }
} }
OpenedInputKind::StdIn | OpenedInputKind::CustomReader => {
if let Some(ref name) = input.metadata.user_provided_name {
self.get_extension_syntax(&name)
.or(self.get_first_line_syntax(&mut input.reader))
} else {
self.get_first_line_syntax(&mut input.reader)
}
}
OpenedInputKind::ThemePreviewFile => self.syntax_set.find_syntax_by_name("Rust"),
} }
(None, Input::StdIn(None)) => String::from_utf8(reader.first_line.clone())
.ok()
.and_then(|l| self.syntax_set.find_syntax_by_first_line(&l)),
(None, Input::StdIn(Some(file_name))) => self
.get_extension_syntax(&file_name)
.or(self.get_first_line_syntax(reader)),
(_, Input::ThemePreviewFile) => self.syntax_set.find_syntax_by_name("Rust"),
(None, Input::FromReader(_, _)) => unimplemented!(),
}; };
syntax.unwrap_or_else(|| self.syntax_set.find_syntax_plain_text()) syntax.unwrap_or_else(|| self.syntax_set.find_syntax_plain_text())
@ -249,8 +257,6 @@ impl HighlightingAssets {
mod tests { mod tests {
use super::*; use super::*;
use crate::input::OrdinaryFile;
use std::ffi::{OsStr, OsString}; use std::ffi::{OsStr, OsString};
use std::fs::File; use std::fs::File;
use std::io; use std::io;
@ -281,12 +287,12 @@ mod tests {
writeln!(temp_file, "{}", first_line).unwrap(); writeln!(temp_file, "{}", first_line).unwrap();
} }
let input = Input::Ordinary(OrdinaryFile::from_path(file_path.as_os_str())); let input: Input = Input::ordinary_file(file_path.as_os_str());
let stdin = io::stdin(); let dummy_stdin: &[u8] = &[];
let mut reader = input.get_reader(stdin.lock()).unwrap(); let mut opened_input = input.open(dummy_stdin).unwrap();
let syntax = self let syntax = self
.assets .assets
.get_syntax(None, &input, &mut reader, &self.syntax_mapping); .get_syntax(None, &mut opened_input, &self.syntax_mapping);
syntax.name.clone() syntax.name.clone()
} }
@ -304,13 +310,13 @@ mod tests {
} }
fn syntax_for_stdin_with_content(&self, file_name: &str, content: &[u8]) -> String { fn syntax_for_stdin_with_content(&self, file_name: &str, content: &[u8]) -> String {
let input = Input::StdIn(Some(OsString::from(file_name))); let mut input = Input::stdin();
let syntax = self.assets.get_syntax( input.set_provided_name(Some(OsStr::new(file_name)));
None, let mut opened_input = input.open(content).unwrap();
&input,
&mut input.get_reader(content).unwrap(), let syntax = self
&self.syntax_mapping, .assets
); .get_syntax(None, &mut opened_input, &self.syntax_mapping);
syntax.name.clone() syntax.name.clone()
} }
} }

View File

@ -15,10 +15,11 @@ use console::Term;
use bat::{ use bat::{
config::{ config::{
Config, HighlightedLineRanges, Input, LineRange, LineRanges, MappingTarget, OrdinaryFile, Config, HighlightedLineRanges, LineRange, LineRanges, MappingTarget, PagingMode,
PagingMode, StyleComponent, StyleComponents, SyntaxMapping, WrappingMode, StyleComponent, StyleComponents, SyntaxMapping, WrappingMode,
}, },
errors::*, errors::*,
input::Input,
HighlightingAssets, HighlightingAssets,
}; };
@ -83,13 +84,7 @@ impl App {
if self.matches.occurrences_of("plain") > 1 { if self.matches.occurrences_of("plain") > 1 {
// If we have -pp as an option when in auto mode, the pager should be disabled. // If we have -pp as an option when in auto mode, the pager should be disabled.
PagingMode::Never PagingMode::Never
} else if inputs.iter().any(|f| { } else if inputs.iter().any(Input::is_stdin) {
if let Input::StdIn(None) = f {
true
} else {
false
}
}) {
// If we are reading from stdin, only enable paging if we write to an // If we are reading from stdin, only enable paging if we write to an
// interactive terminal and if we do not *read* from an interactive // interactive terminal and if we do not *read* from an interactive
// terminal. // terminal.
@ -251,9 +246,9 @@ impl App {
let files: Option<Vec<&OsStr>> = self.matches.values_of_os("FILE").map(|vs| vs.collect()); let files: Option<Vec<&OsStr>> = self.matches.values_of_os("FILE").map(|vs| vs.collect());
if files.is_none() { if files.is_none() {
return Ok(vec![Input::StdIn( let mut input = Input::stdin();
filenames_or_none.nth(0).unwrap().map(|f| f.to_owned()), input.set_provided_name(filenames_or_none.nth(0).unwrap_or(None));
)]); return Ok(vec![input]);
} }
let files_or_none: Box<dyn Iterator<Item = _>> = match files { let files_or_none: Box<dyn Iterator<Item = _>> = match files {
Some(ref files) => Box::new(files.into_iter().map(|name| Some(*name))), Some(ref files) => Box::new(files.into_iter().map(|name| Some(*name))),
@ -261,16 +256,16 @@ impl App {
}; };
let mut file_input = Vec::new(); let mut file_input = Vec::new();
for (input, name) in files_or_none.zip(filenames_or_none) { for (filepath, provided_name) in files_or_none.zip(filenames_or_none) {
if let Some(input) = input { if let Some(filepath) = filepath {
if input.to_str().unwrap_or_default() == "-" { if filepath.to_str().unwrap_or_default() == "-" {
file_input.push(Input::StdIn(name.map(|n| n.to_owned()))); let mut input = Input::stdin();
input.set_provided_name(provided_name);
file_input.push(input);
} else { } else {
let mut ofile = OrdinaryFile::from_path(input); let mut input = Input::ordinary_file(filepath);
if let Some(path) = name { input.set_provided_name(provided_name);
ofile.set_provided_path(path); file_input.push(input);
}
file_input.push(Input::Ordinary(ofile))
} }
} }
} }

View File

@ -26,8 +26,9 @@ use clap::crate_version;
use directories::PROJECT_DIRS; use directories::PROJECT_DIRS;
use bat::{ use bat::{
config::{Config, Input, OrdinaryFile, StyleComponent, StyleComponents}, config::{Config, StyleComponent, StyleComponents},
errors::*, errors::*,
input::Input,
Controller, HighlightingAssets, Controller, HighlightingAssets,
}; };
@ -134,7 +135,7 @@ pub fn list_themes(cfg: &Config) -> Result<()> {
)?; )?;
config.theme = theme.to_string(); config.theme = theme.to_string();
Controller::new(&config, &assets) Controller::new(&config, &assets)
.run(vec![Input::ThemePreviewFile]) .run(vec![Input::theme_preview_file()])
.ok(); .ok();
writeln!(stdout)?; writeln!(stdout)?;
} }
@ -167,9 +168,7 @@ fn run() -> Result<bool> {
run_cache_subcommand(cache_matches)?; run_cache_subcommand(cache_matches)?;
Ok(true) Ok(true)
} else { } else {
let inputs = vec![Input::Ordinary(OrdinaryFile::from_path(OsStr::new( let inputs = vec![Input::ordinary_file(OsStr::new("cache"))];
"cache",
)))];
let config = app.config(&inputs)?; let config = app.config(&inputs)?;
run_controller(inputs, &config) run_controller(inputs, &config)

View File

@ -1,5 +1,3 @@
pub use crate::input::Input;
pub use crate::input::OrdinaryFile;
pub use crate::line_range::{HighlightedLineRanges, LineRange, LineRanges}; pub use crate::line_range::{HighlightedLineRanges, LineRange, LineRanges};
pub use crate::style::{StyleComponent, StyleComponents}; pub use crate::style::{StyleComponent, StyleComponents};
pub use crate::syntax_mapping::{MappingTarget, SyntaxMapping}; pub use crate::syntax_mapping::{MappingTarget, SyntaxMapping};

View File

@ -5,7 +5,7 @@ use crate::config::Config;
#[cfg(feature = "paging")] #[cfg(feature = "paging")]
use crate::config::PagingMode; use crate::config::PagingMode;
use crate::errors::*; use crate::errors::*;
use crate::input::{Input, InputDescription, InputReader}; use crate::input::{Input, InputDescription, InputKind, InputReader, OpenedInput};
use crate::line_range::{LineRanges, RangeCheckResult}; use crate::line_range::{LineRanges, RangeCheckResult};
use crate::output::OutputType; use crate::output::OutputType;
use crate::printer::{InteractivePrinter, Printer, SimplePrinter}; use crate::printer::{InteractivePrinter, Printer, SimplePrinter};
@ -38,9 +38,9 @@ impl<'b> Controller<'b> {
// Do not launch the pager if NONE of the input files exist // Do not launch the pager if NONE of the input files exist
let mut paging_mode = self.config.paging_mode; let mut paging_mode = self.config.paging_mode;
if self.config.paging_mode != PagingMode::Never { if self.config.paging_mode != PagingMode::Never {
let call_pager = inputs.iter().any(|file| { let call_pager = inputs.iter().any(|ref input| {
if let Input::Ordinary(ofile) = file { if let InputKind::OrdinaryFile(ref path) = input.kind {
return Path::new(ofile.provided_path()).exists(); return Path::new(path).exists();
} else { } else {
return true; return true;
} }
@ -61,27 +61,24 @@ impl<'b> Controller<'b> {
let mut no_errors: bool = true; let mut no_errors: bool = true;
for input in inputs.into_iter() { for input in inputs.into_iter() {
let description = input.description(); match input.open(io::stdin().lock()) {
match input.get_reader(io::stdin().lock()) {
Err(error) => { Err(error) => {
handle_error(&error); handle_error(&error);
no_errors = false; no_errors = false;
} }
Ok(mut reader) => { Ok(mut opened_input) => {
let result = if self.config.loop_through { let mut printer: Box<dyn Printer> = if self.config.loop_through {
let mut printer = SimplePrinter::new(); Box::new(SimplePrinter::new())
self.print_file(reader, &mut printer, writer, &description)
} else { } else {
let mut printer = InteractivePrinter::new( Box::new(InteractivePrinter::new(
&self.config, &self.config,
&self.assets, &self.assets,
&input, &mut opened_input,
&mut reader, ))
);
self.print_file(reader, &mut printer, writer, &description)
}; };
let result = self.print_file(&mut *printer, writer, &mut opened_input);
if let Err(error) = result { if let Err(error) = result {
handle_error(&error); handle_error(&error);
no_errors = false; no_errors = false;
@ -93,30 +90,29 @@ impl<'b> Controller<'b> {
Ok(no_errors) Ok(no_errors)
} }
fn print_file<'a, P: Printer>( fn print_file<'a>(
&self, &self,
reader: InputReader, printer: &mut dyn Printer,
printer: &mut P,
writer: &mut dyn Write, writer: &mut dyn Write,
input_description: &InputDescription, input: &mut OpenedInput,
) -> Result<()> { ) -> Result<()> {
if !reader.first_line.is_empty() || self.config.style_components.header() { if !input.reader.first_line.is_empty() || self.config.style_components.header() {
printer.print_header(writer, input_description)?; printer.print_header(writer, input)?;
} }
if !reader.first_line.is_empty() { if !input.reader.first_line.is_empty() {
self.print_file_ranges(printer, writer, reader, &self.config.line_ranges)?; self.print_file_ranges(printer, writer, &mut input.reader, &self.config.line_ranges)?;
} }
printer.print_footer(writer)?; printer.print_footer(writer, input)?;
Ok(()) Ok(())
} }
fn print_file_ranges<P: Printer>( fn print_file_ranges(
&self, &self,
printer: &mut P, printer: &mut dyn Printer,
writer: &mut dyn Write, writer: &mut dyn Write,
mut reader: InputReader, reader: &mut InputReader,
line_ranges: &LineRanges, line_ranges: &LineRanges,
) -> Result<()> { ) -> Result<()> {
let mut line_buffer = Vec::new(); let mut line_buffer = Vec::new();

View File

@ -7,30 +7,6 @@ use content_inspector::{self, ContentType};
use crate::errors::*; use crate::errors::*;
const THEME_PREVIEW_FILE: &[u8] = include_bytes!("../assets/theme_preview.rs"); const THEME_PREVIEW_FILE: &[u8] = include_bytes!("../assets/theme_preview.rs");
#[derive(Debug, Clone, PartialEq)]
pub struct OrdinaryFile {
path: OsString,
user_provided_path: Option<OsString>,
}
impl OrdinaryFile {
pub fn from_path(path: &OsStr) -> OrdinaryFile {
OrdinaryFile {
path: path.to_os_string(),
user_provided_path: None,
}
}
pub fn set_provided_path(&mut self, user_provided_path: &OsStr) {
self.user_provided_path = Some(user_provided_path.to_os_string());
}
pub(crate) fn provided_path<'a>(&'a self) -> &'a OsStr {
self.user_provided_path
.as_ref()
.unwrap_or_else(|| &self.path)
}
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct InputDescription { pub struct InputDescription {
@ -39,69 +15,134 @@ pub struct InputDescription {
pub name: String, pub name: String,
} }
pub enum Input { pub enum InputKind {
StdIn(Option<OsString>), OrdinaryFile(OsString),
Ordinary(OrdinaryFile), StdIn,
FromReader(Box<dyn Read>, Option<OsString>),
ThemePreviewFile, ThemePreviewFile,
CustomReader(Box<dyn BufRead>),
}
#[derive(Clone, Default)]
pub struct InputMetadata {
pub user_provided_name: Option<OsString>,
}
pub struct Input {
pub kind: InputKind,
pub metadata: InputMetadata,
}
pub enum OpenedInputKind {
OrdinaryFile(OsString),
StdIn,
ThemePreviewFile,
CustomReader,
}
pub struct OpenedInput<'a> {
pub kind: OpenedInputKind,
pub metadata: InputMetadata,
pub reader: InputReader<'a>,
} }
impl Input { impl Input {
pub(crate) fn get_reader<'a, R: BufRead + 'a>(&self, stdin: R) -> Result<InputReader<'a>> { pub fn ordinary_file(path: &OsStr) -> Self {
match self { Input {
Input::StdIn(_) => Ok(InputReader::new(stdin)), kind: InputKind::OrdinaryFile(path.to_os_string()),
Input::Ordinary(ofile) => { metadata: InputMetadata::default(),
let file = File::open(&ofile.path)
.map_err(|e| format!("'{}': {}", ofile.path.to_string_lossy(), e))?;
if file.metadata()?.is_dir() {
return Err(
format!("'{}' is a directory.", ofile.path.to_string_lossy()).into(),
);
}
Ok(InputReader::new(BufReader::new(file)))
}
Input::ThemePreviewFile => Ok(InputReader::new(THEME_PREVIEW_FILE)),
Input::FromReader(_, _) => unimplemented!(), //Ok(InputReader::new(BufReader::new(reader))),
} }
} }
pub(crate) fn description(&self) -> InputDescription { pub fn stdin() -> Self {
match self { Input {
Input::Ordinary(ofile) => InputDescription { kind: InputKind::StdIn,
full: format!("file '{}'", &ofile.provided_path().to_string_lossy()), metadata: InputMetadata::default(),
prefix: "File: ".to_owned(), }
name: ofile.provided_path().to_string_lossy().into_owned(), }
},
Input::StdIn(Some(name)) => InputDescription { pub fn theme_preview_file() -> Self {
full: format!( Input {
"STDIN (with name '{}')", kind: InputKind::ThemePreviewFile,
name.to_string_lossy().into_owned() metadata: InputMetadata::default(),
), }
prefix: "File: ".to_owned(), }
name: name.to_string_lossy().into_owned(),
}, pub fn is_stdin(&self) -> bool {
Input::StdIn(None) => InputDescription { if let InputKind::StdIn = self.kind {
full: "STDIN".to_owned(), true
prefix: "".to_owned(), } else {
name: "STDIN".to_owned(), false
}, }
Input::ThemePreviewFile => InputDescription { }
full: "".to_owned(),
prefix: "".to_owned(), pub fn set_provided_name(&mut self, provided_name: Option<&OsStr>) {
name: "".to_owned(), self.metadata.user_provided_name = provided_name.map(|n| n.to_owned());
}, }
Input::FromReader(_, Some(name)) => InputDescription {
pub fn open<'a, R: BufRead + 'a>(self, stdin: R) -> Result<OpenedInput<'a>> {
match self.kind {
InputKind::StdIn => Ok(OpenedInput {
kind: OpenedInputKind::StdIn,
metadata: self.metadata,
reader: InputReader::new(stdin),
}),
InputKind::OrdinaryFile(path) => Ok(OpenedInput {
kind: OpenedInputKind::OrdinaryFile(path.clone()),
metadata: self.metadata,
reader: {
let file = File::open(&path)
.map_err(|e| format!("'{}': {}", path.to_string_lossy(), e))?;
if file.metadata()?.is_dir() {
return Err(format!("'{}' is a directory.", path.to_string_lossy()).into());
}
InputReader::new(BufReader::new(file))
},
}),
InputKind::ThemePreviewFile => Ok(OpenedInput {
kind: OpenedInputKind::ThemePreviewFile,
metadata: self.metadata,
reader: InputReader::new(THEME_PREVIEW_FILE),
}),
InputKind::CustomReader(reader) => Ok(OpenedInput {
kind: OpenedInputKind::CustomReader,
metadata: self.metadata,
reader: InputReader::new(BufReader::new(reader)),
}),
}
}
}
impl<'a> OpenedInput<'a> {
pub fn description(&self) -> InputDescription {
if let Some(ref name) = self.metadata.user_provided_name {
InputDescription {
full: format!("file '{}'", name.to_string_lossy()), full: format!("file '{}'", name.to_string_lossy()),
prefix: "File: ".to_owned(), prefix: "File: ".to_owned(),
name: name.to_string_lossy().into_owned(), name: name.to_string_lossy().into_owned(),
}, }
Input::FromReader(_, None) => InputDescription { } else {
full: "reader".to_owned(), match self.kind {
prefix: "".to_owned(), OpenedInputKind::OrdinaryFile(ref path) => InputDescription {
name: "READER".into(), full: format!("file '{}'", path.to_string_lossy()),
}, prefix: "File: ".to_owned(),
name: path.to_string_lossy().into_owned(),
},
OpenedInputKind::StdIn => InputDescription {
full: "STDIN".to_owned(),
prefix: "".to_owned(),
name: "STDIN".to_owned(),
},
OpenedInputKind::ThemePreviewFile => InputDescription {
full: "".to_owned(),
prefix: "".to_owned(),
name: "".to_owned(),
},
OpenedInputKind::CustomReader => InputDescription {
full: "reader".to_owned(),
prefix: "".to_owned(),
name: "READER".into(),
},
}
} }
} }
} }

View File

@ -8,7 +8,7 @@ pub(crate) mod controller;
mod decorations; mod decorations;
mod diff; mod diff;
pub mod errors; pub mod errors;
pub(crate) mod input; pub mod input;
mod less; mod less;
pub(crate) mod line_range; pub(crate) mod line_range;
mod output; mod output;

View File

@ -3,10 +3,10 @@ use std::io::Read;
use crate::{ use crate::{
config::{ config::{
Config, HighlightedLineRanges, Input, LineRanges, OrdinaryFile, StyleComponents, Config, HighlightedLineRanges, LineRanges, StyleComponents, SyntaxMapping, WrappingMode,
SyntaxMapping, WrappingMode,
}, },
errors::Result, errors::Result,
input::{Input, InputKind, OpenedInput},
Controller, HighlightingAssets, Controller, HighlightingAssets,
}; };
@ -35,8 +35,8 @@ impl<'a> PrettyPrinter<'a> {
/// Add a file which should be pretty-printed /// Add a file which should be pretty-printed
pub fn input_file(&mut self, path: &OsStr) -> &mut Self { pub fn input_file(&mut self, path: &OsStr) -> &mut Self {
self.inputs // self.inputs
.push(Input::Ordinary(OrdinaryFile::from_path(path))); // .push(Input::Ordinary(OrdinaryFile::from_path(path)));
self self
} }
@ -47,15 +47,15 @@ impl<'a> PrettyPrinter<'a> {
P: AsRef<OsStr>, P: AsRef<OsStr>,
{ {
for path in paths { for path in paths {
self.inputs // self.inputs
.push(Input::Ordinary(OrdinaryFile::from_path(path.as_ref()))); // .push(Input::Ordinary(OrdinaryFile::from_path(path.as_ref())));
} }
self self
} }
/// Add STDIN as an input /// Add STDIN as an input
pub fn input_stdin(&mut self) -> &mut Self { pub fn input_stdin(&mut self) -> &mut Self {
self.inputs.push(Input::StdIn(None)); // self.inputs.push(Input::StdIn(None));
self self
} }

View File

@ -27,15 +27,15 @@ use crate::decorations::{Decoration, GridBorderDecoration, LineNumberDecoration}
#[cfg(feature = "git")] #[cfg(feature = "git")]
use crate::diff::{get_git_diff, LineChanges}; use crate::diff::{get_git_diff, LineChanges};
use crate::errors::*; use crate::errors::*;
use crate::input::{Input, InputDescription, InputReader}; use crate::input::{Input, InputDescription, InputKind, InputReader, OpenedInput, OpenedInputKind};
use crate::line_range::RangeCheckResult; use crate::line_range::RangeCheckResult;
use crate::preprocessor::{expand_tabs, replace_nonprintable}; use crate::preprocessor::{expand_tabs, replace_nonprintable};
use crate::terminal::{as_terminal_escaped, to_ansi_color}; use crate::terminal::{as_terminal_escaped, to_ansi_color};
use crate::wrap::WrappingMode; use crate::wrap::WrappingMode;
pub trait Printer { pub trait Printer {
fn print_header(&mut self, handle: &mut dyn Write, input: &InputDescription) -> Result<()>; fn print_header(&mut self, handle: &mut dyn Write, input: &OpenedInput) -> Result<()>;
fn print_footer(&mut self, handle: &mut dyn Write) -> Result<()>; fn print_footer(&mut self, handle: &mut dyn Write, input: &OpenedInput) -> Result<()>;
fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()>; fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()>;
@ -57,11 +57,11 @@ impl SimplePrinter {
} }
impl Printer for SimplePrinter { impl Printer for SimplePrinter {
fn print_header(&mut self, _handle: &mut dyn Write, input: &InputDescription) -> Result<()> { fn print_header(&mut self, _handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
Ok(()) Ok(())
} }
fn print_footer(&mut self, _handle: &mut dyn Write) -> Result<()> { fn print_footer(&mut self, _handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
Ok(()) Ok(())
} }
@ -101,8 +101,7 @@ impl<'a> InteractivePrinter<'a> {
pub fn new( pub fn new(
config: &'a Config, config: &'a Config,
assets: &'a HighlightingAssets, assets: &'a HighlightingAssets,
input: &Input, input: &mut OpenedInput,
reader: &mut InputReader,
) -> Self { ) -> Self {
let theme = assets.get_theme(&config.theme); let theme = assets.get_theme(&config.theme);
@ -150,7 +149,8 @@ impl<'a> InteractivePrinter<'a> {
#[cfg(feature = "git")] #[cfg(feature = "git")]
let mut line_changes = None; let mut line_changes = None;
let highlighter = if reader let highlighter = if input
.reader
.content_type .content_type
.map_or(false, |c| c.is_binary() && !config.show_nonprintable) .map_or(false, |c| c.is_binary() && !config.show_nonprintable)
{ {
@ -160,14 +160,14 @@ impl<'a> InteractivePrinter<'a> {
#[cfg(feature = "git")] #[cfg(feature = "git")]
{ {
if config.style_components.changes() { if config.style_components.changes() {
if let Input::Ordinary(ofile) = input { if let OpenedInputKind::OrdinaryFile(ref path) = input.kind {
line_changes = get_git_diff(ofile.provided_path()); line_changes = get_git_diff(path);
} }
} }
} }
// Determine the type of syntax for highlighting // Determine the type of syntax for highlighting
let syntax = assets.get_syntax(config.language, input, reader, &config.syntax_mapping); let syntax = assets.get_syntax(config.language, input, &config.syntax_mapping);
Some(HighlightLines::new(syntax, theme)) Some(HighlightLines::new(syntax, theme))
}; };
@ -176,7 +176,7 @@ impl<'a> InteractivePrinter<'a> {
colors, colors,
config, config,
decorations, decorations,
content_type: reader.content_type, content_type: input.reader.content_type,
ansi_prefix_sgr: String::new(), ansi_prefix_sgr: String::new(),
#[cfg(feature = "git")] #[cfg(feature = "git")]
line_changes, line_changes,
@ -230,11 +230,7 @@ impl<'a> InteractivePrinter<'a> {
} }
impl<'a> Printer for InteractivePrinter<'a> { impl<'a> Printer for InteractivePrinter<'a> {
fn print_header( fn print_header(&mut self, handle: &mut dyn Write, input: &OpenedInput) -> Result<()> {
&mut self,
handle: &mut dyn Write,
description: &InputDescription,
) -> Result<()> {
if !self.config.style_components.header() { if !self.config.style_components.header() {
if Some(ContentType::BINARY) == self.content_type && !self.config.show_nonprintable { if Some(ContentType::BINARY) == self.content_type && !self.config.show_nonprintable {
writeln!( writeln!(
@ -243,7 +239,7 @@ impl<'a> Printer for InteractivePrinter<'a> {
(but will be present if the output of 'bat' is piped). You can use 'bat -A' \ (but will be present if the output of 'bat' is piped). You can use 'bat -A' \
to show the binary file contents.", to show the binary file contents.",
Yellow.paint("[bat warning]"), Yellow.paint("[bat warning]"),
description.full, input.description().full,
)?; )?;
} else { } else {
if self.config.style_components.grid() { if self.config.style_components.grid() {
@ -276,6 +272,8 @@ impl<'a> Printer for InteractivePrinter<'a> {
_ => "", _ => "",
}; };
let description = input.description();
writeln!( writeln!(
handle, handle,
"{}{}{}", "{}{}{}",
@ -295,7 +293,7 @@ impl<'a> Printer for InteractivePrinter<'a> {
Ok(()) Ok(())
} }
fn print_footer(&mut self, handle: &mut dyn Write) -> Result<()> { fn print_footer(&mut self, handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
if self.config.style_components.grid() if self.config.style_components.grid()
&& (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable) && (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable)
{ {