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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
use std::path::{Path, PathBuf};
use git2::{Branch, Delta, Error, Repository, StatusOptions};
use indexmap::set::IndexSet as Set;
use walkdir::WalkDir;
#[derive(Debug)]
pub struct Output {
pub path: PathBuf,
pub pending: Option<Set<&'static str>>,
pub error: Option<Error>,
}
pub struct Crawler {
pending: bool,
ignore_untracked: bool,
ignore_uncommitted_repos: bool,
absolute_paths: bool,
untagged_heads: bool,
access_remote: Option<String>,
root_path: PathBuf,
iter: Box<dyn Iterator<Item = Repository>>,
}
impl Crawler {
pub fn new<P: AsRef<Path>>(root: P) -> Self {
Crawler {
pending: false,
ignore_untracked: false,
ignore_uncommitted_repos: false,
absolute_paths: false,
untagged_heads: false,
access_remote: None,
root_path: root.as_ref().into(),
iter: Box::new(
WalkDir::new(root)
.into_iter()
.filter_map(|entry| entry.ok())
.filter(|entry| entry.file_type().is_dir())
.filter(|entry| entry.file_name() != ".git")
.filter_map(|entry| Repository::open(entry.path()).ok()),
),
}
}
pub fn pending(mut self, answer: bool) -> Self {
self.pending = answer;
self
}
pub fn ignore_untracked(mut self, answer: bool) -> Self {
self.ignore_untracked = answer;
self
}
pub fn ignore_uncommitted_repos(mut self, answer: bool) -> Self {
self.ignore_uncommitted_repos = answer;
self
}
pub fn absolute_paths(mut self, answer: bool) -> Self {
self.absolute_paths = answer;
self
}
pub fn untagged_heads(mut self, answer: bool) -> Self {
self.untagged_heads = answer;
self
}
pub fn access_remote(mut self, ssh_auth_method: Option<String>) -> Self {
self.access_remote = ssh_auth_method;
self
}
fn repo_ops(&self, repo: &Repository) -> Option<Output> {
if let Some(path) = repo.workdir() {
if git2::Repository::discover(path).is_err() {
return None;
}
let mut pending = Set::new();
let mut path = path.to_path_buf();
if !self.absolute_paths {
path = self.make_relative(&path);
}
let mut opts = StatusOptions::new();
opts.include_ignored(false)
.include_untracked(true)
.renames_head_to_index(true)
.renames_index_to_workdir(true);
let local_ref = match repo.head() {
Ok(head) => head,
Err(why) => {
if self.ignore_uncommitted_repos
&& why.class() == git2::ErrorClass::Reference
&& why.code() == git2::ErrorCode::UnbornBranch
{
return None;
}
return Some(Output {
path,
pending: None,
error: Some(why),
});
}
};
let local_branch = Branch::wrap(local_ref);
let local_head_oid = match local_branch.get().target() {
Some(oid) => oid,
None => return None,
};
match repo.statuses(Some(&mut opts)) {
Ok(statuses) => {
for status in statuses.iter() {
pending = self.diff_ops(&status, pending);
}
if self.untagged_heads {
let local_ref = local_branch.get();
if let Ok(tags) = repo.tag_names(None) {
let mut untagged = true;
for tag in tags.iter() {
if let Some(tag) = tag {
let tag = format!("refs/tags/{}", tag);
if let Ok(reference) = repo.find_reference(&tag) {
if &reference == local_ref {
untagged = false;
break;
}
}
}
}
if untagged {
pending.insert("untagged HEAD");
}
}
}
if let Ok(upstream_branch) = local_branch.upstream() {
let upstream_ref = upstream_branch.into_reference();
let upstream_head_oid = match upstream_ref.target() {
Some(oid) => oid,
None => return None,
};
if local_head_oid != upstream_head_oid {
if let Ok((ahead, behind)) =
repo.graph_ahead_behind(local_head_oid, upstream_head_oid)
{
if ahead > 0 {
pending.insert("unpushed commits");
}
if behind > 0 {
pending.insert("outdated branch");
}
}
}
}
if self.access_remote.is_some() {
pending = match self.remote_ops(repo, pending, local_head_oid) {
Ok(pending) => pending,
Err(why) => {
return Some(Output {
path,
pending: None,
error: Some(why),
});
}
}
}
if !pending.is_empty() {
Some(Output {
path,
pending: Some(pending),
error: None,
})
} else if !self.pending {
Some(Output {
path,
pending: None,
error: None,
})
} else {
None
}
}
Err(why) => Some(Output {
path,
pending: None,
error: Some(why),
}),
}
} else {
None
}
}
fn diff_ops<'b>(
&self,
status: &git2::StatusEntry<'_>,
mut pending: Set<&'b str>,
) -> Set<&'b str> {
if let Some(diff_delta) = status.index_to_workdir() {
match diff_delta.status() {
Delta::Untracked => {
if !self.ignore_untracked {
pending.insert("untracked files");
}
}
Delta::Modified => {
pending.insert("uncommitted changes");
}
Delta::Deleted => {
pending.insert("deleted files");
}
Delta::Renamed => {
pending.insert("renamed files");
}
_ => (),
}
}
if let Some(diff_delta) = status.head_to_index() {
match diff_delta.status() {
Delta::Added => {
pending.insert("added files");
}
Delta::Modified => {
pending.insert("uncommitted changes");
}
Delta::Deleted => {
pending.insert("deleted files");
}
Delta::Renamed => {
pending.insert("renamed files");
}
_ => (),
}
};
pending
}
fn remote_ops<'b>(
&self,
repo: &Repository,
mut pending: Set<&'b str>,
local_head_oid: git2::Oid,
) -> Result<Set<&'b str>, Error> {
if let Ok(remote) = repo.find_remote("origin") {
let config = git2::Config::open_default().expect("could not get git config");
let url = match remote.url() {
Some(url) => url,
None => return Ok(pending),
};
let mut callbacks = git2::RemoteCallbacks::new();
if url.starts_with("http") {
callbacks.credentials(|_, _, _| git2::Cred::credential_helper(&config, url, None));
} else if url.starts_with("git") {
if let Some(ref method) = self.access_remote {
if method == "ssh-key" {
for file_name in &["id_rsa", "id_dsa"] {
if let Some(home_dir) = dirs::home_dir() {
let private_key = home_dir.join(".ssh").join(file_name);
if private_key.exists() {
callbacks.credentials(move |_, _, _| {
git2::Cred::ssh_key("git", None, &private_key, None)
});
break;
}
}
}
} else if method == "ssh-agent" {
callbacks.credentials(|_, _, _| git2::Cred::ssh_key_from_agent("git"));
}
}
}
let mut remote = remote.clone();
remote.connect_auth(git2::Direction::Fetch, Some(callbacks), None)?;
let mut remote_tags = Set::new();
if let Ok(remote_list) = remote.list() {
for item in remote_list {
let name = item.name();
if name.starts_with("refs/tags/") {
if !name.ends_with("^{}") {
remote_tags.insert((item.name().to_string(), item.oid()));
}
} else if name.starts_with("refs/heads") && item.oid() != local_head_oid {
let mut found = false;
if let Ok(branches) = repo.branches(None) {
for branch in branches {
if let Ok(branch) = branch {
if let Some(oid) = branch.0.get().target() {
if oid == item.oid() {
found = true;
break;
}
}
}
}
}
if !found {
pending.insert("unfetched commits");
}
}
}
let mut local_tags = Set::new();
if let Ok(tags) = repo.tag_names(None) {
for tag in tags.iter() {
if let Some(tag) = tag {
let tag = format!("refs/tags/{}", tag);
if let Ok(reference) = repo.find_reference(&tag) {
if let Some(oid) = reference.target() {
local_tags.insert((tag, oid));
}
}
}
}
}
if !local_tags.is_subset(&remote_tags) {
pending.insert("unpushed tags");
}
if !remote_tags.is_subset(&local_tags) {
pending.insert("unpulled tags");
}
}
}
Ok(pending)
}
fn make_relative(&self, target_dir: &Path) -> PathBuf {
if let Ok(path) = target_dir.strip_prefix(&self.root_path) {
if path.to_string_lossy().is_empty() {
".".into()
} else {
path.into()
}
} else {
target_dir.into()
}
}
}
impl Iterator for Crawler {
type Item = Output;
fn next(&mut self) -> Option<Self::Item> {
loop {
match self.iter.next() {
None => return None,
Some(repo) => {
if let Some(output) = self.repo_ops(&repo) {
return Some(output);
}
}
}
}
}
}