git-ward 0.2.0

Proof-before-delete archival for local Git repositories
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::process::Command;
use walkdir::WalkDir;

pub fn find_git_repos(root: &Path) -> Vec<PathBuf> {
    let mut repos = Vec::new();
    let mut it = WalkDir::new(root).into_iter();
    loop {
        let entry = match it.next() {
            None => break,
            Some(Err(_)) => continue,
            Some(Ok(e)) => e,
        };
        if !entry.file_type().is_dir() {
            continue;
        }
        let name = entry.file_name().to_string_lossy().to_string();
        if name == ".git" {
            it.skip_current_dir();
            continue;
        }
        if name.starts_with('.') && entry.depth() > 0 {
            it.skip_current_dir();
            continue;
        }
        if entry.path().join(".git").is_dir() {
            repos.push(entry.path().to_path_buf());
            it.skip_current_dir();
        }
    }
    repos
}

pub fn remote_urls(repo: &Path) -> Vec<(String, String)> {
    Command::new("git")
        .args(["remote", "-v"])
        .current_dir(repo)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
        .map(|text| {
            let mut seen = std::collections::HashSet::new();
            let mut result = Vec::new();
            for line in text.lines() {
                let mut parts = line.split_whitespace();
                let Some(name) = parts.next() else { continue };
                let Some(url) = parts.next() else { continue };
                let key = format!("{name}:{url}");
                if seen.insert(key) {
                    result.push((name.to_string(), url.to_string()));
                }
            }
            result
        })
        .unwrap_or_default()
}

pub fn origin_url(repo: &Path) -> Option<String> {
    Command::new("git")
        .args(["remote", "get-url", "origin"])
        .current_dir(repo)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .filter(|s| !s.is_empty())
}

pub fn last_commit_date(repo: &Path) -> Option<chrono::NaiveDate> {
    Command::new("git")
        .args(["log", "-1", "--format=%aI"])
        .current_dir(repo)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .and_then(|o| {
            let s = String::from_utf8_lossy(&o.stdout).trim().to_string();
            chrono::DateTime::parse_from_rfc3339(&s)
                .ok()
                .map(|dt| dt.date_naive())
        })
}

pub fn first_commit_date(repo: &Path) -> Option<chrono::NaiveDate> {
    Command::new("git")
        .args(["log", "--reverse", "--format=%aI"])
        .current_dir(repo)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .and_then(|o| {
            let s = String::from_utf8_lossy(&o.stdout);
            let first = s.lines().next()?.trim().to_string();
            chrono::DateTime::parse_from_rfc3339(&first)
                .ok()
                .map(|dt| dt.date_naive())
        })
}

pub fn head_sha(repo: &Path) -> Option<String> {
    Command::new("git")
        .args(["rev-parse", "HEAD"])
        .current_dir(repo)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .filter(|s| !s.is_empty())
}

pub fn root_commit_sha(repo: &Path) -> Option<String> {
    Command::new("git")
        .args(["rev-list", "--max-parents=0", "HEAD"])
        .current_dir(repo)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .and_then(|o| {
            let text = String::from_utf8_lossy(&o.stdout).to_string();
            text.lines().next().map(|s| s.trim().to_string())
        })
        .filter(|s| !s.is_empty())
}

pub fn commit_count(repo: &Path) -> u64 {
    Command::new("git")
        .args(["rev-list", "--count", "HEAD"])
        .current_dir(repo)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .and_then(|o| {
            String::from_utf8_lossy(&o.stdout)
                .trim()
                .parse::<u64>()
                .ok()
        })
        .unwrap_or(0)
}

pub fn author_count(repo: &Path) -> u64 {
    Command::new("git")
        .args(["log", "--format=%ae"])
        .current_dir(repo)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| {
            let text = String::from_utf8_lossy(&o.stdout).to_string();
            let mut set = std::collections::HashSet::new();
            for line in text.lines() {
                set.insert(line.trim().to_string());
            }
            set.len() as u64
        })
        .unwrap_or(0)
}

pub fn has_uncommitted_changes(repo: &Path) -> Result<bool> {
    let output = Command::new("git")
        .args(["status", "--porcelain"])
        .current_dir(repo)
        .output()
        .context("Failed to run git status")?;
    let text = String::from_utf8_lossy(&output.stdout);
    let has_tracked_changes = text
        .lines()
        .any(|l| !l.starts_with("?? ") && !l.starts_with("!! ") && !l.trim().is_empty());
    Ok(has_tracked_changes)
}

pub fn untracked_count(repo: &Path) -> Result<(u64, u64)> {
    let output = Command::new("git")
        .args(["status", "--porcelain", "--ignored"])
        .current_dir(repo)
        .output()
        .context("Failed to run git status")?;
    let text = String::from_utf8_lossy(&output.stdout);
    let mut untracked = 0u64;
    let mut ignored = 0u64;
    for line in text.lines() {
        if line.starts_with("?? ") {
            untracked += 1;
        } else if line.starts_with("!! ") {
            ignored += 1;
        }
    }
    Ok((untracked, ignored))
}

pub fn stash_count(repo: &Path) -> u64 {
    Command::new("git")
        .args(["stash", "list"])
        .current_dir(repo)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).lines().count() as u64)
        .unwrap_or(0)
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BranchStatus {
    pub name: String,
    pub upstream: Option<String>,
    pub ahead: u64,
}

pub fn branches(repo: &Path) -> Vec<BranchStatus> {
    let output = Command::new("git")
        .args([
            "for-each-ref",
            "--format=%(refname:short)|%(upstream:short)|%(upstream:track)",
            "refs/heads",
        ])
        .current_dir(repo)
        .output();
    let Ok(output) = output else {
        return Vec::new();
    };
    if !output.status.success() {
        return Vec::new();
    }
    let text = String::from_utf8_lossy(&output.stdout).to_string();
    let mut result = Vec::new();
    for line in text.lines() {
        let parts: Vec<&str> = line.split('|').collect();
        if parts.len() < 2 {
            continue;
        }
        let name = parts[0].to_string();
        let upstream = if parts[1].is_empty() {
            None
        } else {
            Some(parts[1].to_string())
        };
        let track = parts.get(2).unwrap_or(&"");
        let ahead = parse_ahead(track);
        result.push(BranchStatus {
            name,
            upstream,
            ahead,
        });
    }
    result
}

fn parse_ahead(s: &str) -> u64 {
    let inner = s.trim_start_matches('[').trim_end_matches(']');
    for part in inner.split(", ") {
        if let Some(n) = part.strip_prefix("ahead ") {
            return n.parse().unwrap_or(0);
        }
    }
    0
}

pub fn tag_count(repo: &Path) -> u64 {
    Command::new("git")
        .args(["tag", "--list"])
        .current_dir(repo)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).lines().count() as u64)
        .unwrap_or(0)
}

pub fn worktree_paths(repo: &Path) -> Vec<PathBuf> {
    let output = Command::new("git")
        .args(["worktree", "list", "--porcelain"])
        .current_dir(repo)
        .output();
    let Ok(output) = output else {
        return Vec::new();
    };
    if !output.status.success() {
        return Vec::new();
    }
    let text = String::from_utf8_lossy(&output.stdout).to_string();
    let mut paths = Vec::new();
    for line in text.lines() {
        if let Some(path) = line.strip_prefix("worktree ") {
            paths.push(PathBuf::from(path));
        }
    }
    paths
}

pub fn stash_shas(repo: &Path) -> Vec<String> {
    Command::new("git")
        .args(["reflog", "show", "refs/stash", "--format=%H"])
        .current_dir(repo)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| {
            String::from_utf8_lossy(&o.stdout)
                .lines()
                .map(|l| l.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect()
        })
        .unwrap_or_default()
}

pub fn create_stash_refs(repo: &Path) -> Result<Vec<String>> {
    let shas = stash_shas(repo);
    for (i, sha) in shas.iter().enumerate() {
        let refname = format!("refs/ward-stash/{i}");
        let output = Command::new("git")
            .args(["update-ref", &refname, sha])
            .current_dir(repo)
            .output()
            .context("Failed to create stash ref")?;
        if !output.status.success() {
            let err = String::from_utf8_lossy(&output.stderr).to_string();
            anyhow::bail!("update-ref failed for {refname}: {err}");
        }
    }
    Ok(shas)
}

pub fn cleanup_stash_refs(repo: &Path) {
    let output = Command::new("git")
        .args(["for-each-ref", "--format=%(refname)", "refs/ward-stash/"])
        .current_dir(repo)
        .output();
    if let Ok(o) = output {
        let text = String::from_utf8_lossy(&o.stdout).to_string();
        for refname in text.lines() {
            let _ = Command::new("git")
                .args(["update-ref", "-d", refname.trim()])
                .current_dir(repo)
                .output();
        }
    }
}

pub fn restore_stash_refs(repo: &Path) -> Result<u64> {
    let output = Command::new("git")
        .args([
            "for-each-ref",
            "--sort=refname",
            "--format=%(refname) %(objectname)",
            "refs/ward-stash/",
        ])
        .current_dir(repo)
        .output()
        .context("Failed to list ward-stash refs")?;
    let text = String::from_utf8_lossy(&output.stdout).to_string();
    let mut count = 0u64;
    for line in text.lines() {
        let mut parts = line.splitn(2, ' ');
        let Some(refname) = parts.next() else {
            continue;
        };
        let Some(sha) = parts.next() else { continue };
        let store = Command::new("git")
            .args(["stash", "store", "-m", "restored by ward", sha.trim()])
            .current_dir(repo)
            .output();
        if store.is_ok() {
            count += 1;
        }
        let _ = Command::new("git")
            .args(["update-ref", "-d", refname.trim()])
            .current_dir(repo)
            .output();
    }
    Ok(count)
}

pub fn has_submodules(repo: &Path) -> bool {
    repo.join(".gitmodules").exists()
}

pub fn submodule_count(repo: &Path) -> u64 {
    if !has_submodules(repo) {
        return 0;
    }
    Command::new("git")
        .args(["submodule", "status"])
        .current_dir(repo)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| {
            String::from_utf8_lossy(&o.stdout)
                .lines()
                .filter(|l| !l.trim().is_empty())
                .count() as u64
        })
        .unwrap_or(0)
}

pub fn has_worktree_config(repo: &Path) -> bool {
    repo.join(".git/config.worktree").exists()
}

pub fn effective_hooks_path(repo: &Path) -> Option<PathBuf> {
    let output = std::process::Command::new("git")
        .args(["config", "--get", "core.hooksPath"])
        .current_dir(repo)
        .output()
        .ok()?;
    if output.status.success() {
        let p = String::from_utf8_lossy(&output.stdout).trim().to_string();
        if p.is_empty() {
            return None;
        }
        let path = if let Some(rest) = p.strip_prefix("~/") {
            if let Ok(home) = std::env::var("HOME") {
                PathBuf::from(format!("{home}/{rest}"))
            } else {
                PathBuf::from(&p)
            }
        } else {
            PathBuf::from(&p)
        };
        if path.is_dir() {
            return Some(path);
        }
    }
    None
}

pub fn custom_hooks(repo: &Path) -> Vec<PathBuf> {
    let hooks_dir = effective_hooks_path(repo)
        .unwrap_or_else(|| repo.join(".git/hooks"));
    if !hooks_dir.is_dir() {
        return Vec::new();
    }
    std::fs::read_dir(&hooks_dir)
        .ok()
        .map(|entries| {
            entries
                .filter_map(|e| e.ok())
                .map(|e| e.path())
                .filter(|p| p.is_file() && !p.to_string_lossy().ends_with(".sample"))
                .collect()
        })
        .unwrap_or_default()
}

pub fn normalise_remote_url(url: &str) -> String {
    let s = url.trim();
    let s = s.strip_suffix(".git").unwrap_or(s);
    let s = if let Some(rest) = s.strip_prefix("git@") {
        rest.replacen(':', "/", 1)
    } else {
        s.to_string()
    };
    let s = s.strip_prefix("https://").unwrap_or(&s);
    let s = s.strip_prefix("http://").unwrap_or(s);
    let s = s.strip_prefix("ssh://").unwrap_or(s);
    s.to_lowercase()
}