Files
Rack/src/printer.rs
Cameron Cordes a403dbda76 Omit files and print only match options added
These are essential for using the tool for scripting purposes.
2020-05-20 17:54:46 -04:00

114 lines
3.2 KiB
Rust

extern crate term;
use super::config::Config;
use super::filematch::*;
pub trait Printer {
fn print(&self);
}
pub struct ColorPrinter<'a> {
pub config: &'a Config,
pub file_match: &'a FileMatch,
}
pub struct SimplePrinter<'a> {
pub config: &'a Config,
pub file_match: &'a FileMatch,
}
impl<'a> Printer for SimplePrinter<'a> {
fn print(&self) {
self.print_file_name();
for mat in &self.file_match.matches {
self.print_linenumber(mat);
let mut last_position = 0;
for (idx, match_index) in mat.match_indexes.iter().enumerate() {
self.print_first_part_of_line(mat, last_position, match_index.start);
self.print_match(mat, match_index);
if idx == mat.match_indexes.len() - 1 {
self.print_end_of_line(mat, match_index);
last_position = 0;
} else {
last_position = match_index.end;
}
}
}
println!();
}
}
impl<'a> SimplePrinter<'a> {
fn print_file_name(&self) {
if !self.config.omit_filenames {
println!("{}:", self.file_match.file_name);
}
}
fn print_linenumber(&self, mat: &Match) {
if !self.config.omit_filenames {
print!("{}: ", mat.line_number);
}
}
fn print_first_part_of_line(&self, mat: &Match, current_position: usize, match_start: usize) {
if !self.config.match_only {
print!("{}", mat.text.get(current_position..match_start).unwrap());
}
}
fn print_match(&self, mat: &Match, index: &MatchIndex) {
print!("{}", mat.text.get(index.start..index.end).unwrap());
}
fn print_end_of_line(&self, mat: &Match, index: &MatchIndex) {
if !self.config.match_only {
println!("{}", mat.text.get(index.end..mat.text.len()).unwrap());
} else {
println!();
}
}
}
impl<'a> Printer for ColorPrinter<'a> {
fn print(&self) {
let simple_printer = SimplePrinter {
config: self.config,
file_match: self.file_match,
};
let mut term = term::stdout().unwrap();
term.fg(term::color::YELLOW).unwrap();
term.attr(term::Attr::Bold).unwrap();
simple_printer.print_file_name();
term.reset().unwrap();
for mat in &self.file_match.matches {
term.attr(term::Attr::Bold).unwrap();
simple_printer.print_linenumber(mat);
term.reset().unwrap();
let mut last_position = 0;
for (idx, match_index) in mat.match_indexes.iter().enumerate() {
simple_printer.print_first_part_of_line(mat, last_position, match_index.start);
term.fg(term::color::BRIGHT_RED).unwrap();
simple_printer.print_match(mat, match_index);
term.reset().unwrap();
if idx == mat.match_indexes.len() - 1 {
simple_printer.print_end_of_line(mat, match_index);
last_position = 0;
} else {
last_position = match_index.end;
}
}
}
println!();
}
}