Skip to main content

broot/display/
git_status_display.rs

1use {
2    super::CropWriter,
3    crate::{
4        errors::ProgramError,
5        git::TreeGitStatus,
6        skin::StyleMap,
7    },
8};
9
10pub struct GitStatusDisplay<'a, 's> {
11    status: &'a TreeGitStatus,
12    skin: &'s StyleMap,
13    show_branch: bool,
14    show_wide: bool,
15    show_stats: bool,
16    pub width: usize,
17}
18
19impl<'a, 's> GitStatusDisplay<'a, 's> {
20    pub fn from(
21        status: &'a TreeGitStatus,
22        skin: &'s StyleMap,
23        available_width: usize,
24    ) -> Self {
25        let mut show_branch = false;
26        let mut width = 0;
27        if let Some(branch) = &status.current_branch_name {
28            let branch_width = branch.chars().count();
29            if branch_width < available_width {
30                width += branch_width;
31                show_branch = true;
32            }
33        }
34        let mut show_stats = false;
35        let unstyled_stats = format!("+{}-{}", status.insertions, status.deletions);
36        let stats_width = unstyled_stats.len();
37        if width + stats_width < available_width {
38            width += stats_width;
39            show_stats = true;
40        }
41        let show_wide = width + 3 < available_width;
42        if show_wide {
43            width += 3; // difference between compact and wide format widths
44        }
45        Self {
46            status,
47            skin,
48            show_branch,
49            show_wide,
50            show_stats,
51            width,
52        }
53    }
54
55    pub fn write<W>(
56        &self,
57        cw: &mut CropWriter<W>,
58        selected: bool,
59    ) -> Result<(), ProgramError>
60    where
61        W: std::io::Write,
62    {
63        if self.show_branch {
64            cond_bg!(branch_style, self, selected, self.skin.git_branch);
65            if let Some(name) = &self.status.current_branch_name {
66                if self.show_wide {
67                    cw.queue_str(branch_style, " ᚜ ")?;
68                } else {
69                    cw.queue_char(branch_style, ' ')?;
70                }
71                cw.queue_str(branch_style, name)?;
72                cw.queue_char(branch_style, ' ')?;
73            }
74        }
75        if self.show_stats {
76            cond_bg!(insertions_style, self, selected, self.skin.git_insertions);
77            cw.queue_g_string(insertions_style, format!("+{}", self.status.insertions))?;
78            cond_bg!(deletions_style, self, selected, self.skin.git_deletions);
79            cw.queue_g_string(deletions_style, format!("-{}", self.status.deletions))?;
80        }
81        Ok(())
82    }
83}