summaryrefslogtreecommitdiffstats
path: root/src/delta.rs
blob: 620e00e8199555da9a8e94468bff4648653473f4 (plain)
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
use std::borrow::Cow;
use std::io::BufRead;
use std::io::Write;

use bytelines::ByteLines;
use unicode_segmentation::UnicodeSegmentation;

use crate::ansi;
use crate::cli;
use crate::config::Config;
use crate::draw;
use crate::features;
use crate::format;
use crate::hunk_header;
use crate::paint::Painter;
use crate::parse;
use crate::style::{self, DecorationStyle};

#[derive(Clone, Debug, PartialEq)]
pub enum State {
    CommitMeta,                // In commit metadata section
    FileMeta, // In diff metadata section, between (possible) commit metadata and first hunk
    HunkHeader, // In hunk metadata line
    HunkZero, // In hunk; unchanged line
    HunkMinus(Option<String>), // In hunk; removed line (raw_line)
    HunkPlus(Option<String>), // In hunk; added line (raw_line)
    Unknown,
}

#[derive(Debug, PartialEq)]
pub enum Source {
    GitDiff,     // Coming from a `git diff` command
    DiffUnified, // Coming from a `diff -u` command
    Unknown,
}

impl State {
    fn is_in_hunk(&self) -> bool {
        matches!(*self, State::HunkHeader | State::HunkZero | State::HunkMinus(_) | State::HunkPlus(_))
    }
}

// Possible transitions, with actions on entry:
//
//
// | from \ to   | CommitMeta  | FileMeta    | HunkHeader  | HunkZero    | HunkMinus   | HunkPlus |
// |-------------+-------------+-------------+-------------+-------------+-------------+----------|
// | CommitMeta  | emit        | emit        |             |             |             |          |
// | FileMeta    |             | emit        | emit        |             |             |          |
// | HunkHeader  |             |             |             | emit        | push        | push     |
// | HunkZero    | emit        | emit        | emit        | emit        | push        | push     |
// | HunkMinus   | flush, emit | flush, emit | flush, emit | flush, emit | push        | push     |
// | HunkPlus    | flush, emit | flush, emit | flush, emit | flush, emit | flush, push | push     |

pub fn delta<I>(
    mut lines: ByteLines<I>,
    writer: &mut dyn Write,
    config: &Config,
) -> std::io::Result<()>
where
    I: BufRead,
{
    let mut painter = Painter::new(writer, config);
    let mut minus_file = "".to_string();
    let mut plus_file = "".to_string();
    let mut file_event = parse::FileEvent::NoEvent;
    let mut state = State::Unknown;
    let mut source = Source::Unknown;

    // When a file is modified, we use lines starting with '---' or '+++' to obtain the file name.
    // When a file is renamed without changes, we use lines starting with 'rename' to obtain the
    // file name (there is no diff hunk and hence no lines starting with '---' or '+++'). But when
    // a file is renamed with changes, both are present, and we rely on the following variables to
    // avoid emitting the file meta header line twice (#245).
    let mut current_file_pair;
    let mut handled_file_meta_header_line_file_pair = None;

    while let Some(Ok(raw_line_bytes)) = lines.next() {
        let raw_line = String::from_utf8_lossy(&raw_line_bytes);
        let raw_line = if config.max_line_length > 0 && raw_line.len() > config.max_line_length {
            ansi::truncate_str(&raw_line, config.max_line_length, &config.truncation_symbol)
        } else {
            raw_line
        };
        let line = ansi::strip_ansi_codes(&raw_line).to_string();
        if source == Source::Unknown {
            source = detect_source(&line);
        }
        if line.starts_with("commit ") {
            painter.paint_buffered_minus_and_plus_lines();
            state = State::CommitMeta;
            if should_handle(&state, config) {
                painter.emit()?;
                handle_commit_meta_header_line(&mut painter, &line, &raw_line, config)?;
                continue;
            }
        } else if line.starts_with("diff ") {
            painter.paint_buffered_minus_and_plus_lines();
            state = State::FileMeta;
            handled_file_meta_header_line_file_pair = None;
        } else if (state == State::FileMeta || source == Source::DiffUnified)
            && (line.starts_with("--- ")
                || line.starts_with("rename from ")
                || line.starts_with("copy from "))
        {
            let parsed_file_meta_line =
                parse::parse_file_meta_line(&line, source == Source::GitDiff);
            minus_file = parsed_file_meta_line.0;
            file_event = parsed_file_meta_line.1;

            if source == Source::DiffUnified {
                state = State::FileMeta;
                painter.set_syntax(parse::get_file_extension_from_marker_line(&line));
            } else {
                painter.set_syntax(parse::get_file_extension_from_file_meta_line_file_path(
                    &minus_file,
                ));
            }

            // In color_only mode, raw_line's structure shouldn't be changed.
            // So it needs to avoid fn handle_file_meta_header_line
            // (it connects the plus_file and minus_file),
            // and to call fn handle_generic_file_meta_header_line directly.
            if config.color_only {
                handle_generic_file_meta_header_line(&mut painter, &line, &raw_line, config)?;
                continue;
            }
        } else if (state == State::FileMeta || source == Source::DiffUnified)
            && (line.starts_with("+++ ")
                || line.starts_with("rename to ")
                || line.starts_with("copy to "))
        {
            let parsed_file_meta_line =
                parse::parse_file_meta_line(&line, source == Source::GitDiff);
            plus_file = parsed_file_meta_line.0;
            painter.set_syntax(parse::get_file_extension_from_file_meta_line_file_path(
                &plus_file,
            ));
            current_file_pair = Some((minus_file.clone(), plus_file.clone()));

            // In color_only mode, raw_line's structure shouldn't be changed.
            // So it needs to avoid fn handle_file_meta_header_line
            // (it connects the plus_file and minus_file),
            // and to call fn handle_generic_file_meta_header_line directly.
            if config.color_only {
                handle_generic_file_meta_header_line(&mut painter, &line, &raw_line, config)?;
                continue;
            }
            if should_handle(&State::FileMeta, config)
                && handled_file_meta_header_line_file_pair != current_file_pair
            {
                painter.emit()?;
                handle_file_meta_header_line(
                    &mut painter,
                    &minus_file,
                    &plus_file,
                    config,
                    &file_event,
                    source == Source::DiffUnified,
                )?;
                handled_file_meta_header_line_file_pair = current_file_pair
            }
        } else if line.starts_with("@@") {
            painter.paint_buffered_minus_and_plus_lines();
            state = State::HunkHeader;
            painter.set_highlighter();
            painter.emit()?;
            handle_hunk_header_line(&mut painter, &line, &raw_line, &plus_file, config)?;
            painter.set_highlighter();
            continue;
        } else if source == Source::DiffUnified && line.starts_with("Only in ")
            || line.starts_with("Submodule ")
            || line.starts_with("Binary files ")
        {
            // Additional FileMeta cases:
            //
            // 1. When comparing directories with diff -u, if filenames match between the
            //    directories, the files themselves will be compared. However, if an equivalent
            //    filename is not present, diff outputs a single line (Only in...) starting
            //    indicating that the file is present in only one of the directories.
            //
            // 2. Git diff emits lines describing submodule state such as "Submodule x/y/z contains
            //    untracked content"
            //
            // See https://github.com/dandavison/delta/issues/60#issuecomment-557485242 for a
            // proposal for more robust parsing logic.

            painter.paint_buffered_minus_and_plus_lines();
            state = State::FileMeta;
            if