Skip to main content

lx_cli/
git.rs

1use std::collections::{HashMap, HashSet};
2use std::ffi::OsStr;
3use std::io;
4use std::os::unix::ffi::OsStrExt;
5use std::path::{Path, PathBuf};
6use std::process::Command;
7
8/// A single state for an entry or directory summary.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum GitStatus {
11    Clean,
12    Modified,
13    Staged,
14    Untracked,
15    Conflict,
16    Mixed,
17}
18
19impl GitStatus {
20    pub(crate) fn badge(self, icons_enabled: bool) -> &'static str {
21        let (letter, icon) = match self {
22            Self::Clean => ("-", "-"),
23            Self::Modified => ("M", "\u{f040}"),  // Pencil
24            Self::Staged => ("S", "\u{f058}"),    // Circled check
25            Self::Untracked => ("?", "\u{f059}"), // Circled question
26            Self::Conflict => ("!", "\u{f071}"),  // Warning
27            Self::Mixed => ("*", "\u{f074}"),     // Shuffle
28        };
29        if icons_enabled { icon } else { letter }
30    }
31
32    pub(crate) fn style_role(self) -> &'static str {
33        match self {
34            Self::Clean => "git.clean",
35            Self::Modified => "git.modified",
36            Self::Staged => "git.staged",
37            Self::Untracked => "git.untracked",
38            Self::Conflict => "git.conflict",
39            Self::Mixed => "git.mixed",
40        }
41    }
42
43    fn from_codes(codes: [u8; 2]) -> Self {
44        match &codes {
45            b"  " => Self::Clean,
46            b"??" => Self::Untracked,
47            b"DD" | b"AU" | b"UD" | b"UA" | b"DU" | b"AA" | b"UU" => Self::Conflict,
48            [b' ', _] => Self::Modified,
49            [_, b' '] => Self::Staged,
50            _ => Self::Mixed,
51        }
52    }
53
54    fn merge(&mut self, other: Self) {
55        *self = match (*self, other) {
56            (Self::Conflict, _) | (_, Self::Conflict) => Self::Conflict,
57            (Self::Clean, status) | (status, Self::Clean) => status,
58            (current, incoming) if current == incoming => current,
59            _ => Self::Mixed,
60        };
61    }
62}
63
64/// One status snapshot for the repository containing the listing target.
65#[derive(Debug)]
66pub struct GitRepository {
67    statuses: HashMap<PathBuf, GitStatus>,
68    ignored: HashSet<PathBuf>,
69}
70
71impl GitRepository {
72    /// Returns `None` outside a working tree; optionally collects ignored paths.
73    pub fn load(target: &Path, include_ignored: bool) -> io::Result<Option<Self>> {
74        let directory = if target.is_dir() && !target.is_symlink() {
75            target
76        } else {
77            target
78                .parent()
79                .filter(|parent| !parent.as_os_str().is_empty())
80                .unwrap_or(Path::new("."))
81        };
82        let directory = directory.canonicalize()?;
83        let Some(root) = directory
84            .ancestors()
85            .find(|path| path.join(".git").exists())
86        else {
87            return Ok(None);
88        };
89
90        let mut command = Command::new("git");
91        command
92            .args(["--no-optional-locks", "--literal-pathspecs", "-C"])
93            .arg(root)
94            .args(["status", "--porcelain=v1", "-z", "--untracked-files=all"]);
95        if include_ignored {
96            command.arg("--ignored=matching");
97        }
98        // Statuses and summaries only ever describe paths beneath the listed directory, so
99        // there is no need for Git to scan the rest of the repository.
100        let scope = directory.strip_prefix(root).unwrap_or(Path::new(""));
101        if !scope.as_os_str().is_empty() {
102            command.arg("--").arg(scope);
103        }
104        let output = command.output()?;
105        if !output.status.success() {
106            return Err(io::Error::other(
107                String::from_utf8_lossy(&output.stderr).trim().to_string(),
108            ));
109        }
110        let mut repository = Self::from_porcelain(root, &output.stdout)?;
111        if include_ignored {
112            repository.ignored.insert(root.join(".git"));
113        }
114        Ok(Some(repository))
115    }
116
117    /// Annotates entries returned by `read_target` with this repository's status.
118    pub fn annotate(&self, target: &Path, entries: &mut [crate::FileEntry]) -> io::Result<()> {
119        let directory = if target.is_dir() && !target.is_symlink() {
120            target
121        } else {
122            target
123                .parent()
124                .filter(|parent| !parent.as_os_str().is_empty())
125                .unwrap_or(Path::new("."))
126        }
127        .canonicalize()?;
128        for entry in entries {
129            entry.git_status = Some(self.status(&directory.join(&entry.path)));
130        }
131        Ok(())
132    }
133
134    pub(crate) fn status(&self, path: &Path) -> GitStatus {
135        self.statuses.get(path).copied().unwrap_or(GitStatus::Clean)
136    }
137
138    pub(crate) fn is_ignored(&self, path: &Path) -> bool {
139        path.ancestors()
140            .any(|ancestor| self.ignored.contains(ancestor))
141    }
142
143    fn from_porcelain(root: &Path, output: &[u8]) -> io::Result<Self> {
144        let mut repository = Self {
145            statuses: HashMap::new(),
146            ignored: HashSet::new(),
147        };
148        let mut records = output.split(|byte| *byte == 0);
149        while let Some(record) = records.next() {
150            if record.is_empty() {
151                continue;
152            }
153            if record.len() < 4 || record[2] != b' ' {
154                return Err(io::Error::new(
155                    io::ErrorKind::InvalidData,
156                    "invalid Git status record",
157                ));
158            }
159            let codes = [record[0], record[1]];
160            let path = root.join(OsStr::from_bytes(&record[3..]));
161            if codes == *b"!!" {
162                repository.ignored.insert(path);
163                continue;
164            }
165            let status = GitStatus::from_codes(codes);
166            repository.record_path(root, &path, status);
167
168            if codes.iter().any(|code| matches!(code, b'R' | b'C')) {
169                let original = records
170                    .next()
171                    .filter(|record| !record.is_empty())
172                    .ok_or_else(|| {
173                        io::Error::new(io::ErrorKind::InvalidData, "missing Git rename source")
174                    })?;
175                if codes.contains(&b'R') {
176                    let deleted = GitStatus::from_codes(
177                        codes.map(|code| if code == b'R' { b'D' } else { b' ' }),
178                    );
179                    repository.record_path(root, &root.join(OsStr::from_bytes(original)), deleted);
180                }
181            }
182        }
183        Ok(repository)
184    }
185
186    fn record_path(&mut self, root: &Path, path: &Path, status: GitStatus) {
187        self.statuses.insert(path.to_path_buf(), status);
188        for ancestor in path
189            .ancestors()
190            .skip(1)
191            .take_while(|ancestor| ancestor.starts_with(root))
192        {
193            self.statuses
194                .entry(ancestor.to_path_buf())
195                .or_insert(GitStatus::Clean)
196                .merge(status);
197        }
198    }
199}
200
201#[cfg(test)]
202mod tests {
203    use super::{GitRepository, GitStatus};
204    use std::os::unix::ffi::OsStrExt;
205    use std::path::Path;
206
207    #[test]
208    fn parses_paths_and_aggregates_changes_without_marking_clean_siblings() {
209        let root = Path::new("/repo");
210        let repository = GitRepository::from_porcelain(root, b" M src/space name\0A  src/added\0?? src/new/nested/file\0R  destination/renamed\0source/old\0UU conflict\0 M invalid-\xff\0D  deleted/staged\0 D deleted/unstaged\0!! cache/\0!! ignored-\xff\0").expect("parse status");
211        assert!(repository.is_ignored(Path::new("/repo/cache/nested/file")));
212        assert!(!repository.is_ignored(Path::new("/repo/cache-other")));
213        assert!(repository.is_ignored(&root.join(std::ffi::OsStr::from_bytes(b"ignored-\xff"))));
214        assert_eq!(
215            repository.status(Path::new("/repo/cache")),
216            GitStatus::Clean
217        );
218        assert_eq!(
219            repository.status(Path::new("/repo/src/space name")),
220            GitStatus::Modified
221        );
222        assert_eq!(repository.status(Path::new("/repo/src")), GitStatus::Mixed);
223        assert_eq!(
224            repository.status(Path::new("/repo/src/clean")),
225            GitStatus::Clean
226        );
227        assert_eq!(
228            repository.status(Path::new("/repo/src/new/nested/file")),
229            GitStatus::Untracked
230        );
231        assert_eq!(
232            repository.status(Path::new("/repo/destination/renamed")),
233            GitStatus::Staged
234        );
235        assert_eq!(
236            repository.status(Path::new("/repo/source")),
237            GitStatus::Staged
238        );
239        assert_eq!(repository.status(root), GitStatus::Conflict);
240        assert_eq!(
241            repository.status(Path::new("/repo/deleted")),
242            GitStatus::Mixed
243        );
244        assert_eq!(
245            repository.status(&root.join(std::ffi::OsStr::from_bytes(b"invalid-\xff"))),
246            GitStatus::Modified
247        );
248    }
249}