git_prole/git/
status.rs

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
use std::fmt::Debug;
use std::fmt::Display;
use std::iter;
use std::str::FromStr;

use camino::Utf8PathBuf;
use command_error::CommandExt;
use command_error::OutputContext;
use miette::miette;
use tracing::instrument;
use utf8_command::Utf8Output;
use winnow::combinator::eof;
use winnow::combinator::opt;
use winnow::combinator::repeat_till;
use winnow::token::one_of;
use winnow::PResult;
use winnow::Parser;

use crate::parse::till_null;

use super::GitLike;

/// Git methods for dealing with statuses and the working tree.
#[repr(transparent)]
pub struct GitStatus<'a, G>(&'a G);

impl<G> Debug for GitStatus<'_, G>
where
    G: GitLike,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("GitStatus")
            .field(&self.0.get_current_dir().as_ref())
            .finish()
    }
}

impl<'a, G> GitStatus<'a, G>
where
    G: GitLike,
{
    pub fn new(git: &'a G) -> Self {
        Self(git)
    }

    #[instrument(level = "trace")]
    pub fn get(&self) -> miette::Result<Status> {
        Ok(self
            .0
            .command()
            .args(["status", "--porcelain=v1", "--ignored=traditional", "-z"])
            .output_checked_as(|context: OutputContext<Utf8Output>| {
                if context.status().success() {
                    Status::from_str(&context.output().stdout).map_err(|err| context.error_msg(err))
                } else {
                    Err(context.error())
                }
            })?)
    }

    /// List untracked files and directories.
    #[instrument(level = "trace")]
    pub fn untracked_files(&self) -> miette::Result<Vec<Utf8PathBuf>> {
        Ok(self
            .0
            .command()
            .args([
                "ls-files",
                // Show untracked (e.g. ignored) files.
                "--others",
                // If a whole directory is classified as other, show just its name and not its
                // whole contents.
                "--directory",
                "-z",
            ])
            .output_checked_utf8()?
            .stdout
            .split('\0')
            .filter(|path| !path.is_empty())
            .map(Utf8PathBuf::from)
            .collect())
    }
}

/// The status code of a particular file. Each [`StatusEntry`] has two of these.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StatusCode {
    /// ` `
    Unmodified,
    /// `M`
    Modified,
    /// `T`
    TypeChanged,
    /// `A`
    Added,
    /// `D`
    Deleted,
    /// `R`
    Renamed,
    /// `C`
    Copied,
    /// `U`
    Unmerged,
    /// `?`
    Untracked,
    /// `!`
    Ignored,
}

impl StatusCode {
    pub fn parser(input: &mut &str) -> PResult<Self> {
        let code = one_of([' ', 'M', 'T', 'A', 'D', 'R', 'C', 'U', '?', '!']).parse_next(input)?;
        Ok(match code {
            ' ' => Self::Unmodified,
            'M' => Self::Modified,
            'T' => Self::TypeChanged,
            'A' => Self::Added,
            'D' => Self::Deleted,
            'R' => Self::Renamed,
            'C' => Self::Copied,
            'U' => Self::Unmerged,
            '?' => Self::Untracked,
            '!' => Self::Ignored,
            _ => {
                unreachable!()
            }
        })
    }
}

impl Display for StatusCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::Unmodified => ' ',
                Self::Modified => 'M',
                Self::TypeChanged => 'T',
                Self::Added => 'A',
                Self::Deleted => 'D',
                Self::Renamed => 'R',
                Self::Copied => 'C',
                Self::Unmerged => 'U',
                Self::Untracked => '?',
                Self::Ignored => '!',
            }
        )
    }
}

/// The status of a particular file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StatusEntry {
    /// The status of the file in the index.
    ///
    /// If no merge is occurring, or a merge was successful, this indicates the status of the
    /// index.
    ///
    /// If a merge conflict has occured and is not resolved, this is the left head of th
    /// merge.
    pub left: StatusCode,
    /// The status of the file in the working tree.
    ///
    /// If no merge is occurring, or a merge was successful, this indicates the status of the
    /// working tree.
    ///
    /// If a merge conflict has occured and is not resolved, this is the right head of th
    /// merge.
    pub right: StatusCode,
    /// The path for this status entry.
    pub path: Utf8PathBuf,
    /// The path this status entry was renamed from, if any.
    pub renamed_from: Option<Utf8PathBuf>,
}

impl StatusEntry {
    pub fn codes(&self) -> impl Iterator<Item = StatusCode> {
        iter::once(self.left).chain(iter::once(self.right))
    }

    pub fn is_renamed(&self) -> bool {
        self.codes().any(|code| matches!(code, StatusCode::Renamed))
    }

    /// True if the file is not ignored, untracked, or unmodified.
    pub fn is_modified(&self) -> bool {
        self.codes().any(|code| {
            !matches!(
                code,
                StatusCode::Ignored | StatusCode::Untracked | StatusCode::Unmodified
            )
        })
    }

    pub fn parser(input: &mut &str) -> PResult<Self> {
        let left = StatusCode::parser.parse_next(input)?;
        let right = StatusCode::parser.parse_next(input)?;
        let _ = ' '.parse_next(input)?;
        let path = till_null.parse_next(input)?;

        let mut entry = Self {
            left,
            right,
            path: Utf8PathBuf::from(path),
            renamed_from: None,
        };

        if entry.is_renamed() {
            let renamed_from = till_null.parse_next(input)?;
            entry.renamed_from = Some(Utf8PathBuf::from(renamed_from));
        }

        Ok(entry)
    }
}

impl FromStr for StatusEntry {
    type Err = miette::Report;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        Self::parser.parse(input).map_err(|err| miette!("{err}"))
    }
}

impl Display for StatusEntry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}{} ", self.left, self.right)?;
        if let Some(renamed_from) = &self.renamed_from {
            write!(f, "{renamed_from} -> ")?;
        }
        write!(f, "{}", self.path)
    }
}

/// A `git status` listing.
///
/// ```plain
///  M Cargo.lock
///  M Cargo.toml
///  M src/app.rs
///  M src/cli.rs
///  D src/commit_hash.rs
///  D src/git.rs
///  M src/main.rs
///  D src/ref_name.rs
///  D src/worktree.rs
/// ?? src/config.rs
/// ?? src/git/
/// ?? src/utf8tempdir.rs
/// !! target/
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Status {
    pub entries: Vec<StatusEntry>,
}

impl Status {
    #[instrument(level = "trace")]
    pub fn is_clean(&self) -> bool {
        self.entries.iter().all(|entry| !entry.is_modified())
    }

    pub fn parser(input: &mut &str) -> PResult<Self> {
        if opt(eof).parse_next(input)?.is_some() {
            return Ok(Self {
                entries: Vec::new(),
            });
        }

        let (entries, _eof) = repeat_till(1.., StatusEntry::parser, eof).parse_next(input)?;
        Ok(Self { entries })
    }
}

impl FromStr for Status {
    type Err = miette::Report;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        Self::parser.parse(input).map_err(|err| miette!("{err}"))
    }
}

#[cfg(test)]
mod tests {
    use indoc::indoc;
    use pretty_assertions::assert_eq;

    use super::*;

    #[test]
    fn test_status_parse_empty() {
        assert_eq!(Status::from_str("").unwrap().entries, vec![]);
    }

    #[test]
    fn test_status_parse_complex() {
        assert_eq!(
            Status::from_str(
                &indoc!(
                    " M Cargo.lock
                     M Cargo.toml
                     M src/app.rs
                     M src/cli.rs
                     D src/commit_hash.rs
                     D src/git.rs
                     M src/main.rs
                     D src/ref_name.rs
                     D src/worktree.rs
                    ?? src/config.rs
                    ?? src/git/
                    ?? src/utf8tempdir.rs
                    !! target/
                    "
                )
                .replace('\n', "\0")
            )
            .unwrap()
            .entries,
            vec![
                StatusEntry {
                    left: StatusCode::Unmodified,
                    right: StatusCode::Modified,
                    path: "Cargo.lock".into(),
                    renamed_from: None,
                },
                StatusEntry {
                    left: StatusCode::Unmodified,
                    right: StatusCode::Modified,
                    path: "Cargo.toml".into(),
                    renamed_from: None,
                },
                StatusEntry {
                    left: StatusCode::Unmodified,
                    right: StatusCode::Modified,
                    path: "src/app.rs".into(),
                    renamed_from: None,
                },
                StatusEntry {
                    left: StatusCode::Unmodified,
                    right: StatusCode::Modified,
                    path: "src/cli.rs".into(),
                    renamed_from: None,
                },
                StatusEntry {
                    left: StatusCode::Unmodified,
                    right: StatusCode::Deleted,
                    path: "src/commit_hash.rs".into(),
                    renamed_from: None,
                },
                StatusEntry {
                    left: StatusCode::Unmodified,
                    right: StatusCode::Deleted,
                    path: "src/git.rs".into(),
                    renamed_from: None,
                },
                StatusEntry {
                    left: StatusCode::Unmodified,
                    right: StatusCode::Modified,
                    path: "src/main.rs".into(),
                    renamed_from: None,
                },
                StatusEntry {
                    left: StatusCode::Unmodified,
                    right: StatusCode::Deleted,
                    path: "src/ref_name.rs".into(),
                    renamed_from: None,
                },
                StatusEntry {
                    left: StatusCode::Unmodified,
                    right: StatusCode::Deleted,
                    path: "src/worktree.rs".into(),
                    renamed_from: None,
                },
                StatusEntry {
                    left: StatusCode::Untracked,
                    right: StatusCode::Untracked,
                    path: "src/config.rs".into(),
                    renamed_from: None,
                },
                StatusEntry {
                    left: StatusCode::Untracked,
                    right: StatusCode::Untracked,
                    path: "src/git/".into(),
                    renamed_from: None,
                },
                StatusEntry {
                    left: StatusCode::Untracked,
                    right: StatusCode::Untracked,
                    path: "src/utf8tempdir.rs".into(),
                    renamed_from: None,
                },
                StatusEntry {
                    left: StatusCode::Ignored,
                    right: StatusCode::Ignored,
                    path: "target/".into(),
                    renamed_from: None,
                },
            ]
        );
    }

    #[test]
    fn test_status_parse_renamed() {
        assert_eq!(
            Status::from_str("R  PUPPY.md\0README.md\0")
                .unwrap()
                .entries,
            vec![StatusEntry {
                left: StatusCode::Renamed,
                right: StatusCode::Unmodified,
                path: "PUPPY.md".into(),
                renamed_from: Some("README.md".into()),
            }]
        );
    }
}