gex 0.6.7

Git workflow improvement CLI tool inspired by Magit
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
//! Module relating to the Status display, including diffs of files.

use std::{
    borrow::Cow,
    fmt, fs,
    io::{stdout, Read, Write},
    process::{Command, Output, Stdio},
    sync::atomic::AtomicBool,
};

use anyhow::{anyhow, Context, Error, Result};
use crossterm::{
    cursor,
    style::{self, Attribute},
    terminal,
};
use git2::{ErrorCode::UnbornBranch, Repository};
use nom::{bytes::complete::take_until, IResult};

use crate::{
    config::{Config, Options, CONFIG},
    git_process,
    minibuffer::{MessageType, MiniBuffer},
    parse::{self, parse_hunk_new, parse_hunk_old},
    render::{self, Renderer, ResetAttributes, ResetColor},
};

pub static REFRESH_FLAG: AtomicBool = AtomicBool::new(false);

pub trait Expand {
    fn toggle_expand(&mut self);
    fn expanded(&self) -> bool;
}

#[derive(Debug)]
enum DiffType {
    Modified,
    Created,
    Untracked,
    Renamed,
    Deleted,
}

#[derive(Debug, Clone)]
pub struct Hunk {
    diff: String,
    expanded: bool,
}

impl fmt::Display for Hunk {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        use fmt::Write;
        let config = CONFIG.get().expect("config wasn't initialised");

        let mut lines = self.diff.lines();
        let Some(head) = lines.next() else {
            return Ok(());
        };
        let mut outbuf = format!(
            "{}{}{}",
            style::SetForegroundColor(config.colors.hunk_head),
            if self.expanded { "⌄" } else { "›" },
            head.replace(" @@", &format!(" @@{ResetAttributes}"))
        );

        if self.expanded {
            let ws_error_highlight = CONFIG
                .get()
                .expect("config is initialised at the start of the program")
                .options
                .ws_error_highlight;
            for line in lines {
                match line.chars().next() {
                    Some('+') => write!(
                        &mut outbuf,
                        "\r\n{}{}",
                        style::SetForegroundColor(config.colors.addition),
                        if ws_error_highlight.new {
                            format_trailing_whitespace(line, config)
                        } else {
                            Cow::Borrowed(line)
                        }
                    ),
                    Some('-') => write!(
                        &mut outbuf,
                        "\r\n{}{}",
                        style::SetForegroundColor(config.colors.deletion),
                        if ws_error_highlight.old {
                            format_trailing_whitespace(line, config)
                        } else {
                            Cow::Borrowed(line)
                        }
                    ),
                    Some(c) => write!(
                        &mut outbuf,
                        "\r\n{}{c}{}",
                        style::SetForegroundColor(config.colors.foreground),
                        if ws_error_highlight.context {
                            format_trailing_whitespace(&line[1..], config)
                        } else {
                            Cow::Borrowed(&line[1..])
                        }
                    ),
                    // I think this case never happens, but if it does, it just means the line was
                    // empty.
                    None => {
                        outbuf.push('\n');
                        Ok(())
                    }
                }?;
            }
        }
        write!(f, "{outbuf}")
    }
}

fn format_trailing_whitespace<'s>(s: &'s str, config: &'_ Config) -> Cow<'s, str> {
    let count_trailing_whitespace = s
        .bytes()
        .rev()
        .take_while(|c| c.is_ascii_whitespace())
        .count();
    if count_trailing_whitespace > 0 {
        Cow::Owned({
            let mut line = s.to_string();
            line.insert_str(
                line.len() - count_trailing_whitespace,
                &format!("{}", style::SetBackgroundColor(config.colors.error)),
            );
            line
        })
    } else {
        Cow::Borrowed(s)
    }
}

impl Hunk {
    pub const fn new(diff: String, expanded: bool) -> Self {
        Self { diff, expanded }
    }
}

impl Expand for Hunk {
    fn toggle_expand(&mut self) {
        self.expanded = !self.expanded;
    }

    fn expanded(&self) -> bool {
        self.expanded
    }
}

#[derive(Debug)]
pub struct FileDiff {
    path: String,
    expanded: bool,
    hunks: Vec<Hunk>,
    cursor: usize,
    kind: DiffType,
    // The implementation here involving this `selected` field is awful and hacky and I can't wait
    // to refactor it out.
    selected: bool,
}

impl render::Render for FileDiff {
    fn render(&self, f: &mut Renderer) -> fmt::Result {
        use fmt::Write;
        let config = CONFIG.get().expect("config wasn't initialised");
        write!(
            f,
            "\r{}{}{}{ResetAttributes}",
            if self.expanded { "⌄" } else { "›" },
            match self.kind {
                DiffType::Renamed => "[RENAME] ",
                DiffType::Deleted => "[DELETE] ",
                _ => "",
            },
            self.path,
        )?;
        if self.expanded {
            if self.hunks.is_empty() {
                if let Ok(file_content) = fs::read_to_string(&self.path) {
                    let ws_error_highlight = config.options.ws_error_highlight;

                    write!(f, "{ResetAttributes}")?;
                    for l in file_content.lines() {
                        write!(
                            f,
                            "\r\n{}+{l}",
                            style::SetForegroundColor(config.colors.addition),
                            l = if ws_error_highlight.new {
                                format_trailing_whitespace(l, config)
                            } else {
                                Cow::Borrowed(l)
                            }
                        )?;
                    }
                    if self.selected {
                        f.insert_item_end();
                    }
                }
            } else {
                for (i, hunk) in self.hunks.iter().enumerate() {
                    if self.selected && i + 1 == self.cursor {
                        f.insert_cursor();
                        write!(f, "{ResetAttributes}\r\n{}{hunk}", Attribute::Reverse)?;
                        f.insert_item_end();
                    } else {
                        write!(f, "{ResetAttributes}\r\n{hunk}")?;
                    }
                }
            }
        }
        Ok(())
    }
}

impl FileDiff {
    fn new(path: &str, kind: DiffType, expanded: bool, cursor: usize) -> Self {
        Self {
            path: path.to_string(),
            hunks: Vec::new(),
            selected: false,
            kind,
            expanded,
            cursor,
        }
    }

    /// Fails on the case that we are already on the first hunk
    fn up(&mut self) -> Result<(), ()> {
        self.cursor = self.cursor.checked_sub(1).ok_or(())?;
        Ok(())
    }

    /// Fails on the case that we are already on the final hunk
    const fn down(&mut self) -> Result<(), ()> {
        if self.cursor + 1 >= self.len() {
            return Err(());
        }
        self.cursor += 1;
        Ok(())
    }

    /// Move the cursor to the topmost element of this `FileDiff`.
    const fn cursor_first(&mut self) {
        self.cursor = 0;
    }

    /// Move the cursor to the last element of this `FileDiff`, if it is expanded.
    const fn cursor_last(&mut self) {
        self.cursor = self.len() - 1;
    }

    const fn len(&self) -> usize {
        if self.expanded {
            self.hunks.len() + 1
        } else {
            1
        }
    }
}

impl Expand for FileDiff {
    fn toggle_expand(&mut self) {
        self.expanded = !self.expanded;
    }

    fn expanded(&self) -> bool {
        self.expanded
    }
}

// Enum for `Status.stage_or_unstage`
#[derive(Clone, Copy)]
enum Stage {
    Add,
    Reset,
}

#[derive(Debug, Default)]
pub struct Status {
    pub branch: String,
    pub head: String,
    pub file_diffs: Vec<FileDiff>,
    pub count_untracked: usize,
    pub count_unstaged: usize,
    pub count_staged: usize,
    pub cursor: usize,
}

impl render::Render for Status {
    fn render(&self, f: &mut Renderer) -> Result<(), fmt::Error> {
        use fmt::Write;
        let config = CONFIG.get().expect("config wasn't initialised");
        // Display the current branch
        writeln!(
            f,
            "\rOn branch {}{}{}",
            Attribute::Bold,
            self.branch,
            ResetAttributes,
        )?;

        // Display most recent commit
        if !self.head.is_empty() {
            let mut head = self.head.split_whitespace();
            writeln!(
                f,
                "{}\r\n{}{}{}",
                Attribute::Dim,
                head.next().unwrap(), // !self.head.is_empty()
                ResetAttributes,
                head.fold(String::new(), |mut acc, w| {
                    let _ = write!(acc, " {w}");
                    acc
                })
            )?;
        }

        if self.file_diffs.is_empty() {
            write!(
                f,
                "\r\n{}nothing to commit, working tree clean{}",
                style::SetForegroundColor(config.colors.heading),
                style::SetForegroundColor(config.colors.foreground)
            )?;
            drop(stdout().flush());
        }

        for (index, file) in self.file_diffs.iter().enumerate() {
            if index == 0 && self.count_untracked != 0 {
                writeln!(
                    f,
                    "\r\n{}Untracked files{} {}({}){}",
                    style::SetForegroundColor(config.colors.heading),
                    ResetColor,
                    style::Attribute::Dim,
                    self.count_untracked,
                    ResetAttributes
                )?;
            } else if index == self.count_untracked && self.count_unstaged != 0 {
                writeln!(
                    f,
                    "\r\n{}Unstaged changes{} {}({}){}",
                    style::SetForegroundColor(config.colors.heading),
                    ResetColor,
                    style::Attribute::Dim,
                    self.count_unstaged,
                    ResetAttributes
                )?;
            } else if index == self.count_untracked + self.count_unstaged {
                writeln!(
                    f,
                    "\r\n{}Staged changes{} {}({}){}",
                    style::SetForegroundColor(config.colors.heading),
                    ResetColor,
                    style::Attribute::Dim,
                    self.count_staged,
                    ResetAttributes
                )?;
            }

            if file.cursor == 0 && self.cursor == index {
                f.insert_cursor();
                write!(f, "{}", Attribute::Reverse)?;
            }
            write!(f, "\r    ")?;
            file.render(f)?;
            writeln!(f, "{ResetAttributes}")?;
        }

        Ok(())
    }
}

impl Status {
    pub fn new(repo: &Repository, options: &Options) -> Result<Self> {
        let mut status = Self::default();
        status.fetch(repo, options)?;
        Ok(status)
    }

    pub fn fetch(&mut self, repo: &Repository, options: &Options) -> Result<()> {
        // Leaving ourselves a lot of room to optimise and tidy up in here :D
        let output = git_process(&["status"])?;

        let input =
            std::str::from_utf8(&output.stdout).context("malformed stdout from `git status`")?;

        // TODO: When head().is_branch() is false, we should do something different. For example,
        // use `branch: Option<String>` in `Status` and display something different when head
        // detached or on tag, etc.
        let branch = match repo.head() {
            Ok(head) => head
                .shorthand()
                .context("no name found for current HEAD")?
                .to_string(),
            Err(e) => {
                // git2 doesn't provide any API to get the name of an unborn branch, so we have to
                // read it directly :(
                if e.code() == UnbornBranch {
                    let mut head_path = repo.path().to_path_buf();
                    head_path.push("HEAD");
                    fs::read_to_string(&head_path)
                        .with_context(|| format!("couldn't read file: {}", head_path.display()))?
                        .lines()
                        .next()
                        .with_context(|| format!("no ref found in {}", head_path.display()))?
                        .trim()
                        .strip_prefix("ref: refs/heads/")
                        .with_context(|| {
                            format!("unexpected ref path found in {}", head_path.display())
                        })?
                        .to_string()
                } else {
                    return Err(Error::new(e)).context("failed to get name of current branch");
                }
            }
        };

        let mut untracked = Vec::new();
        let mut staged = Vec::new();
        let mut unstaged = Vec::new();

        let mut lines = input.lines();
        while let Some(line) = lines.next() {
            if line == "Untracked files:" {
                // (use "git add <file>..." to include in what will be committed)
                lines.next().context("strange `git status` output")?;
                for line in lines.by_ref() {
                    if line.is_empty() {
                        break;
                    }
                    let path = line.trim_start();
                    let previous_entry = self
                        .file_diffs
                        .iter()
                        .take(self.count_untracked)
                        .find(|f| f.path == path);
                    untracked.push(FileDiff::new(
                        path,
                        DiffType::Untracked,
                        previous_entry.map_or(options.auto_expand_files, |f| f.expanded),
                        previous_entry.map_or(0, |f| f.cursor),
                    ));
                }
            } else if line == "Changes not staged for commit:" {
                // (use "git add <file>..." to update what will be committed)
                // (use "git restore <file>..." to discard changes in working directory)
                lines.next().context("strange `git status` output")?;
                lines.next().context("strange `git status` output")?;
                for line in lines.by_ref() {
                    if line.is_empty() {
                        break;
                    }

                    let parse_result: IResult<&str, &str> = take_until("  ")(line.trim_start());
                    let (line, prefix) = parse_result
                        .map_err(|e| e.to_owned())
                        .context("strange diff output")?;

                    let path = line.trim_start();
                    let previous_entry = self
                        .file_diffs
                        .iter()
                        .skip(self.count_untracked)
                        .take(self.count_unstaged)
                        .find(|f| f.path == path);
                    unstaged.push(FileDiff::new(
                        path,
                        match prefix {
                            "" => DiffType::Untracked,        // untracked files
                            "new file:" => DiffType::Created, // staged new files
                            "modified:" => DiffType::Modified,
                            "renamed:" => DiffType::Renamed,
                            "deleted:" => DiffType::Deleted,
                            _ => {
                                return Err(anyhow!(
                                    "unknown file prefix in `git status` output: `{prefix}`"
                                ))
                            }
                        },
                        previous_entry.map_or(options.auto_expand_files, |f| f.expanded),
                        previous_entry.map_or(0, |f| f.cursor),
                    ));
                }
            } else if line == "Changes to be committed:" {
                // (use "git restore --staged <file>..." to unstage)
                lines.next().context("strange `git status` output")?;
                for line in lines.by_ref() {
                    if line.is_empty() {
                        break;
                    }

                    let parse_result: IResult<&str, &str> = take_until("  ")(line.trim_start());
                    let (line, prefix) = parse_result
                        .map_err(|e| e.to_owned())
                        .context("strange `git status` output")?;

                    let path = line.trim_start();
                    let previous_entry = self
                        .file_diffs
                        .iter()
                        .skip(self.count_untracked + self.count_unstaged)
                        .find(|f| f.path == path);
                    staged.push(FileDiff::new(
                        path,
                        match prefix {
                            "" => DiffType::Untracked,        // untracked files
                            "new file:" => DiffType::Created, // staged new files
                            "modified:" => DiffType::Modified,
                            "renamed:" => DiffType::Renamed,
                            "deleted:" => DiffType::Deleted,
                            _ => {
                                return Err(anyhow!(
                                    "unknown file prefix in `git status` output: `{prefix}`"
                                ))
                            }
                        },
                        previous_entry.map_or(options.auto_expand_files, |f| f.expanded),
                        previous_entry.map_or(0, |f| f.cursor),
                    ));
                }
            }
        }

        // Get the diff information for unstaged changes
        let diff = git_process(&["diff", "--no-ext-diff", "--default-prefix"])?;
        Self::populate_diffs(&mut unstaged, &self.file_diffs, &diff, options)
            .context("failed to populate unstaged file diffs")?;

        // Get the diff information for staged changes
        let diff = git_process(&["diff", "--cached", "--no-ext-diff", "--default-prefix"])?;
        Self::populate_diffs(&mut staged, &self.file_diffs, &diff, options)
            .context("failed to populate unstaged file diffs")?;

        self.branch = branch;
        self.head = std::str::from_utf8(
            &git_process(&["log", "HEAD", "--pretty=format:%h %s", "-n", "1"])?.stdout,
        )
        .context("invalid utf8 from `git log`")?
        .to_string();
        self.count_untracked = untracked.len();
        self.count_staged = staged.len();
        self.count_unstaged = unstaged.len();

        self.file_diffs = untracked;
        self.file_diffs.append(&mut unstaged);
        self.file_diffs.append(&mut staged);

        for file_diff in self.file_diffs.iter_mut().filter(|f| f.cursor >= f.len()) {
            file_diff.cursor = file_diff.len() - 1;
        }

        if !self.file_diffs.is_empty() && self.cursor >= self.file_diffs.len() {
            self.cursor = self.file_diffs.len() - 1;
        }

        if let Some(file_diff) = self.file_diffs.get_mut(self.cursor) {
            file_diff.selected = true;
        }

        Ok(())
    }

    /// Takes a vec `file_diffs` containing `FileDiff` elements that have only the name populated,
    /// and populates their hunks based on the parsing of `diff`, and the `prev_file_diffs`.
    fn populate_diffs(
        file_diffs: &mut Vec<FileDiff>,
        prev_file_diffs: &[FileDiff],
        diff: &Output,
        options: &Options,
    ) -> Result<()> {
        let diff = std::str::from_utf8(&diff.stdout).context("malformed stdout from `git diff`")?;
        let hunks = parse::parse_diff(diff)?;
        for file in file_diffs {
            if let Some(hunks) = hunks.get(file.path.as_str()) {
                // Get all the diffs entries of this file from the previous iteration.
                let previous_file_entries = prev_file_diffs.iter().filter(|f| f.path == file.path);
                file.hunks = hunks
                    .iter()
                    .map(|hunk| {
                        let expanded = previous_file_entries
                            .clone()
                            .find_map(|f| {
                                f.hunks.iter().find(|h| {
                                    let h_header =
                                        h.diff.lines().next().expect("hunk should never be empty");
                                    let hunk_header =
                                        hunk.lines().next().expect("hunk should never be empty");
                                    (parse_hunk_new(h_header).unwrap_or_else(|e| panic!("{e:?}"))
                                        == parse_hunk_new(hunk_header)
                                            .unwrap_or_else(|e| panic!("{e:?}")))
                                        || (parse_hunk_old(h_header)
                                            .unwrap_or_else(|e| panic!("{e:?}"))
                                            == parse_hunk_old(hunk_header)
                                                .unwrap_or_else(|e| panic!("{e:?}")))
                                })
                            })
                            .map_or(options.auto_expand_hunks, |h| h.expanded);

                        Hunk::new(hunk.clone(), expanded)
                    })
                    .collect();
            }
        }
        Ok(())
    }

    fn stage_or_unstage(&mut self, command: Stage) -> Result<()> {
        if self.file_diffs.is_empty() {
            return Ok(());
        }

        let file = self
            .file_diffs
            .get_mut(self.cursor)
            .context("cursor is at invalid position")?;
        file.selected = false;

        match file.cursor {
            0 => {
                let args = match command {
                    Stage::Add => vec!["add", &file.path],
                    Stage::Reset => match file.kind {
                        DiffType::Deleted => vec!["reset", "HEAD", &file.path],
                        _ => vec!["reset", &file.path],
                    },
                };
                git_process(&args)?;
            }
            i => {
                let mut patch = Command::new("git")
                    .args(match command {
                        Stage::Add => ["add", "-p", &file.path],
                        Stage::Reset => ["reset", "-p", &file.path],
                    })
                    .stdin(Stdio::piped())
                    .stdout(Stdio::null())
                    .stderr(Stdio::piped())
                    .spawn()
                    .context("failed to spawn interactive git process")?;

                let mut stdin = patch.stdin.take().context("failed to open child stdin")?;

                let mut bufs = vec![b"n\n"; i - 1];
                bufs.push(b"y\n");

                std::thread::spawn(move || {
                    for buf in bufs {
                        stdin.write_all(buf).context("failed to patch hunk")?;
                    }
                    Ok::<_, Error>(())
                })
                .join()
                .unwrap()
                .context("failed to patch hunk")?;

                let mut stderr_buf = String::new();
                patch
                    .stderr
                    // If I understand correctly, reading to EOF should have the added effect
                    // waiting on the child process to finish.
                    .map(|mut stderr| stderr.read_to_string(&mut stderr_buf))
                    .context("failed to read stderr of child process")??;
                MiniBuffer::push(&stderr_buf, MessageType::Error);
            }
        }

        self.file_diffs
            .get_mut(self.cursor)
            .context("cursor is at invalid position")?
            .selected = true;
        Ok(())
    }

    pub fn stage(&mut self) -> Result<()> {
        self.stage_or_unstage(Stage::Add)
    }

    pub fn unstage(&mut self) -> Result<()> {
        self.stage_or_unstage(Stage::Reset)
    }

    /// Toggles expand on the selected diff item.
    pub fn expand(&mut self) -> Result<()> {
        if self.file_diffs.is_empty() {
            return Ok(());
        }

        let file = self
            .file_diffs
            .get_mut(self.cursor)
            .context("cursor is at invalid position")?;

        if file.cursor == 0 {
            file.toggle_expand();
        } else {
            file.hunks[file.cursor - 1].toggle_expand();
        }

        Ok(())
    }

    /// Open the current file in the configured editor. Return when the edit finishes.
    pub fn open_editor(&self) -> Result<()> {
        let editor = &crate::config!().options.editor;
        let file = &self
            .file_diffs
            .get(self.cursor)
            .expect("cursor is at invalid position");

        let row = match file.cursor {
            0 => 1,
            n => parse_hunk_new(&file.hunks[n - 1].diff)?
                .split_once(',')
                .context("strange hunk header")?
                .0
                .parse()
                .context("couldn't get starting line of hunk")?,
        };
        // If your editor isn't supported yet for opening at a specific line, please add the
        // implementation below!
        let args = match (editor.as_str(), row) {
            (_, 1) => vec![file.path.clone()],
            ("nvim" | "vim" | "vi" | "nano", _) => vec![format!("+{row}"), file.path.clone()],
            ("hx", _) => vec![format!("{}:{row}", &file.path)],
            _ => vec![file.path.clone()],
        };

        crossterm::execute!(stdout(), terminal::LeaveAlternateScreen)
            .expect("failed to leave alternate screen");
        Command::new(editor)
            .args(&args)
            .stdout(Stdio::inherit())
            .stdin(Stdio::inherit())
            .output()
            .with_context(|| format!("failed to open editor ({editor})"))?;
        crossterm::execute!(stdout(), terminal::EnterAlternateScreen, cursor::Hide)
            .expect("failed to enter alternate screen");
        Ok(())
    }

    /// Jump to previous file.
    pub fn file_up(&mut self) -> Result<()> {
        if self.file_diffs.is_empty() {
            return Ok(());
        }
        let file = self
            .file_diffs
            .get_mut(self.cursor)
            .context("cursor is at invalid position")?;
        if file.cursor == 0 {
            file.selected = false;
            self.cursor = self.cursor.saturating_sub(1);
            let new_file = self
                .file_diffs
                .get_mut(self.cursor)
                .expect("self.cursor >= 0, !self.file_diffs.is_empty");
            new_file.selected = true;
            new_file.cursor = 0;
        } else {
            file.cursor = 0;
        }
        Ok(())
    }

    /// Jump to next file.
    pub fn file_down(&mut self) -> Result<()> {
        if self.cursor < self.file_diffs.len() - 1 {
            self.file_diffs
                .get_mut(self.cursor)
                .context("cursor is at invalid position")?
                .selected = false;
            self.cursor += 1;
            let new_file = self
                .file_diffs
                .get_mut(self.cursor)
                .expect("self.cursor < self.file_diffs.len");
            new_file.selected = true;
            new_file.cursor = 0;
        }
        Ok(())
    }

    /// Move the cursor up one
    pub fn up(&mut self) -> Result<()> {
        if self.file_diffs.is_empty() {
            return Ok(());
        }

        let file = self
            .file_diffs
            .get_mut(self.cursor)
            .context("cursor is at invalid position")?;

        if file.up().is_err() {
            match self.cursor.checked_sub(1) {
                Some(v) => {
                    self.cursor = v;
                    file.selected = false;
                    let new_file = self
                        .file_diffs
                        .get_mut(self.cursor)
                        .context("cursor at invalid position")?;
                    new_file.selected = true;
                    if new_file.expanded() {
                        new_file.cursor_last();
                    }
                }
                None => self.cursor = 0,
            }
        }

        Ok(())
    }

    /// Move the cursor down one
    pub fn down(&mut self) -> Result<()> {
        if self.file_diffs.is_empty() {
            return Ok(());
        }

        let count_file_diffs = self.file_diffs.len();
        let file = self
            .file_diffs
            .get_mut(self.cursor)
            .context("cursor is at invalid position")?;

        if file.down().is_err() {
            if self.cursor + 1 >= count_file_diffs {
                return Ok(());
            }

            self.cursor += 1;
            file.selected = false;
            let new_file = self
                .file_diffs
                .get_mut(self.cursor)
                .context("cursor at invalid position")?;
            new_file.selected = true;
            if new_file.expanded() {
                new_file.cursor_first();
            }
        }

        Ok(())
    }

    /// Move the cursor to the first element.
    pub fn cursor_first(&mut self) -> Result<()> {
        if self.file_diffs.is_empty() {
            return Ok(());
        }

        self.file_diffs
            .get_mut(self.cursor)
            .context("cursor is at invalid position")?
            .selected = false;
        self.cursor = 0;
        let new_file = self
            .file_diffs
            .get_mut(self.cursor)
            .expect("0th element must exist, !self.file_diffs.is_empty()");
        new_file.cursor_first();
        new_file.selected = true;
        Ok(())
    }

    /// Move the cursor to the last element.
    pub fn cursor_last(&mut self) -> Result<()> {
        if self.file_diffs.is_empty() {
            return Ok(());
        }

        self.file_diffs
            .get_mut(self.cursor)
            .context("cursor is at invalid position")?
            .selected = false;
        self.cursor = self.file_diffs.len() - 1;
        let new_file = self
            .file_diffs
            .get_mut(self.cursor)
            .expect("cursor at `len() - 1`th pos of non-empty diffs");
        new_file.cursor_last();
        new_file.selected = true;
        Ok(())
    }
}