flake_edit/
diff.rs

1//! Wrapper for diffing the changes
2
3use std::io::IsTerminal;
4pub struct Diff<'a> {
5    old: &'a str,
6    new: &'a str,
7}
8
9fn use_color() -> bool {
10    // Respect NO_COLOR (https://no-color.org/)
11    if std::env::var("NO_COLOR").is_ok() {
12        return false;
13    }
14    std::io::stdout().is_terminal()
15}
16
17impl<'a> Diff<'a> {
18    pub fn new(old: &'a str, new: &'a str) -> Self {
19        Self { old, new }
20    }
21    pub fn compare(&self) {
22        print!("{}", self.to_string_colored(use_color()));
23    }
24    /// Return the diff as a string, optionally with ANSI colors
25    pub fn to_string_colored(&self, color: bool) -> String {
26        let patch = diffy::create_patch(self.old, self.new);
27        let f = if color {
28            diffy::PatchFormatter::new().with_color()
29        } else {
30            diffy::PatchFormatter::new()
31        };
32        f.fmt_patch(&patch).to_string()
33    }
34    /// Return the diff as a plain string without colors
35    pub fn to_string_plain(&self) -> String {
36        self.to_string_colored(false)
37    }
38}