likewise/examples/terminal-inline.rs
Armin Ronacher f3e401fc17 Change behavior of inline diff to be word based
This also fixes a bug with bad indexes and updates the inline terminal
example.
2021-01-31 22:02:09 +01:00

57 lines
1.7 KiB
Rust

use std::fmt;
use std::fs::read_to_string;
use std::process::exit;
use console::{style, Style};
use similar::text::{ChangeTag, TextDiff};
struct Line(Option<usize>);
impl fmt::Display for Line {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.0 {
None => write!(f, " "),
Some(idx) => write!(f, "{:<4}", idx + 1),
}
}
}
fn main() {
let args: Vec<_> = std::env::args_os().collect();
if args.len() != 3 {
eprintln!("usage: terminal-inline [old] [new]");
exit(1);
}
let old = read_to_string(&args[1]).unwrap();
let new = read_to_string(&args[2]).unwrap();
let diff = TextDiff::from_lines(&old, &new);
for group in diff.grouped_ops(5) {
for op in group {
for change in diff.iter_inline_changes(&op) {
let (sign, s) = match change.tag() {
ChangeTag::Delete => ("-", Style::new().red()),
ChangeTag::Insert => ("+", Style::new().green()),
ChangeTag::Equal => (" ", Style::new()),
};
print!(
"{}{} |{}",
style(Line(change.old_index())).dim(),
style(Line(change.new_index())).dim(),
s.apply_to(sign).bold(),
);
for &(emphasized, value) in change.values() {
if emphasized {
print!("{}", s.apply_to(value).underlined().on_black());
} else {
print!("{}", s.apply_to(value));
}
}
if change.is_missing_newline() {
println!();
}
}
}
}
}