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
|
use git2::RepositoryState;
use std::path::{Path, PathBuf};
use super::{Context, Module, RootModuleConfig};
use crate::configs::git_state::GitStateConfig;
use crate::formatter::StringFormatter;
/// Creates a module with the state of the git repository at the current directory
///
/// During a git operation it will show: REBASING, BISECTING, MERGING, etc.
/// If the progress information is available (e.g. rebasing 3/10), it will show that too.
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("git_state");
let config: GitStateConfig = GitStateConfig::try_load(module.config);
let repo = context.get_repo().ok()?;
let repo_root = repo.root.as_ref()?;
let repo_state = repo.state?;
let state_description = get_state_description(repo_state, repo_root, &config)?;
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"state" => Some(state_description.label),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"progress_current" => state_description.current.as_ref().map(Ok),
"progress_total" => state_description.total.as_ref().map(Ok),
_ => None,
})
.parse(None)
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `git_state`:\n{}", error);
return None;
}
});
Some(module)
}
/// Returns the state of the current repository
///
/// During a git operation it will show: REBASING, BISECTING, MERGING, etc.
fn get_state_description<'a>(
state: RepositoryState,
root: &'a Path,
config: &GitStateConfig<'a>,
) -> Option<StateDescription<'a>> {
match state {
RepositoryState::Clean => None,
RepositoryState::Merge => Some(StateDescription {
label: config.merge,
current: None,
total: None,
}),
RepositoryState::Revert => Some(StateDescription {
label: config.revert,
current: None,
total: None,
}),
RepositoryState::RevertSequence => Some(StateDescription {
label: config.revert,
current: None,
total: None,
}),
RepositoryState::CherryPick => Some(StateDescription {
label: config.cherry_pick,
current: None,
total: None,
}),
RepositoryState::CherryPickSequence => Some(StateDescription {
label: config.cherry_pick,
current: None,
total: None,
}),
RepositoryState::Bisect => Some(StateDescription {
label: config.bisect,
current: None,
total: None,
}),
RepositoryState::ApplyMailbox => Some(StateDescription {
label: config.am,
current: None,
total: None,
}),
RepositoryState::ApplyMailboxOrRebase => Some(StateDescription {
label: config.am_or_rebase,
current: None,
total: None,
}),
RepositoryState::Rebase => Some(describe_rebase(root, config.rebase)),
RepositoryState::RebaseInteractive => Some(describe_rebase(root, config.rebase)),
RepositoryState::RebaseMerge => Some(describe_rebase(root, config.rebase)),
}
}
fn describe_rebase<'a>(root: &'a Path, rebase_config: &'a str) -> StateDescription<'a> {
/*
* Sadly, libgit2 seems to have some issues with reading the state of
* interactive rebases. So, instead, we'll poke a few of the .git files
* ourselves. This might be worth re-visiting this in the future...
*
* The following is based heavily on: https://github.com/magicmonty/bash-git-prompt
*/
let dot_git = root.join(".git");
let dot_git = if let Ok(conf) = std::fs::read_to_string(&dot_git) {
let gitdir_re = regex::Regex::new(r"(?m)^gitdir: (.*)$").unwrap();
if let Some(caps) = gitdir_re.captures(&conf) {
root.join(caps.get(1).unwrap().as_str())
} else {
dot_git
}
} else {
dot_git
};
let has_path = |relative_path: &str| {
let path = dot_git.join(PathBuf::from(relative_path));
path.exists()
};
let file_to_usize = |relative_path: &str| {
let path = dot_git.join(PathBuf::from(relative_path));
let contents = crate::utils::read_file(path).ok()?;
let quantity = contents.trim().parse::<usize>().ok()?;
Some(quantity)
};
let paths_to_progress = |current_path: &str, total_path: &str| {
let current = file_to_usize(current_path)?;
let total = file_to_usize(total_path)?;
Some((current, total))
};
let progress = if has_path("rebase-merge/msgnum") {
paths_to_progress("rebase-merge/msgnum", "rebase-merge/end")
} else if has_path("rebase-apply") {
paths_to_progress("rebase-apply/next", "rebase-apply/last")
} else {
None
};
let (current, total) = if let Some((c, t)) = progress {
(Some(format!("{}", c)), Some(format!("{}", t)))
} else {
(None, None)
};
StateDescription {
label: rebase_config,
current,
total,
}
}
struct StateDescription<'a> {
label: &'a str,
current: Option<String>,
total: Option<String>,
}
#[cfg(test)]
mod tests {
use ansi_term::Color;
use std::ffi::OsStr;
use std::fs::OpenOptions;
use std::io::{self, Error, ErrorKind, Write};
use std::path::Path;
use std::process::{Command, Stdio};
use crate::test::ModuleRenderer;
#[test]
fn show_nothing_on_empty_dir() -> io::Result<()> {
let repo_dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("git_state")
.path(repo_dir.path())
.collect();
let expected = None;
assert_eq!(expected, actual);
repo_dir.close()
}
#[test]
fn shows_rebasing() -> io::Result<()> {
let repo_dir = create_repo_with_conflict()?;
let path = repo_dir.path();
run_git_cmd(&["rebase", "other-branch"], Some(path), false)?;
let actual = ModuleRenderer::new("git_state").path(path).collect();
let expected = Some(format!("({}) ", Color::Yellow.bold().paint("REBASING 1/1")));
assert_eq!(expected, actual);
repo_dir.close()
}
#[test]
fn shows_merging() -> io::Result<()> {
let repo_dir = create_repo_with_conflict()?;
let path = repo_dir.path();
run_git_cmd(&["merge", "other-branch"], Some(path), false)?;
let actual = ModuleRenderer::new("git_state").path(path).collect();
let expected = Some(format!("({}) ", Color::Yellow.bold().paint("MERGING")));
assert_eq!(
|