on 0e38c17 help sign in
bat/src/controller.rs
229 lines 8.1 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 (index, input) in inputs.into_iter().enumerate() {
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(&self.config))
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 index != 0,
132 #[cfg(feature = "git")]
133 &line_changes,
134 );
136 if let Err(error) = result {
137 print_error(&error, writer);
138 no_errors = false;
139 }
140 }
141 }
142 }
144 Ok(no_errors)
145 }
147 fn print_file<'a>(
148 &self,
149 printer: &mut dyn Printer,
150 writer: &mut dyn Write,
151 input: &mut OpenedInput,
152 add_header_padding: bool,
153 #[cfg(feature = "git")] line_changes: &Option<LineChanges>,
154 ) -> Result<()> {
155 if !input.reader.first_line.is_empty() || self.config.style_components.header() {
156 printer.print_header(writer, input, add_header_padding)?;
157 }
159 if !input.reader.first_line.is_empty() {
160 let line_ranges = match self.config.visible_lines {
161 VisibleLines::Ranges(ref line_ranges) => line_ranges.clone(),
162 #[cfg(feature = "git")]
163 VisibleLines::DiffContext(context) => {
164 let mut line_ranges: Vec<LineRange> = vec![];
166 if let Some(line_changes) = line_changes {
167 for line in line_changes.keys() {
168 let line = *line as usize;
169 line_ranges.push(LineRange::new(line - context, line + context));
170 }
171 }
173 LineRanges::from(line_ranges)
174 }
175 };
177 self.print_file_ranges(printer, writer, &mut input.reader, &line_ranges)?;
178 }
179 printer.print_footer(writer, input)?;
181 Ok(())
182 }
184 fn print_file_ranges(
185 &self,
186 printer: &mut dyn Printer,
187 writer: &mut dyn Write,
188 reader: &mut InputReader,
189 line_ranges: &LineRanges,
190 ) -> Result<()> {
191 let mut line_buffer = Vec::new();
192 let mut line_number: usize = 1;
194 let mut first_range: bool = true;
195 let mut mid_range: bool = false;
197 while reader.read_line(&mut line_buffer)? {
198 match line_ranges.check(line_number) {
199 RangeCheckResult::BeforeOrBetweenRanges => {
200 // Call the printer in case we need to call the syntax highlighter
201 // for this line. However, set `out_of_range` to `true`.
202 printer.print_line(true, writer, line_number, &line_buffer)?;
203 mid_range = false;
204 }
206 RangeCheckResult::InRange => {
207 if self.config.style_components.snip() {
208 if first_range {
209 first_range = false;
210 mid_range = true;
211 } else if !mid_range {
212 mid_range = true;
213 printer.print_snip(writer)?;
214 }
215 }
217 printer.print_line(false, writer, line_number, &line_buffer)?;
218 }
219 RangeCheckResult::AfterLastRange => {
220 break;
221 }
222 }
224 line_number += 1;
225 line_buffer.clear();
226 }
227 Ok(())
228 }