1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
#[cfg(feature = "text")]
use std::{fmt, io};
use crate::iter::AllChangesIter;
use crate::text::{DiffableStr, TextDiff};
use crate::types::{Algorithm, DiffOp};
struct MissingNewlineHint(bool);
impl fmt::Display for MissingNewlineHint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.0 {
write!(f, "\n\\ No newline at end of file")?;
}
Ok(())
}
}
#[derive(Copy, Clone, Debug)]
struct UnifiedDiffHunkRange(usize, usize);
impl UnifiedDiffHunkRange {
fn start(&self) -> usize {
self.0
}
fn end(&self) -> usize {
self.1
}
}
impl fmt::Display for UnifiedDiffHunkRange {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut beginning = self.start() + 1;
let len = self.end().saturating_sub(self.start());
if len == 1 {
write!(f, "{}", beginning)
} else {
if len == 0 {
beginning -= 1;
}
write!(f, "{},{}", beginning, len)
}
}
}
pub struct UnifiedHunkHeader {
old_range: UnifiedDiffHunkRange,
new_range: UnifiedDiffHunkRange,
}
impl UnifiedHunkHeader {
pub fn new(ops: &[DiffOp]) -> UnifiedHunkHeader {
let first = ops[0];
let last = ops[ops.len() - 1];
let old_start = first.old_range().start;
let new_start = first.new_range().start;
let old_end = last.old_range().end;
let new_end = last.new_range().end;
UnifiedHunkHeader {
old_range: UnifiedDiffHunkRange(old_start, old_end),
new_range: UnifiedDiffHunkRange(new_start, new_end),
}
}
}
impl fmt::Display for UnifiedHunkHeader {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "@@ -{} +{} @@", &self.old_range, &self.new_range)
}
}
pub struct UnifiedDiff<'diff, 'old, 'new, 'bufs, T: DiffableStr + ?Sized> {
diff: &'diff TextDiff<'old, 'new, 'bufs, T>,
context_radius: usize,
missing_newline_hint: bool,
header: Option<(String, String)>,
}
impl<'diff, 'old, 'new, 'bufs, T: DiffableStr + ?Sized> UnifiedDiff<'diff, 'old, 'new, 'bufs, T> {
pub fn from_text_diff(diff: &'diff TextDiff<'old, 'new, 'bufs, T>) -> Self {
UnifiedDiff {
diff,
context_radius: 3,
missing_newline_hint: true,
header: None,
}
}
pub fn context_radius(&mut self, n: usize) -> &mut Self {
self.context_radius = n;
self
}
pub fn header(&mut self, a: &str, b: &str) -> &mut Self {
self.header = Some((a.to_string(), b.to_string()));
self
}
pub fn missing_newline_hint(&mut self, yes: bool) -> &mut Self {
self.missing_newline_hint = yes;
self
}
pub fn iter_hunks(&self) -> impl Iterator<Item = UnifiedDiffHunk<'diff, 'old, 'new, 'bufs, T>> {
let diff = self.diff;
let missing_newline_hint = self.missing_newline_hint;
self.diff
.grouped_ops(self.context_radius)
.into_iter()
.filter(|ops| !ops.is_empty())
.map(move |ops| UnifiedDiffHunk::new(ops, diff, missing_newline_hint))
}
pub fn to_writer<W: io::Write>(&self, mut w: W) -> Result<(), io::Error>
where
'diff: 'old + 'new + 'bufs,
{
let mut header = self.header.as_ref();
for hunk in self.iter_hunks() {
if let Some((old_file, new_file)) = header.take() {
writeln!(w, "--- {}", old_file)?;
writeln!(w, "+++ {}", new_file)?;
}
write!(w, "{}", hunk)?;
}
Ok(())
}
fn header_opt(&mut self, header: Option<(&str, &str)>) -> &mut Self {
if let Some((a, b)) = header {
self.header(a, b);
}
self
}
}
pub struct UnifiedDiffHunk<'diff, 'old, 'new, 'bufs, T: DiffableStr + ?Sized> {
diff: &'diff TextDiff<'old, 'new, 'bufs, T>,
ops: Vec<DiffOp>,
missing_newline_hint: bool,
}
impl<'diff, 'old, 'new, 'bufs, T: DiffableStr + ?Sized>
UnifiedDiffHunk<'diff, 'old, 'new, 'bufs, T>
{
pub fn new(
ops: Vec<DiffOp>,
diff: &'diff TextDiff<'old, 'new, 'bufs, T>,
missing_newline_hint: bool,
) -> UnifiedDiffHunk<'diff, 'old, 'new, 'bufs, T> {
UnifiedDiffHunk {
diff,
ops,
missing_newline_hint,
}
}
pub fn header(&self) -> UnifiedHunkHeader {
UnifiedHunkHeader::new(&self.ops)
}
pub fn ops(&self) -> &[DiffOp] {
&self.ops
}
pub fn missing_newline_hint(&self) -> bool {
self.missing_newline_hint
}
pub fn iter_changes<'x, 'slf>(&'slf self) -> AllChangesIter<'slf, 'x, T>
where
'x: 'slf + 'old + 'new,
'old: 'x,
'new: 'x,
{
AllChangesIter::new(self.diff.old_slices(), self.diff.new_slices(), self.ops())
}
pub fn to_writer<W: io::Write>(&self, mut w: W) -> Result<(), io::Error>
where
'diff: 'old + 'new + 'bufs,
{
for (idx, change) in self.iter_changes().enumerate() {
if idx == 0 {
writeln!(w, "{}", self.header())?;
}
write!(w, "{}", change.tag())?;
w.write_all(change.value().as_bytes())?;
if !self.diff.newline_terminated() {
writeln!(w)?;
}
if self.diff.newline_terminated() && change.missing_newline() {
writeln!(w, "{}", MissingNewlineHint(self.missing_newline_hint))?;
}
}
Ok(())
}
}
impl<'diff, 'old, 'new, 'bufs, T: DiffableStr + ?Sized> fmt::Display
for UnifiedDiffHunk<'diff, 'old, 'new, 'bufs, T>
where
'diff: 'old + 'new + 'bufs,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (idx, change) in self.iter_changes().enumerate() {
if idx == 0 {
writeln!(f, "{}", self.header())?;
}
write!(f, "{}{}", change.tag(), change.to_string_lossy())?;
if !self.diff.newline_terminated() {
writeln!(f)?;
}
if self.diff.newline_terminated() && change.missing_newline() {
writeln!(f, "{}", MissingNewlineHint(self.missing_newline_hint))?;
}
}
Ok(())
}
}
impl<'diff, 'old, 'new, 'bufs, T: DiffableStr + ?Sized> fmt::Display
for UnifiedDiff<'diff, 'old, 'new, 'bufs, T>
where
'diff: 'old + 'new + 'bufs,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut header = self.header.as_ref();
for hunk in self.iter_hunks() {
if let Some((old_file, new_file)) = header.take() {
writeln!(f, "--- {}", old_file)?;
writeln!(f, "+++ {}", new_file)?;
}
write!(f, "{}", hunk)?;
}
Ok(())
}
}
pub fn unified_diff<'old, 'new>(
alg: Algorithm,
old: &'old str,
new: &'new str,
n: usize,
header: Option<(&str, &str)>,
) -> String {
TextDiff::configure()
.algorithm(alg)
.diff_lines(old, new)
.unified_diff()
.context_radius(n)
.header_opt(header)
.to_string()
}
#[test]
fn test_unified_diff() {
let diff = TextDiff::from_lines(
"a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl\nm\nn\no\np\nq\nr\ns\nt\nu\nv\nw\nx\ny\nz\nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nO\nP\nQ\nR\nS\nT\nU\nV\nW\nX\nY\nZ",
"a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl\nm\nn\no\np\nq\nr\nS\nt\nu\nv\nw\nx\ny\nz\nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\no\nP\nQ\nR\nS\nT\nU\nV\nW\nX\nY\nZ",
);
insta::assert_snapshot!(&diff.unified_diff().header("a.txt", "b.txt").to_string());
}
#[test]
fn test_empty_unified_diff() {
let diff = TextDiff::from_lines("abc", "abc");
assert_eq!(diff.unified_diff().header("a.txt", "b.txt").to_string(), "");
}
#[test]
fn test_unified_diff_newline_hint() {
let diff = TextDiff::from_lines("a\n", "b");
insta::assert_snapshot!(&diff.unified_diff().header("a.txt", "b.txt").to_string());
insta::assert_snapshot!(&diff
.unified_diff()
.missing_newline_hint(false)
.header("a.txt", "b.txt")
.to_string());
}