1use std::fmt::Display;
2use std::path::PathBuf;
3use std::str::FromStr;
4
5use bstr::ByteVec;
6use lazy_static::lazy_static;
7use regex::bytes::Regex;
8use tracing::{instrument, warn};
9
10#[allow(missing_docs)]
13#[derive(Copy, Clone, Debug, PartialEq, Eq)]
14pub enum FileStatus {
15 Unmodified,
16 Modified,
17 Added,
18 Deleted,
19 Renamed,
20 Copied,
21 Unmerged,
22 Untracked,
23 Ignored,
24}
25
26impl FileStatus {
27 pub fn is_changed(&self) -> bool {
30 match self {
31 FileStatus::Added
32 | FileStatus::Copied
33 | FileStatus::Deleted
34 | FileStatus::Modified
35 | FileStatus::Renamed => true,
36 FileStatus::Ignored
37 | FileStatus::Unmerged
38 | FileStatus::Unmodified
39 | FileStatus::Untracked => false,
40 }
41 }
42}
43
44impl From<u8> for FileStatus {
45 fn from(status: u8) -> Self {
46 match status {
47 b'.' => FileStatus::Unmodified,
48 b'M' => FileStatus::Modified,
49 b'A' => FileStatus::Added,
50 b'D' => FileStatus::Deleted,
51 b'R' => FileStatus::Renamed,
52 b'C' => FileStatus::Copied,
53 b'U' => FileStatus::Unmerged,
54 b'?' => FileStatus::Untracked,
55 b'!' => FileStatus::Ignored,
56 _ => {
57 warn!(?status, "invalid status indicator");
58 FileStatus::Untracked
59 }
60 }
61 }
62}
63
64#[allow(missing_docs)]
66#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
67pub enum FileMode {
68 Unreadable,
69 Tree,
70 Blob,
71 BlobExecutable,
72 BlobGroupWritable,
73 Link,
74 Commit,
75}
76
77impl From<git2::FileMode> for FileMode {
78 fn from(file_mode: git2::FileMode) -> Self {
79 match file_mode {
80 git2::FileMode::Blob => FileMode::Blob,
81 git2::FileMode::BlobExecutable => FileMode::BlobExecutable,
82 git2::FileMode::BlobGroupWritable => FileMode::BlobGroupWritable,
83 git2::FileMode::Commit => FileMode::Commit,
84 git2::FileMode::Link => FileMode::Link,
85 git2::FileMode::Tree => FileMode::Tree,
86 git2::FileMode::Unreadable => FileMode::Unreadable,
87 }
88 }
89}
90
91impl From<i32> for FileMode {
92 fn from(file_mode: i32) -> Self {
93 if file_mode == i32::from(git2::FileMode::Blob) {
94 FileMode::Blob
95 } else if file_mode == i32::from(git2::FileMode::BlobExecutable) {
96 FileMode::BlobExecutable
97 } else if file_mode == i32::from(git2::FileMode::Commit) {
98 FileMode::Commit
99 } else if file_mode == i32::from(git2::FileMode::Link) {
100 FileMode::Link
101 } else if file_mode == i32::from(git2::FileMode::Tree) {
102 FileMode::Tree
103 } else {
104 FileMode::Unreadable
105 }
106 }
107}
108
109impl From<FileMode> for i32 {
110 fn from(file_mode: FileMode) -> Self {
111 match file_mode {
112 FileMode::Blob => git2::FileMode::Blob.into(),
113 FileMode::BlobExecutable => git2::FileMode::BlobExecutable.into(),
114 FileMode::BlobGroupWritable => git2::FileMode::BlobGroupWritable.into(),
115 FileMode::Commit => git2::FileMode::Commit.into(),
116 FileMode::Link => git2::FileMode::Link.into(),
117 FileMode::Tree => git2::FileMode::Tree.into(),
118 FileMode::Unreadable => git2::FileMode::Unreadable.into(),
119 }
120 }
121}
122
123impl From<FileMode> for u32 {
124 fn from(file_mode: FileMode) -> Self {
125 i32::from(file_mode).try_into().unwrap()
126 }
127}
128
129impl FromStr for FileMode {
130 type Err = eyre::Error;
131
132 fn from_str(file_mode: &str) -> eyre::Result<Self> {
136 let file_mode = match file_mode {
137 "000000" => FileMode::Unreadable,
138 "040000" => FileMode::Tree,
139 "100644" => FileMode::Blob,
140 "100755" => FileMode::BlobExecutable,
141 "100664" => FileMode::BlobGroupWritable,
142 "120000" => FileMode::Link,
143 "160000" => FileMode::Commit,
144 _ => eyre::bail!("unknown file mode: {}", file_mode),
145 };
146 Ok(file_mode)
147 }
148}
149
150impl Display for FileMode {
151 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
152 match self {
153 FileMode::Unreadable => write!(f, "000000"),
154 FileMode::Tree => write!(f, "040000"),
155 FileMode::Blob => write!(f, "100644"),
156 FileMode::BlobExecutable => write!(f, "100755"),
157 FileMode::BlobGroupWritable => write!(f, "100664"),
158 FileMode::Link => write!(f, "120000"),
159 FileMode::Commit => write!(f, "160000"),
160 }
161 }
162}
163
164#[derive(Clone, Debug, PartialEq, Eq)]
166pub struct StatusEntry {
167 pub index_status: FileStatus,
169 pub working_copy_status: FileStatus,
171 pub working_copy_file_mode: FileMode,
173 pub path: PathBuf,
175 pub orig_path: Option<PathBuf>,
177}
178
179impl StatusEntry {
180 pub fn paths(&self) -> Vec<PathBuf> {
182 let mut result = vec![self.path.clone()];
183 if let Some(orig_path) = &self.orig_path {
184 result.push(orig_path.clone());
185 }
186 result
187 }
188}
189
190impl TryFrom<&[u8]> for StatusEntry {
191 type Error = eyre::Error;
192
193 #[instrument]
194 fn try_from(line: &[u8]) -> eyre::Result<StatusEntry> {
195 lazy_static! {
196 static ref STATUS_PORCELAIN_V2_REGEXP: Regex = Regex::new(concat!(
199 r#"^(?P<prefix>1|2|u) "#, r#"(?P<index_status>[\w.])(?P<working_copy_status>[\w.]) "#, r#"[\w.]+ "#, r#"(\d{6} ){2,3}(?P<working_copy_filemode>\d{6}) "#, r#"([a-f\d]+ ){2,3}([CR]\d{1,3} )?"#, r#"(?P<path>[^\x00]+)(\x00(?P<orig_path>[^\x00]+))?$"# ))
208 .expect("porcelain v2 status line regex");
209 }
210
211 let status_line_parts = STATUS_PORCELAIN_V2_REGEXP
212 .captures(line)
213 .ok_or_else(|| eyre::eyre!("unable to parse status line into parts"))?;
214
215 let index_status: FileStatus = match status_line_parts.name("prefix") {
216 Some(m) if m.as_bytes() == b"u" => FileStatus::Unmerged,
217 _ => status_line_parts
218 .name("index_status")
219 .and_then(|m| m.as_bytes().iter().next().copied())
220 .ok_or_else(|| eyre::eyre!("no index status indicator"))?
221 .into(),
222 };
223 let working_copy_status: FileStatus = status_line_parts
224 .name("working_copy_status")
225 .and_then(|m| m.as_bytes().iter().next().copied())
226 .ok_or_else(|| eyre::eyre!("no working copy status indicator"))?
227 .into();
228 let working_copy_file_mode = status_line_parts
229 .name("working_copy_filemode")
230 .ok_or_else(|| eyre::eyre!("no working copy filemode in status line"))
231 .and_then(|m| {
232 std::str::from_utf8(m.as_bytes())
233 .map_err(|err| {
234 eyre::eyre!("unable to decode working copy file mode: {:?}", err)
235 })
236 .and_then(|working_copy_file_mode| working_copy_file_mode.parse::<FileMode>())
237 })?;
238 let path = status_line_parts
239 .name("path")
240 .ok_or_else(|| eyre::eyre!("no path in status line"))?
241 .as_bytes();
242 let orig_path = status_line_parts
243 .name("orig_path")
244 .map(|orig_path| orig_path.as_bytes());
245
246 Ok(StatusEntry {
247 index_status,
248 working_copy_status,
249 working_copy_file_mode,
250 path: path.to_vec().into_path_buf()?,
251 orig_path: orig_path
252 .map(|orig_path| orig_path.to_vec().into_path_buf())
253 .transpose()?,
254 })
255 }
256}