1
0
mirror of https://github.com/sharkdp/bat.git synced 2025-01-18 20:11:03 +00:00

Rename output component to 'style compinent', move wrap to separate module

This commit is contained in:
sharkdp 2020-03-21 20:54:16 +01:00 committed by David Peter
parent a8851e1307
commit 84ba323b1c
9 changed files with 88 additions and 86 deletions

View File

@ -3,7 +3,7 @@ use bat::{
config::Config, config::Config,
controller::Controller, controller::Controller,
inputfile::InputFile, inputfile::InputFile,
style::{OutputComponent, OutputComponents}, style::{StyleComponent, StyleComponents},
}; };
use console::Term; use console::Term;
use std::process; use std::process;
@ -20,10 +20,10 @@ fn main() {
term_width: Term::stdout().size().1 as usize, term_width: Term::stdout().size().1 as usize,
colored_output: true, colored_output: true,
true_color: true, true_color: true,
output_components: OutputComponents::new(&[ style_components: StyleComponents::new(&[
OutputComponent::Header, StyleComponent::Header,
OutputComponent::Grid, StyleComponent::Grid,
OutputComponent::Numbers, StyleComponent::Numbers,
]), ]),
files: files.iter().map(|file| InputFile::Ordinary(file)).collect(), files: files.iter().map(|file| InputFile::Ordinary(file)).collect(),
theme: "1337".into(), theme: "1337".into(),

View File

@ -22,8 +22,9 @@ use bat::{
errors::*, errors::*,
inputfile::InputFile, inputfile::InputFile,
line_range::{HighlightedLineRanges, LineRange, LineRanges}, line_range::{HighlightedLineRanges, LineRange, LineRanges},
style::{OutputComponent, OutputComponents, OutputWrap}, style::{StyleComponent, StyleComponents},
syntax_mapping::SyntaxMapping, syntax_mapping::SyntaxMapping,
wrap::OutputWrap,
}; };
fn is_truecolor_terminal() -> bool { fn is_truecolor_terminal() -> bool {
@ -79,7 +80,7 @@ impl App {
pub fn config(&self) -> Result<Config> { pub fn config(&self) -> Result<Config> {
let files = self.files(); let files = self.files();
let output_components = self.output_components()?; let style_components = self.style_components()?;
let paging_mode = match self.matches.value_of("paging") { let paging_mode = match self.matches.value_of("paging") {
Some("always") => PagingMode::Always, Some("always") => PagingMode::Always,
@ -152,7 +153,7 @@ impl App {
Some("character") => OutputWrap::Character, Some("character") => OutputWrap::Character,
Some("never") => OutputWrap::None, Some("never") => OutputWrap::None,
Some("auto") | _ => { Some("auto") | _ => {
if output_components.plain() { if style_components.plain() {
OutputWrap::None OutputWrap::None
} else { } else {
OutputWrap::Character OutputWrap::Character
@ -182,7 +183,7 @@ impl App {
.or_else(|| env::var("BAT_TABS").ok()) .or_else(|| env::var("BAT_TABS").ok())
.and_then(|t| t.parse().ok()) .and_then(|t| t.parse().ok())
.unwrap_or( .unwrap_or(
if output_components.plain() && paging_mode == PagingMode::Never { if style_components.plain() && paging_mode == PagingMode::Never {
0 0
} else { } else {
4 4
@ -208,7 +209,7 @@ impl App {
.transpose()? .transpose()?
.map(LineRanges::from) .map(LineRanges::from)
.unwrap_or_default(), .unwrap_or_default(),
output_components, style_components,
syntax_mapping, syntax_mapping,
pager: self.matches.value_of("pager"), pager: self.matches.value_of("pager"),
use_italic_text: match self.matches.value_of("italic-text") { use_italic_text: match self.matches.value_of("italic-text") {
@ -243,23 +244,23 @@ impl App {
.unwrap_or_else(|| vec![InputFile::StdIn]) .unwrap_or_else(|| vec![InputFile::StdIn])
} }
fn output_components(&self) -> Result<OutputComponents> { fn style_components(&self) -> Result<StyleComponents> {
let matches = &self.matches; let matches = &self.matches;
Ok(OutputComponents( Ok(StyleComponents(
if matches.value_of("decorations") == Some("never") { if matches.value_of("decorations") == Some("never") {
HashSet::new() HashSet::new()
} else if matches.is_present("number") { } else if matches.is_present("number") {
[OutputComponent::Numbers].iter().cloned().collect() [StyleComponent::Numbers].iter().cloned().collect()
} else if matches.is_present("plain") { } else if matches.is_present("plain") {
[OutputComponent::Plain].iter().cloned().collect() [StyleComponent::Plain].iter().cloned().collect()
} else { } else {
let env_style_components: Option<Vec<OutputComponent>> = env::var("BAT_STYLE") let env_style_components: Option<Vec<StyleComponent>> = env::var("BAT_STYLE")
.ok() .ok()
.map(|style_str| { .map(|style_str| {
style_str style_str
.split(',') .split(',')
.map(|x| OutputComponent::from_str(&x)) .map(|x| StyleComponent::from_str(&x))
.collect::<Result<Vec<OutputComponent>>>() .collect::<Result<Vec<StyleComponent>>>()
}) })
.transpose()?; .transpose()?;
@ -268,12 +269,12 @@ impl App {
.map(|styles| { .map(|styles| {
styles styles
.split(',') .split(',')
.map(|style| style.parse::<OutputComponent>()) .map(|style| style.parse::<StyleComponent>())
.filter_map(|style| style.ok()) .filter_map(|style| style.ok())
.collect::<Vec<_>>() .collect::<Vec<_>>()
}) })
.or(env_style_components) .or(env_style_components)
.unwrap_or_else(|| vec![OutputComponent::Full]) .unwrap_or_else(|| vec![StyleComponent::Full])
.into_iter() .into_iter()
.map(|style| style.components(self.interactive_output)) .map(|style| style.components(self.interactive_output))
.fold(HashSet::new(), |mut acc, components| { .fold(HashSet::new(), |mut acc, components| {

View File

@ -32,7 +32,7 @@ use bat::{
config::Config, config::Config,
errors::*, errors::*,
inputfile::InputFile, inputfile::InputFile,
style::{OutputComponent, OutputComponents}, style::{StyleComponent, StyleComponents},
}; };
fn run_cache_subcommand(matches: &clap::ArgMatches) -> Result<()> { fn run_cache_subcommand(matches: &clap::ArgMatches) -> Result<()> {
@ -123,9 +123,9 @@ pub fn list_themes(cfg: &Config) -> Result<()> {
let assets = assets_from_cache_or_binary(); let assets = assets_from_cache_or_binary();
let mut config = cfg.clone(); let mut config = cfg.clone();
let mut style = HashSet::new(); let mut style = HashSet::new();
style.insert(OutputComponent::Plain); style.insert(StyleComponent::Plain);
config.files = vec![InputFile::ThemePreviewFile]; config.files = vec![InputFile::ThemePreviewFile];
config.output_components = OutputComponents(style); config.style_components = StyleComponents(style);
let stdout = io::stdout(); let stdout = io::stdout();
let mut stdout = stdout.lock(); let mut stdout = stdout.lock();

View File

@ -1,7 +1,8 @@
use crate::inputfile::InputFile; use crate::inputfile::InputFile;
use crate::line_range::{HighlightedLineRanges, LineRanges}; use crate::line_range::{HighlightedLineRanges, LineRanges};
use crate::style::{OutputComponents, OutputWrap}; use crate::style::StyleComponents;
use crate::syntax_mapping::SyntaxMapping; use crate::syntax_mapping::SyntaxMapping;
use crate::wrap::OutputWrap;
#[derive(Debug, Clone, Copy, PartialEq)] #[derive(Debug, Clone, Copy, PartialEq)]
pub enum PagingMode { pub enum PagingMode {
@ -44,7 +45,7 @@ pub struct Config<'a> {
pub true_color: bool, pub true_color: bool,
/// Style elements (grid, line numbers, ...) /// Style elements (grid, line numbers, ...)
pub output_components: OutputComponents, pub style_components: StyleComponents,
/// Text wrapping mode /// Text wrapping mode
pub output_wrap: OutputWrap, pub output_wrap: OutputWrap,

View File

@ -83,7 +83,7 @@ impl<'b> Controller<'b> {
writer: &mut dyn Write, writer: &mut dyn Write,
input_file: InputFile<'a>, input_file: InputFile<'a>,
) -> Result<()> { ) -> Result<()> {
if !reader.first_line.is_empty() || self.config.output_components.header() { if !reader.first_line.is_empty() || self.config.style_components.header() {
printer.print_header(writer, input_file)?; printer.print_header(writer, input_file)?;
} }
@ -118,7 +118,7 @@ impl<'b> Controller<'b> {
} }
RangeCheckResult::InRange => { RangeCheckResult::InRange => {
if self.config.output_components.snip() { if self.config.style_components.snip() {
if first_range { if first_range {
first_range = false; first_range = false;
mid_range = true; mid_range = true;

View File

@ -27,3 +27,4 @@ mod printer;
pub mod style; pub mod style;
pub mod syntax_mapping; pub mod syntax_mapping;
mod terminal; mod terminal;
pub mod wrap;

View File

@ -30,8 +30,8 @@ use crate::errors::*;
use crate::inputfile::{InputFile, InputFileReader}; use crate::inputfile::{InputFile, InputFileReader};
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::style::OutputWrap;
use crate::terminal::{as_terminal_escaped, to_ansi_color}; use crate::terminal::{as_terminal_escaped, to_ansi_color};
use crate::wrap::OutputWrap;
pub trait Printer { pub trait Printer {
fn print_header(&mut self, handle: &mut dyn Write, file: InputFile) -> Result<()>; fn print_header(&mut self, handle: &mut dyn Write, file: InputFile) -> Result<()>;
@ -116,11 +116,11 @@ impl<'a> InteractivePrinter<'a> {
// Create decorations. // Create decorations.
let mut decorations: Vec<Box<dyn Decoration>> = Vec::new(); let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
if config.output_components.numbers() { if config.style_components.numbers() {
decorations.push(Box::new(LineNumberDecoration::new(&colors))); decorations.push(Box::new(LineNumberDecoration::new(&colors)));
} }
if config.output_components.changes() { if config.style_components.changes() {
decorations.push(Box::new(LineChangesDecoration::new(&colors))); decorations.push(Box::new(LineChangesDecoration::new(&colors)));
} }
@ -130,7 +130,7 @@ impl<'a> InteractivePrinter<'a> {
// The grid border decoration isn't added until after the panel_width calculation, since the // The grid border decoration isn't added until after the panel_width calculation, since the
// print_horizontal_line, print_header, and print_footer functions all assume the panel // print_horizontal_line, print_header, and print_footer functions all assume the panel
// width is without the grid border. // width is without the grid border.
if config.output_components.grid() && !decorations.is_empty() { if config.style_components.grid() && !decorations.is_empty() {
decorations.push(Box::new(GridBorderDecoration::new(&colors))); decorations.push(Box::new(GridBorderDecoration::new(&colors)));
} }
@ -152,7 +152,7 @@ impl<'a> InteractivePrinter<'a> {
None None
} else { } else {
// Get the Git modifications // Get the Git modifications
line_changes = if config.output_components.changes() { line_changes = if config.style_components.changes() {
match file { match file {
InputFile::Ordinary(filename) => get_git_diff(filename), InputFile::Ordinary(filename) => get_git_diff(filename),
_ => None, _ => None,
@ -206,7 +206,7 @@ impl<'a> InteractivePrinter<'a> {
text_truncated, text_truncated,
" ".repeat(self.panel_width - 1 - text_truncated.len()) " ".repeat(self.panel_width - 1 - text_truncated.len())
); );
if self.config.output_components.grid() { if self.config.style_components.grid() {
format!("{}", text_filled) format!("{}", text_filled)
} else { } else {
format!("{}", text_filled) format!("{}", text_filled)
@ -225,7 +225,7 @@ impl<'a> InteractivePrinter<'a> {
impl<'a> Printer for InteractivePrinter<'a> { impl<'a> Printer for InteractivePrinter<'a> {
fn print_header(&mut self, handle: &mut dyn Write, file: InputFile) -> Result<()> { fn print_header(&mut self, handle: &mut dyn Write, file: InputFile) -> Result<()> {
if !self.config.output_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 {
let input = match file { let input = match file {
InputFile::Ordinary(filename) => { InputFile::Ordinary(filename) => {
@ -243,14 +243,14 @@ impl<'a> Printer for InteractivePrinter<'a> {
input input
)?; )?;
} else { } else {
if self.config.output_components.grid() { if self.config.style_components.grid() {
self.print_horizontal_line(handle, '┬')?; self.print_horizontal_line(handle, '┬')?;
} }
} }
return Ok(()); return Ok(());
} }
if self.config.output_components.grid() { if self.config.style_components.grid() {
self.print_horizontal_line(handle, '┬')?; self.print_horizontal_line(handle, '┬')?;
write!( write!(
@ -286,7 +286,7 @@ impl<'a> Printer for InteractivePrinter<'a> {
mode mode
)?; )?;
if self.config.output_components.grid() { if self.config.style_components.grid() {
if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable { if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable {
self.print_horizontal_line(handle, '┼')?; self.print_horizontal_line(handle, '┼')?;
} else { } else {
@ -298,7 +298,7 @@ impl<'a> Printer for InteractivePrinter<'a> {
} }
fn print_footer(&mut self, handle: &mut dyn Write) -> Result<()> { fn print_footer(&mut self, handle: &mut dyn Write) -> Result<()> {
if self.config.output_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)
{ {
self.print_horizontal_line(handle, '┴') self.print_horizontal_line(handle, '┴')

View File

@ -4,7 +4,7 @@ use std::str::FromStr;
use crate::errors::*; use crate::errors::*;
#[derive(Debug, Eq, PartialEq, Copy, Clone, Hash)] #[derive(Debug, Eq, PartialEq, Copy, Clone, Hash)]
pub enum OutputComponent { pub enum StyleComponent {
Auto, Auto,
Changes, Changes,
Grid, Grid,
@ -15,92 +15,80 @@ pub enum OutputComponent {
Plain, Plain,
} }
#[derive(Debug, Eq, PartialEq, Copy, Clone, Hash)] impl StyleComponent {
pub enum OutputWrap { pub fn components(self, interactive_terminal: bool) -> &'static [StyleComponent] {
Character,
None,
}
impl Default for OutputWrap {
fn default() -> Self {
OutputWrap::None
}
}
impl OutputComponent {
pub fn components(self, interactive_terminal: bool) -> &'static [OutputComponent] {
match self { match self {
OutputComponent::Auto => { StyleComponent::Auto => {
if interactive_terminal { if interactive_terminal {
OutputComponent::Full.components(interactive_terminal) StyleComponent::Full.components(interactive_terminal)
} else { } else {
OutputComponent::Plain.components(interactive_terminal) StyleComponent::Plain.components(interactive_terminal)
} }
} }
OutputComponent::Changes => &[OutputComponent::Changes], StyleComponent::Changes => &[StyleComponent::Changes],
OutputComponent::Grid => &[OutputComponent::Grid], StyleComponent::Grid => &[StyleComponent::Grid],
OutputComponent::Header => &[OutputComponent::Header], StyleComponent::Header => &[StyleComponent::Header],
OutputComponent::Numbers => &[OutputComponent::Numbers], StyleComponent::Numbers => &[StyleComponent::Numbers],
OutputComponent::Snip => &[OutputComponent::Snip], StyleComponent::Snip => &[StyleComponent::Snip],
OutputComponent::Full => &[ StyleComponent::Full => &[
OutputComponent::Changes, StyleComponent::Changes,
OutputComponent::Grid, StyleComponent::Grid,
OutputComponent::Header, StyleComponent::Header,
OutputComponent::Numbers, StyleComponent::Numbers,
OutputComponent::Snip, StyleComponent::Snip,
], ],
OutputComponent::Plain => &[], StyleComponent::Plain => &[],
} }
} }
} }
impl FromStr for OutputComponent { impl FromStr for StyleComponent {
type Err = Error; type Err = Error;
fn from_str(s: &str) -> Result<Self> { fn from_str(s: &str) -> Result<Self> {
match s { match s {
"auto" => Ok(OutputComponent::Auto), "auto" => Ok(StyleComponent::Auto),
"changes" => Ok(OutputComponent::Changes), "changes" => Ok(StyleComponent::Changes),
"grid" => Ok(OutputComponent::Grid), "grid" => Ok(StyleComponent::Grid),
"header" => Ok(OutputComponent::Header), "header" => Ok(StyleComponent::Header),
"numbers" => Ok(OutputComponent::Numbers), "numbers" => Ok(StyleComponent::Numbers),
"snip" => Ok(OutputComponent::Snip), "snip" => Ok(StyleComponent::Snip),
"full" => Ok(OutputComponent::Full), "full" => Ok(StyleComponent::Full),
"plain" => Ok(OutputComponent::Plain), "plain" => Ok(StyleComponent::Plain),
_ => Err(format!("Unknown style '{}'", s).into()), _ => Err(format!("Unknown style '{}'", s).into()),
} }
} }
} }
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
pub struct OutputComponents(pub HashSet<OutputComponent>); pub struct StyleComponents(pub HashSet<StyleComponent>);
impl OutputComponents { impl StyleComponents {
pub fn new(components: &[OutputComponent]) -> OutputComponents { pub fn new(components: &[StyleComponent]) -> StyleComponents {
OutputComponents(components.iter().cloned().collect()) StyleComponents(components.iter().cloned().collect())
} }
pub fn changes(&self) -> bool { pub fn changes(&self) -> bool {
self.0.contains(&OutputComponent::Changes) self.0.contains(&StyleComponent::Changes)
} }
pub fn grid(&self) -> bool { pub fn grid(&self) -> bool {
self.0.contains(&OutputComponent::Grid) self.0.contains(&StyleComponent::Grid)
} }
pub fn header(&self) -> bool { pub fn header(&self) -> bool {
self.0.contains(&OutputComponent::Header) self.0.contains(&StyleComponent::Header)
} }
pub fn numbers(&self) -> bool { pub fn numbers(&self) -> bool {
self.0.contains(&OutputComponent::Numbers) self.0.contains(&StyleComponent::Numbers)
} }
pub fn snip(&self) -> bool { pub fn snip(&self) -> bool {
self.0.contains(&OutputComponent::Snip) self.0.contains(&StyleComponent::Snip)
} }
pub fn plain(&self) -> bool { pub fn plain(&self) -> bool {
self.0.iter().all(|c| c == &OutputComponent::Plain) self.0.iter().all(|c| c == &StyleComponent::Plain)
} }
} }

11
src/wrap.rs Normal file
View File

@ -0,0 +1,11 @@
#[derive(Debug, Eq, PartialEq, Copy, Clone, Hash)]
pub enum OutputWrap {
Character,
None,
}
impl Default for OutputWrap {
fn default() -> Self {
OutputWrap::None
}
}