Building a colored line diff CLI in Rust with clap and similar

This post builds a small command-line tool that compares two text files line by line and prints the result with - for removed lines (red) and + for added lines (green), similar to diff -u without the hunk headers.
Two crates do the work:
clapparses the command-line arguments from a struct definition.similarcomputes the diff. It uses the Myers algorithm by default, the same family of algorithm asdiffandgit diff.
cargo new difftoolcd difftoolcargo add clap --features derivecargo add similarThe code below was written against clap 4.6 and similar 3.2.
Defining the arguments
Section titled “Defining the arguments”With clap’s derive API, each struct field is a positional argument, and the doc comments become the --help text:
use std::path::PathBuf;
use clap::Parser;
/// Compare two text files line by line.#[derive(Parser)]#[command(version)]struct Cli { /// The original file old: PathBuf, /// The changed file new: PathBuf,}Cli::parse() reads std::env::args(), prints usage and exits if the arguments are wrong, and handles --help and --version for you.
Diffing and printing
Section titled “Diffing and printing”The complete src/main.rs:
use std::fs;use std::io;use std::path::PathBuf;use std::process::ExitCode;
use clap::Parser;use similar::{ChangeTag, TextDiff};
/// Compare two text files line by line.#[derive(Parser)]#[command(version)]struct Cli { /// The original file old: PathBuf, /// The changed file new: PathBuf,}
const RED: &str = "\x1b[31m";const GREEN: &str = "\x1b[32m";const RESET: &str = "\x1b[0m";
fn main() -> io::Result<ExitCode> { let cli = Cli::parse(); let old = fs::read_to_string(&cli.old)?; let new = fs::read_to_string(&cli.new)?;
let diff = TextDiff::from_lines(old.as_str(), new.as_str()); let mut changed = false;
for change in diff.iter_all_changes() { let (sign, color) = match change.tag() { ChangeTag::Delete => ("-", RED), ChangeTag::Insert => ("+", GREEN), ChangeTag::Equal => (" ", ""), }; if change.tag() != ChangeTag::Equal { changed = true; }
// Each change includes its line ending; strip it so the // reset code goes before the newline. let line = change.to_string_lossy(); println!("{color}{sign}{}{RESET}", line.trim_end_matches(['\r', '\n'])); }
// Like `diff`: exit 0 if the files match, 1 if they differ. Ok(if changed { ExitCode::from(1) } else { ExitCode::SUCCESS })}What’s going on:
fs::read_to_stringreads each file in one go. If a file is missing or isn’t valid UTF-8, the?returns the error frommain, which prints it and exits with a non-zero status.TextDiff::from_linessplits both inputs into lines and diffs them.iter_all_changesyields every line, tagged asDelete,Insert, orEqual.- The colors are plain ANSI escape codes. They work in Linux and macOS terminals and in Windows Terminal; if you need to turn them off when output is piped, check
std::io::IsTerminalor use a crate such asanstream. - Returning an
ExitCodemakes the tool usable in scripts, e.g.difftool a.txt b.txt > /dev/null || echo "files differ".
Running it
Section titled “Running it”printf 'apple\nbanana\ncherry\n' > a.txtprintf 'apple\nblueberry\ncherry\ndate\n' > b.txtcargo run -- a.txt b.txtOutput (without the colors):
apple-banana+blueberry cherry+dateWhere to go from here
Section titled “Where to go from here”- Printing every unchanged line gets noisy on large files.
TextDiffhas aunified_diff()method that produces standard unified-diff output with context lines and@@hunk headers. similarcan also diff by words or characters (TextDiff::from_words,TextDiff::from_chars), which is useful for highlighting the changed part of a modified line.read_to_stringloads both files into memory, which is fine for source files and config, but not for multi-gigabyte logs.
Further reading
Section titled “Further reading”© 2026 David Li · Home · Blog · RSS ·Classic site · Built with Astro, Starlight and three.js · Logos:Font Awesome Free (CC BY 4.0)