scm-diff-editor 0.10.1

UI component to interactively select changes to include in a commit.
Documentation
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
use std::borrow::Cow;
use std::path::PathBuf;

use scm_record::helpers::make_binary_description;
use scm_record::{ChangeType, File, Section, SectionChangedLine};
use tracing::warn;

use super::{Error, FileContents, FileInfo, Filesystem};

fn make_section_changed_lines(
    contents: &str,
    change_type: ChangeType,
) -> Vec<SectionChangedLine<'static>> {
    contents
        .split_inclusive('\n')
        .map(|line| SectionChangedLine {
            is_checked: false,
            change_type,
            line: Cow::Owned(line.to_owned()),
        })
        .collect()
}

pub fn create_file(
    filesystem: &dyn Filesystem,
    left_path: PathBuf,
    left_display_path: PathBuf,
    right_path: PathBuf,
    right_display_path: PathBuf,
) -> Result<File<'static>, Error> {
    let FileInfo {
        file_mode: left_file_mode,
        contents: left_contents,
    } = filesystem.read_file_info(&left_path)?;
    let FileInfo {
        file_mode: right_file_mode,
        contents: right_contents,
    } = filesystem.read_file_info(&right_path)?;
    let mut sections = Vec::new();

    if left_file_mode != right_file_mode {
        sections.push(Section::FileMode {
            is_checked: false,
            mode: right_file_mode,
        });
    }

    match (left_contents, right_contents) {
        (FileContents::Absent, FileContents::Absent) => {}
        (
            FileContents::Absent,
            FileContents::Text {
                contents,
                hash: _,
                num_bytes: _,
            },
        ) => sections.push(Section::Changed {
            lines: make_section_changed_lines(&contents, ChangeType::Added),
        }),

        (FileContents::Absent, FileContents::Binary { hash, num_bytes }) => {
            sections.push(Section::Binary {
                is_checked: false,
                old_description: None,
                new_description: Some(Cow::Owned(make_binary_description(&hash, num_bytes))),
            })
        }

        (
            FileContents::Text {
                contents,
                hash: _,
                num_bytes: _,
            },
            FileContents::Absent,
        ) => sections.push(Section::Changed {
            lines: make_section_changed_lines(&contents, ChangeType::Removed),
        }),

        (
            FileContents::Text {
                contents: old_contents,
                hash: _,
                num_bytes: _,
            },
            FileContents::Text {
                contents: new_contents,
                hash: _,
                num_bytes: _,
            },
        ) => {
            sections.extend(create_diff(&old_contents, &new_contents));
        }

        (
            FileContents::Text {
                contents: _,
                hash: old_hash,
                num_bytes: old_num_bytes,
            }
            | FileContents::Binary {
                hash: old_hash,
                num_bytes: old_num_bytes,
            },
            FileContents::Text {
                contents: _,
                hash: new_hash,
                num_bytes: new_num_bytes,
            }
            | FileContents::Binary {
                hash: new_hash,
                num_bytes: new_num_bytes,
            },
        ) => sections.push(Section::Binary {
            is_checked: false,
            old_description: Some(Cow::Owned(make_binary_description(
                &old_hash,
                old_num_bytes,
            ))),
            new_description: Some(Cow::Owned(make_binary_description(
                &new_hash,
                new_num_bytes,
            ))),
        }),

        (FileContents::Binary { hash, num_bytes }, FileContents::Absent) => {
            sections.push(Section::Binary {
                is_checked: false,
                old_description: Some(Cow::Owned(make_binary_description(&hash, num_bytes))),
                new_description: None,
            })
        }
    }

    Ok(File {
        old_path: if left_display_path != right_display_path {
            Some(Cow::Owned(left_display_path))
        } else {
            None
        },
        path: Cow::Owned(right_display_path),
        file_mode: left_file_mode,
        sections,
    })
}

pub fn create_merge_file(
    filesystem: &dyn Filesystem,
    base_path: PathBuf,
    left_path: PathBuf,
    right_path: PathBuf,
    output_path: PathBuf,
) -> Result<File<'static>, Error> {
    let FileInfo {
        file_mode: left_file_mode,
        contents: left_contents,
    } = filesystem.read_file_info(&left_path)?;
    let FileInfo {
        file_mode: _,
        contents: right_contents,
    } = filesystem.read_file_info(&right_path)?;
    let FileInfo {
        file_mode: _,
        contents: base_contents,
    } = filesystem.read_file_info(&base_path)?;

    let (base_contents, left_contents, right_contents) =
        match (base_contents, left_contents, right_contents) {
            (FileContents::Absent, _, _) => {
                return Err(Error::MissingMergeFile { path: base_path })
            }
            (_, FileContents::Absent, _) => {
                return Err(Error::MissingMergeFile { path: left_path })
            }
            (_, _, FileContents::Absent) => {
                return Err(Error::MissingMergeFile { path: right_path })
            }
            (FileContents::Binary { .. }, _, _) => {
                return Err(Error::BinaryMergeFile { path: base_path })
            }
            (_, FileContents::Binary { .. }, _) => {
                return Err(Error::BinaryMergeFile { path: left_path })
            }
            (_, _, FileContents::Binary { .. }) => {
                return Err(Error::BinaryMergeFile { path: right_path })
            }
            (
                FileContents::Text {
                    contents: base_contents,
                    hash: _,
                    num_bytes: _,
                },
                FileContents::Text {
                    contents: left_contents,
                    hash: _,
                    num_bytes: _,
                },
                FileContents::Text {
                    contents: right_contents,
                    hash: _,
                    num_bytes: _,
                },
            ) => (base_contents, left_contents, right_contents),
        };

    let sections = create_merge(&base_contents, &left_contents, &right_contents);
    Ok(File {
        old_path: Some(Cow::Owned(base_path)),
        path: Cow::Owned(output_path),
        file_mode: left_file_mode,
        sections,
    })
}

fn create_diff(old_contents: &str, new_contents: &str) -> Vec<Section<'static>> {
    let patch = {
        // Set the context length to the maximum number of lines in either file,
        // because we will handle abbreviating context ourselves.
        let max_lines = old_contents
            .lines()
            .count()
            .max(new_contents.lines().count());
        let mut diff_options = diffy::DiffOptions::new();
        diff_options.set_context_len(max_lines);
        diff_options.create_patch(old_contents, new_contents)
    };

    let mut sections = Vec::new();
    for hunk in patch.hunks() {
        sections.extend(hunk.lines().iter().fold(Vec::new(), |mut acc, line| {
            match line {
                diffy::Line::Context(line) => match acc.last_mut() {
                    Some(Section::Unchanged { lines }) => {
                        lines.push(Cow::Owned((*line).to_owned()));
                    }
                    _ => {
                        acc.push(Section::Unchanged {
                            lines: vec![Cow::Owned((*line).to_owned())],
                        });
                    }
                },
                diffy::Line::Delete(line) => {
                    let line = SectionChangedLine {
                        is_checked: false,
                        change_type: ChangeType::Removed,
                        line: Cow::Owned((*line).to_owned()),
                    };
                    match acc.last_mut() {
                        Some(Section::Changed { lines }) => {
                            lines.push(line);
                        }
                        _ => {
                            acc.push(Section::Changed { lines: vec![line] });
                        }
                    }
                }
                diffy::Line::Insert(line) => {
                    let line = SectionChangedLine {
                        is_checked: false,
                        change_type: ChangeType::Added,
                        line: Cow::Owned((*line).to_owned()),
                    };
                    match acc.last_mut() {
                        Some(Section::Changed { lines }) => {
                            lines.push(line);
                        }
                        _ => {
                            acc.push(Section::Changed { lines: vec![line] });
                        }
                    }
                }
            }
            acc
        }));
    }
    sections
}

fn make_conflict_markers(base: &str, left: &str, right: &str) -> (String, String, String, String) {
    let all = [base, left, right].concat();
    let left_char = "<";
    let base_start_char = "|";
    let base_end_char = "=";
    let right_char = ">";
    let mut len = 7;
    loop {
        let left_marker = left_char.repeat(len);
        let base_start_marker = base_start_char.repeat(len);
        let base_end_marker = base_end_char.repeat(len);
        let right_marker = right_char.repeat(len);
        if !all.contains(&left_marker)
            && !all.contains(&base_start_marker)
            && !all.contains(&base_end_marker)
            && !all.contains(&right_marker)
        {
            return (
                left_marker,
                base_start_marker,
                base_end_marker,
                right_marker,
            );
        }
        len += 1;
    }
}

fn create_merge(
    base_contents: &str,
    left_contents: &str,
    right_contents: &str,
) -> Vec<Section<'static>> {
    let (left_marker, base_start_marker, base_end_marker, right_marker) =
        make_conflict_markers(base_contents, left_contents, right_contents);

    let mut merge_options = diffy::MergeOptions::new();
    merge_options.set_conflict_marker_length(right_marker.len());
    merge_options.set_conflict_style(diffy::ConflictStyle::Diff3);
    let merge = merge_options.merge(base_contents, left_contents, right_contents);
    let conflicted_text = match merge {
        Ok(_) => return Default::default(),
        Err(conflicted_text) => conflicted_text,
    };

    enum MarkerType {
        Left,
        BaseStart,
        BaseEnd,
        Right,
    }
    #[derive(Debug)]
    enum State<'a> {
        Empty,
        Unchanged {
            lines: Vec<Cow<'a, str>>,
        },
        Left {
            left_lines: Vec<Cow<'a, str>>,
        },
        Base {
            left_lines: Vec<Cow<'a, str>>,
            base_lines: Vec<Cow<'a, str>>,
        },
        Right {
            left_lines: Vec<Cow<'a, str>>,
            base_lines: Vec<Cow<'a, str>>,
            right_lines: Vec<Cow<'a, str>>,
        },
    }

    let mut sections = vec![];
    let mut state = State::Empty;
    for line in conflicted_text.split_inclusive('\n') {
        let marker_type = if line.starts_with(&left_marker) {
            Some(MarkerType::Left)
        } else if line.starts_with(&base_start_marker) {
            Some(MarkerType::BaseStart)
        } else if line.starts_with(&base_end_marker) {
            Some(MarkerType::BaseEnd)
        } else if line.starts_with(&right_marker) {
            Some(MarkerType::Right)
        } else {
            None
        };

        let line = Cow::Owned(line.to_owned());
        let (new_state, new_section) = match (state, marker_type) {
            (State::Empty, Some(MarkerType::Left)) => {
                let new_state = State::Left {
                    left_lines: Default::default(),
                };
                (new_state, None)
            }
            (State::Empty, _) => {
                let new_state = State::Unchanged { lines: vec![line] };
                (new_state, None)
            }

            (State::Unchanged { lines }, Some(MarkerType::Left)) => {
                let new_state = State::Left {
                    left_lines: Default::default(),
                };
                let new_section = Section::Unchanged { lines };
                (new_state, Some(new_section))
            }
            (State::Unchanged { mut lines }, _) => {
                lines.push(line);
                let new_state = State::Unchanged { lines };
                (new_state, None)
            }

            (State::Left { left_lines }, Some(MarkerType::BaseStart)) => {
                let new_state = State::Base {
                    left_lines,
                    base_lines: Default::default(),
                };
                (new_state, None)
            }
            (State::Left { mut left_lines }, _) => {
                left_lines.push(line);
                let new_state = State::Left { left_lines };
                (new_state, None)
            }

            (
                State::Base {
                    left_lines,
                    base_lines,
                },
                Some(MarkerType::BaseEnd),
            ) => {
                let new_state = State::Right {
                    left_lines,
                    base_lines,
                    right_lines: Default::default(),
                };
                (new_state, None)
            }
            (
                State::Base {
                    left_lines,
                    mut base_lines,
                },
                _,
            ) => {
                base_lines.push(line);
                let new_state = State::Base {
                    left_lines,
                    base_lines,
                };
                (new_state, None)
            }

            (
                State::Right {
                    left_lines,
                    base_lines,
                    right_lines,
                },
                Some(MarkerType::Right),
            ) => {
                let new_state = State::Empty;
                let new_section = Section::Changed {
                    lines: left_lines
                        .into_iter()
                        .map(|line| (line, ChangeType::Added))
                        .chain(
                            base_lines
                                .into_iter()
                                .map(|line| (line, ChangeType::Removed)),
                        )
                        .chain(
                            right_lines
                                .into_iter()
                                .map(|line| (line, ChangeType::Added)),
                        )
                        .map(|(line, change_type)| SectionChangedLine {
                            is_checked: false,
                            change_type,
                            line,
                        })
                        .collect(),
                };
                (new_state, Some(new_section))
            }
            (
                State::Right {
                    left_lines,
                    base_lines,
                    mut right_lines,
                },
                _,
            ) => {
                right_lines.push(line);
                let new_state = State::Right {
                    left_lines,
                    base_lines,
                    right_lines,
                };
                (new_state, None)
            }
        };

        state = new_state;
        if let Some(new_section) = new_section {
            sections.push(new_section);
        }
    }

    match state {
        State::Empty => {}
        State::Unchanged { lines } => {
            sections.push(Section::Unchanged { lines });
        }
        state @ (State::Left { .. } | State::Base { .. } | State::Right { .. }) => {
            warn!(?state, "Diff section not terminated");
        }
    }

    sections
}