on master help sign in
Handle broken pipes, closes #9
commit1f2bcf57baf92c83f8668f7908532d2b849e83ee authorsharkdp <davidpeter@web.de> dateSun 22 Apr 2018, 14:37 (9 years ago) parentde11558
1 file changed+23−14
src/main.rs+23−14
src/main.rs+23−14
@@ -8,7 +8,7 @@ extern crate syntect;
88extern crate clap;
99
1010use std::collections::HashMap;
11−use std::io::{self, BufRead, Result};
11+use std::io::{self, BufRead, Result, Write, ErrorKind, StdoutLock};
1212use std::path::Path;
1313use std::process;
1414
@@ -37,11 +37,13 @@ type LineChanges = HashMap<u32, LineChange>;
3737const PANEL_WIDTH: usize = 7;
3838const GRID_COLOR: u8 = 238;
3939
40−fn print_horizontal_line(grid_char: char, term_width: usize) {
40+fn print_horizontal_line(handle: &mut StdoutLock, grid_char: char, term_width: usize) -> io::Result<()> {
4141 let bar = "─".repeat(term_width - (PANEL_WIDTH + 1));
4242 let line = format!("{}{}{}", "─".repeat(PANEL_WIDTH), grid_char, bar);
4343
44− println!("{}", Fixed(GRID_COLOR).paint(line));
44+ write!(handle, "{}\n", Fixed(GRID_COLOR).paint(line))?;
45+
46+ Ok(())
4547}
4648
4749fn print_file<P: AsRef<Path>>(
@@ -52,20 +54,24 @@ fn print_file<P: AsRef<Path>>(
5254) -> io::Result<()> {
5355 let mut highlighter = HighlightFile::new(filename.as_ref().clone(), syntax_set, theme)?;
5456
57+ let stdout = io::stdout();
58+ let mut handle = stdout.lock();
59+
5560 let term = Term::stdout();
5661 let (_, term_width) = term.size();
5762 let term_width = term_width as usize;
5863
59− print_horizontal_line('┬', term_width);
64+ print_horizontal_line(&mut handle, '┬', term_width)?;
6065
61− println!(
62− "{}{} {}",
66+ write!(
67+ handle,
68+ "{}{} {}\n",
6369 " ".repeat(PANEL_WIDTH),
6470 Fixed(GRID_COLOR).paint("│"),
6571 White.bold().paint(filename.as_ref().to_string_lossy())
66− );
72+ )?;
6773
68− print_horizontal_line('┼', term_width);
74+ print_horizontal_line(&mut handle, '┼', term_width)?;
6975
7076 for (idx, maybe_line) in highlighter.reader.lines().enumerate() {
7177 let line_nr = idx + 1;
@@ -84,16 +90,17 @@ fn print_file<P: AsRef<Path>>(
8490 Style::default().paint(" ")
8591 };
8692
87− println!(
88− "{} {} {} {}",
93+ write!(
94+ handle,
95+ "{} {} {} {}\n",
8996 Fixed(244).paint(format!("{:4}", line_nr)),
9097 line_change,
9198 Fixed(GRID_COLOR).paint("│"),
9299 as_24_bit_terminal_escaped(&regions, false)
93− );
100+ )?;
94101 }
95102
96− print_horizontal_line('┴', term_width);
103+ print_horizontal_line(&mut handle, '┴', term_width)?;
97104
98105 Ok(())
99106}
@@ -196,7 +203,9 @@ fn main() {
196203 let result = run(&matches);
197204
198205 if let Err(e) = result {
199− eprintln!("{}: {}", Red.paint("[bat error]"), e);
200− process::exit(1);
206+ if e.kind() != ErrorKind::BrokenPipe {
207+ eprintln!("{}: {}", Red.paint("[bat error]"), e);
208+ process::exit(1);
209+ }
201210 }
202211}