Skip to content

Commit

Permalink
Try using similar rather than difflib
Browse files Browse the repository at this point in the history
Gives much better diffs when lines are inserted

Fixes #755
  • Loading branch information
sourcefrog committed Feb 25, 2024
1 parent 5a09137 commit 5c7e7a4
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 15 deletions.
5 changes: 3 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ trycmd = "0.14.21"
anyhow = "1.0.79"
concolor-control = { version = "0.0.7", features = ["auto"] }
git-conventional = "0.12.4"
similar = "2.4"

[dev-dependencies]
assert_fs = "1.1"
Expand Down
18 changes: 5 additions & 13 deletions src/ops/replace.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use std::collections::BTreeMap;
use std::path::Path;

use similar::TextDiff;

use crate::config::Replace;
use crate::error::CargoResult;

Expand Down Expand Up @@ -118,25 +120,15 @@ pub fn do_file_replacements(

if data != replaced {
if dry_run {
let display_path = path.display().to_string();
let data_lines: Vec<_> = data.lines().map(|s| format!("{}\n", s)).collect();
let replaced_lines: Vec<_> = replaced.lines().map(|s| format!("{}\n", s)).collect();
let diff = difflib::unified_diff(
&data_lines,
&replaced_lines,
display_path.as_str(),
display_path.as_str(),
"original",
"replaced",
0,
);
if noisy {
let diff = TextDiff::from_lines(&data, &replaced);
let display_path = path.display().to_string();
let _ = crate::ops::shell::status(
"Replacing",
format!(
"in {}\n{}",
path.display(),
itertools::join(diff.into_iter(), "")
diff.unified_diff().header(&display_path, &display_path)
),
);
} else {
Expand Down

0 comments on commit 5c7e7a4

Please sign in to comment.