on v0.15.0 help sign in
bat/src/controller.rs
227 lines 8.0 kB history raw
1use std::io::{self, Write};
3use crate::assets::HighlightingAssets;
4use crate::config::{Config, VisibleLines};
5#[cfg(feature = "git")]
6use crate::diff::{get_git_diff, LineChanges};
7use crate::error::*;
8use crate::input::{Input, InputReader, OpenedInput};
9#[cfg(feature = "git")]
10use crate::line_range::LineRange;
11use crate::line_range::{LineRanges, RangeCheckResult};
12use crate::output::OutputType;
13#[cfg(feature = "paging")]
14use crate::paging::PagingMode;
15use crate::printer::{InteractivePrinter, Printer, SimplePrinter};
17pub struct Controller<'a> {
18 config: &'a Config<'a>,
19 assets: &'a HighlightingAssets,
22impl<'b> Controller<'b> {
23 pub fn new<'a>(config: &'a Config, assets: &'a HighlightingAssets) -> Controller<'a> {
24 Controller { config, assets }
25 }
27 pub fn run(&self, inputs: Vec<Input>) -> Result<bool> {
28 self.run_with_error_handler(inputs, default_error_handler)
29 }
31 pub fn run_with_error_handler(
32 &self,
33 inputs: Vec<Input>,
34 handle_error: impl Fn(&Error, &mut dyn Write),
35 ) -> Result<bool> {
36 let mut output_type;
38 #[cfg(feature = "paging")]
39 {
40 use crate::input::InputKind;
41 use std::path::Path;
43 // Do not launch the pager if NONE of the input files exist
44 let mut paging_mode = self.config.paging_mode;
45 if self.config.paging_mode != PagingMode::Never {
46 let call_pager = inputs.iter().any(|ref input| {
47 if let InputKind::OrdinaryFile(ref path) = input.kind {
48 Path::new(path).exists()
49 } else {
50 true
51 }
52 });
53 if !call_pager {
54 paging_mode = PagingMode::Never;
55 }
56 }
57 output_type = OutputType::from_mode(paging_mode, self.config.pager)?;
58 }
60 #[cfg(not(feature = "paging"))]
61 {
62 output_type = OutputType::stdout();
63 }
65 let attached_to_pager = output_type.is_pager();
66 let writer = output_type.handle()?;
67 let mut no_errors: bool = true;
69 let stderr = io::stderr();
70 let print_error = |error: &Error, write: &mut dyn Write| {
71 if attached_to_pager {
72 handle_error(error, write);
73 } else {
74 handle_error(error, &mut stderr.lock());
75 }
76 };
78 for input in inputs.into_iter() {
79 match input.open(io::stdin().lock()) {
80 Err(error) => {
81 print_error(&error, writer);
82 no_errors = false;
83 }
84 Ok(mut opened_input) => {
85 #[cfg(feature = "git")]
86 let line_changes = if self.config.visible_lines.diff_mode()
87 || (!self.config.loop_through && self.config.style_components.changes())
88 {
89 match opened_input.kind {
90 crate::input::OpenedInputKind::OrdinaryFile(ref path) => {
91 let diff = get_git_diff(path);
93 // Skip files without Git modifications
94 if self.config.visible_lines.diff_mode()
95 && diff
96 .as_ref()
97 .map(|changes| changes.is_empty())
98 .unwrap_or(false)
99 {
100 continue;
101 }
103 diff
104 }
105 _ if self.config.visible_lines.diff_mode() => {
106 // Skip non-file inputs in diff mode
107 continue;
108 }
109 _ => None,
110 }
111 } else {
112 None
113 };
115 let mut printer: Box<dyn Printer> = if self.config.loop_through {
116 Box::new(SimplePrinter::new())
117 } else {
118 Box::new(InteractivePrinter::new(
119 &self.config,
120 &self.assets,
121 &mut opened_input,
122 #[cfg(feature = "git")]
123 &line_changes,
124 ))
125 };
127 let result = self.print_file(
128 &mut *printer,
129 writer,
130 &mut opened_input,
131 #[cfg(feature = "git")]
132 &line_changes,
133 );
135 if let Err(error) = result {
136 print_error(&error, writer);
137 no_errors = false;
138 }
139 }
140 }
141 }
143 Ok(no_errors)
144 }
146 fn print_file<'a>(
147 &self,
148 printer: &mut dyn Printer,
149 writer: &mut dyn Write,
150 input: &mut OpenedInput,
151 #[cfg(feature = "git")] line_changes: &Option<LineChanges>,
152 ) -> Result<()> {
153 if !input.reader.first_line.is_empty() || self.config.style_components.header() {
154 printer.print_header(writer, input)?;
155 }
157 if !input.reader.first_line.is_empty() {
158 let line_ranges = match self.config.visible_lines {
159 VisibleLines::Ranges(ref line_ranges) => line_ranges.clone(),
160 #[cfg(feature = "git")]
161 VisibleLines::DiffContext(context) => {
162 let mut line_ranges: Vec<LineRange> = vec![];
164 if let Some(line_changes) = line_changes {
165 for line in line_changes.keys() {
166 let line = *line as usize;
167 line_ranges.push(LineRange::new(line - context, line + context));
168 }
169 }
171 LineRanges::from(line_ranges)
172 }
173 };
175 self.print_file_ranges(printer, writer, &mut input.reader, &line_ranges)?;
176 }
177 printer.print_footer(writer, input)?;
179 Ok(())
180 }
182 fn print_file_ranges(
183 &self,
184 printer: &mut dyn Printer,
185 writer: &mut dyn Write,
186 reader: &mut InputReader,
187 line_ranges: &LineRanges,
188 ) -> Result<()> {
189 let mut line_buffer = Vec::new();
190 let mut line_number: usize = 1;
192 let mut first_range: bool = true;
193 let mut mid_range: bool = false;
195 while reader.read_line(&mut line_buffer)? {
196 match line_ranges.check(line_number) {
197 RangeCheckResult::BeforeOrBetweenRanges => {
198 // Call the printer in case we need to call the syntax highlighter
199 // for this line. However, set `out_of_range` to `true`.
200 printer.print_line(true, writer, line_number, &line_buffer)?;
201 mid_range = false;
202 }
204 RangeCheckResult::InRange => {
205 if self.config.style_components.snip() {
206 if first_range {
207 first_range = false;
208 mid_range = true;
209 } else if !mid_range {
210 mid_range = true;
211 printer.print_snip(writer)?;
212 }
213 }
215 printer.print_line(false, writer, line_number, &line_buffer)?;
216 }
217 RangeCheckResult::AfterLastRange => {
218 break;
219 }
220 }
222 line_number += 1;
223 line_buffer.clear();
224 }
225 Ok(())
226 }