gitrub 1.1.13

A local git server — push, pull, clone over HTTP and SSH with LFS, hooks, and more
Documentation
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
use std::path::Path;
use std::process::Stdio;
use tokio::io::AsyncWriteExt;
use tokio::process::Command;

use crate::Config;

// ---------------------------------------------------------------------------
// Activity tracking
// ---------------------------------------------------------------------------

/// Record an activity event (push, pull, fetch) for a repo.
pub async fn record_activity(repo: &Path, kind: &str) {
    let ts = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    let line = format!("{} {}\n", ts, kind);
    let activity_file = repo.join(".gitrub_activity");
    // Append to activity log
    if let Ok(mut existing) = tokio::fs::read_to_string(&activity_file).await {
        existing.push_str(&line);
        // Keep only last 100 lines
        let lines: Vec<&str> = existing.lines().collect();
        let keep = if lines.len() > 100 { &lines[lines.len() - 100..] } else { &lines };
        let _ = tokio::fs::write(&activity_file, keep.join("\n") + "\n").await;
    } else {
        let _ = tokio::fs::write(&activity_file, &line).await;
    }
}

/// Read the last activity entry for a repo. Returns (unix_timestamp, kind).
pub fn last_activity(repo: &Path) -> Option<(u64, String)> {
    let activity_file = repo.join(".gitrub_activity");
    let content = std::fs::read_to_string(activity_file).ok()?;
    let last_line = content.lines().rev().find(|l| !l.is_empty())?;
    let mut parts = last_line.splitn(2, ' ');
    let ts: u64 = parts.next()?.parse().ok()?;
    let kind = parts.next().unwrap_or("unknown").to_string();
    Some((ts, kind))
}

/// Get recent commits for a repo (blocking, for TUI use).
pub fn recent_commits(repo: &Path, count: usize) -> Vec<String> {
    let output = std::process::Command::new("git")
        .args(["-C"])
        .arg(repo)
        .args([
            "log",
            "--all",
            "--graph",
            "--decorate",
            "--format=%h %an │ %s (%ar)",
            &format!("-{}", count),
        ])
        .output();
    match output {
        Ok(out) if out.status.success() => {
            String::from_utf8_lossy(&out.stdout)
                .lines()
                .map(|l| l.to_string())
                .collect()
        }
        _ => vec!["(no commits yet)".into()],
    }
}

/// Get contributors sorted by number of commits (blocking, for TUI use).
pub fn contributors(repo: &Path) -> Vec<String> {
    let output = std::process::Command::new("git")
        .args(["-C"])
        .arg(repo)
        .args(["shortlog", "-sne", "--all"])
        .output();
    match output {
        Ok(out) if out.status.success() => {
            String::from_utf8_lossy(&out.stdout)
                .lines()
                .map(|l| l.trim().to_string())
                .filter(|l| !l.is_empty())
                .collect()
        }
        _ => vec!["(no contributors yet)".into()],
    }
}

/// Analyze language distribution by file extension (blocking, for TUI use).
/// Returns lines like: "Rust          1234 lines  45.2%"
pub fn languages(repo: &Path) -> Vec<String> {
    // Get file list from HEAD
    let output = std::process::Command::new("git")
        .args(["-C"])
        .arg(repo)
        .args(["ls-tree", "-r", "--name-only", "HEAD"])
        .output();

    let files: Vec<String> = match output {
        Ok(out) if out.status.success() => {
            String::from_utf8_lossy(&out.stdout)
                .lines()
                .map(|l| l.to_string())
                .collect()
        }
        _ => return vec!["(empty repository)".into()],
    };

    if files.is_empty() {
        return vec!["(empty repository)".into()];
    }

    // Count lines per extension using git show
    let mut ext_lines: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
    let mut ext_files: std::collections::HashMap<String, usize> = std::collections::HashMap::new();

    for file in &files {
        let ext = match file.rsplit_once('.') {
            Some((_, ext)) => ext.to_lowercase(),
            None => continue, // skip files without extension
        };

        // Skip binary / non-code extensions
        if matches!(
            ext.as_str(),
            "png" | "jpg" | "jpeg" | "gif" | "ico" | "svg" | "webp"
                | "woff" | "woff2" | "ttf" | "eot" | "otf"
                | "zip" | "tar" | "gz" | "bz2" | "xz" | "7z"
                | "bin" | "exe" | "dll" | "so" | "dylib"
                | "pdf" | "doc" | "docx" | "ppt" | "xlsx"
                | "mp3" | "mp4" | "wav" | "avi" | "mov"
                | "DS_Store" | "lock"
        ) {
            continue;
        }

        // Count lines via git show
        let line_output = std::process::Command::new("git")
            .args(["-C"])
            .arg(repo)
            .args(["show", &format!("HEAD:{}", file)])
            .output();

        let line_count = match line_output {
            Ok(out) if out.status.success() => {
                // Quick binary check: if output contains null bytes, skip
                if out.stdout.contains(&0u8) {
                    continue;
                }
                out.stdout.iter().filter(|&&b| b == b'\n').count()
            }
            _ => continue,
        };

        *ext_lines.entry(ext.clone()).or_default() += line_count;
        *ext_files.entry(ext).or_default() += 1;
    }

    if ext_lines.is_empty() {
        return vec!["(no source files detected)".into()];
    }

    let total_lines: usize = ext_lines.values().sum();
    let total_files: usize = ext_files.values().sum();

    // Sort by lines descending
    let mut sorted: Vec<_> = ext_lines.into_iter().collect();
    sorted.sort_by(|a, b| b.1.cmp(&a.1));

    let mut result = Vec::new();
    result.push(format!(
        "{:<16} {:>8} {:>6} {:>7}",
        "Language", "Lines", "Files", "%"
    ));
    result.push("".repeat(42));

    for (ext, lines) in &sorted {
        let files = ext_files.get(ext).copied().unwrap_or(0);
        let pct = (*lines as f64 / total_lines as f64) * 100.0;
        let lang = ext_to_language(&ext);
        result.push(format!(
            "{:<16} {:>8} {:>6} {:>6.1}%",
            lang, lines, files, pct
        ));
    }

    result.push("".repeat(42));
    result.push(format!(
        "{:<16} {:>8} {:>6} {:>6.1}%",
        "Total", total_lines, total_files, 100.0
    ));

    result
}

fn ext_to_language(ext: &str) -> &str {
    match ext {
        "rs" => "Rust",
        "py" => "Python",
        "js" => "JavaScript",
        "ts" => "TypeScript",
        "tsx" => "TSX",
        "jsx" => "JSX",
        "go" => "Go",
        "java" => "Java",
        "kt" => "Kotlin",
        "c" => "C",
        "h" => "C Header",
        "cpp" | "cc" | "cxx" => "C++",
        "hpp" => "C++ Header",
        "cs" => "C#",
        "rb" => "Ruby",
        "php" => "PHP",
        "swift" => "Swift",
        "m" => "Objective-C",
        "r" => "R",
        "scala" => "Scala",
        "dart" => "Dart",
        "lua" => "Lua",
        "zig" => "Zig",
        "nim" => "Nim",
        "ex" | "exs" => "Elixir",
        "erl" => "Erlang",
        "hs" => "Haskell",
        "ml" | "mli" => "OCaml",
        "clj" => "Clojure",
        "sh" | "bash" => "Shell",
        "zsh" => "Zsh",
        "fish" => "Fish",
        "ps1" => "PowerShell",
        "bat" | "cmd" => "Batch",
        "html" | "htm" => "HTML",
        "css" => "CSS",
        "scss" => "SCSS",
        "sass" => "Sass",
        "less" => "Less",
        "json" => "JSON",
        "yaml" | "yml" => "YAML",
        "toml" => "TOML",
        "xml" => "XML",
        "md" | "markdown" => "Markdown",
        "txt" => "Text",
        "rst" => "reStructuredText",
        "sql" => "SQL",
        "graphql" | "gql" => "GraphQL",
        "proto" => "Protobuf",
        "dockerfile" => "Dockerfile",
        "makefile" => "Makefile",
        "cmake" => "CMake",
        "tf" => "Terraform",
        "hcl" => "HCL",
        "nix" => "Nix",
        "vue" => "Vue",
        "svelte" => "Svelte",
        "astro" => "Astro",
        "sol" => "Solidity",
        "v" => "V",
        "wasm" => "WebAssembly",
        "pl" | "pm" => "Perl",
        "vim" => "Vim Script",
        "el" => "Emacs Lisp",
        "lisp" | "lsp" => "Lisp",
        "rkt" => "Racket",
        other => other,
    }
}

/// List the file tree from HEAD for a repo (blocking, for TUI use).
pub fn file_tree(repo: &Path) -> Vec<String> {
    // Use ls-tree with -l to get sizes (format: mode type size\tname)
    let output = std::process::Command::new("git")
        .args(["-C"])
        .arg(repo)
        .args(["ls-tree", "-r", "-l", "HEAD"])
        .output();
    match output {
        Ok(out) if out.status.success() => {
            String::from_utf8_lossy(&out.stdout)
                .lines()
                .map(|line| {
                    // Format: "100644 blob 1234    path/to/file"
                    // Split at tab to get metadata and path
                    if let Some((meta, path)) = line.split_once('\t') {
                        let size = meta.split_whitespace()
                            .last()
                            .and_then(|s| s.parse::<u64>().ok())
                            .map(format_file_size)
                            .unwrap_or_else(|| "-".into());
                        format!("{:>8}  {}", size, path)
                    } else {
                        line.to_string()
                    }
                })
                .collect()
        }
        _ => vec!["(empty repository)".into()],
    }
}

fn format_file_size(bytes: u64) -> String {
    if bytes < 1024 {
        format!("{}B", bytes)
    } else if bytes < 1024 * 1024 {
        format!("{:.1}K", bytes as f64 / 1024.0)
    } else if bytes < 1024 * 1024 * 1024 {
        format!("{:.1}M", bytes as f64 / (1024.0 * 1024.0))
    } else {
        format!("{:.1}G", bytes as f64 / (1024.0 * 1024.0 * 1024.0))
    }
}

/// Get branch list for a repo (blocking, for TUI use).
pub fn branches(repo: &Path) -> Vec<String> {
    let output = std::process::Command::new("git")
        .args(["-C"])
        .arg(repo)
        .args(["branch", "-a", "--no-color"])
        .output();
    match output {
        Ok(out) if out.status.success() => {
            String::from_utf8_lossy(&out.stdout)
                .lines()
                .map(|l| l.trim().to_string())
                .filter(|l| !l.is_empty())
                .collect()
        }
        _ => vec![],
    }
}

/// Initialize a git repo with working tree and all features enabled.
/// Git internals are stored in .git/, and pushed files are checked out.
pub async fn init_repo(path: &Path, config: &Config) -> Result<(), String> {
    let out = Command::new("git")
        .args(["init"])
        .arg(path)
        .output()
        .await
        .map_err(|e| e.to_string())?;
    if !out.status.success() {
        return Err(String::from_utf8_lossy(&out.stderr).into());
    }

    // Allow pushing to any branch — don't deny current branch pushes
    git_config(path, "receive.denyCurrentBranch", "ignore").await;
    // Allow deleting the current branch
    git_config(path, "receive.denyDeleteCurrent", "ignore").await;
    // Allow push over HTTP
    git_config(path, "http.receivepack", "true").await;
    // Default HEAD to main
    Command::new("git")
        .args(["-C"])
        .arg(path)
        .args(["symbolic-ref", "HEAD", "refs/heads/main"])
        .output()
        .await
        .ok();
    // Enable partial clones
    git_config(path, "uploadpack.allowFilter", "true").await;
    // Enable reachable SHA1
    git_config(path, "uploadpack.allowReachableSHA1InWant", "true").await;

    // Install built-in post-receive hook to checkout files after push
    install_checkout_hook(path).await;

    // Copy user hooks from hooks dir if configured (may override built-in)
    if let Some(hooks_dir) = &config.hooks_dir {
        install_hooks(path, hooks_dir).await;
    }

    Ok(())
}

/// Install a post-receive hook that updates HEAD and checks out working tree files.
async fn install_checkout_hook(repo: &Path) {
    let hooks_dir = if repo.join(".git").exists() {
        repo.join(".git").join("hooks")
    } else {
        repo.join("hooks")
    };
    tokio::fs::create_dir_all(&hooks_dir).await.ok();

    let hook_path = hooks_dir.join("post-receive");
    // Don't overwrite if user already placed a hook
    if hook_path.exists() {
        return;
    }

    let hook_script = r#"#!/bin/sh
# Built-in gitrub hook: update working tree after push
WORK_TREE="$(cd "$(git rev-parse --git-dir)/.." && pwd)"
export GIT_WORK_TREE="$WORK_TREE"
export GIT_DIR="$WORK_TREE/.git"
while read oldrev newrev refname; do
    branch="${refname#refs/heads/}"
    if [ -n "$branch" ]; then
        git symbolic-ref HEAD "$refname"
        git reset --hard
        break
    fi
done
"#;

    if tokio::fs::write(&hook_path, hook_script).await.is_ok() {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            tokio::fs::set_permissions(&hook_path, std::fs::Permissions::from_mode(0o755))
                .await
                .ok();
        }
    }
}

/// Check if a path is a git repo (bare or non-bare).
pub fn is_git_repo(path: &Path) -> bool {
    // Non-bare: has .git/ subdirectory
    if path.join(".git").join("HEAD").exists() {
        return true;
    }
    // Bare: has HEAD and refs at top level
    path.join("HEAD").exists() && path.join("refs").exists()
}

async fn git_config(repo: &Path, key: &str, value: &str) {
    Command::new("git")
        .args(["-C"])
        .arg(repo)
        .args(["config", key, value])
        .output()
        .await
        .ok();
}

async fn install_hooks(repo: &Path, hooks_dir: &Path) {
    // Non-bare repos store hooks in .git/hooks/, bare repos in hooks/
    let dest = if repo.join(".git").exists() {
        repo.join(".git").join("hooks")
    } else {
        repo.join("hooks")
    };
    tokio::fs::create_dir_all(&dest).await.ok();

    let Ok(mut entries) = tokio::fs::read_dir(hooks_dir).await else {
        return;
    };

    while let Ok(Some(entry)) = entries.next_entry().await {
        let src = entry.path();
        if src.is_file() {
            let name = entry.file_name();
            let dst = dest.join(&name);
            if tokio::fs::copy(&src, &dst).await.is_ok() {
                // Make hook executable
                #[cfg(unix)]
                {
                    use std::os::unix::fs::PermissionsExt;
                    tokio::fs::set_permissions(&dst, std::fs::Permissions::from_mode(0o755))
                        .await
                        .ok();
                }
            }
        }
    }
}

/// Run git info/refs advertisement (for both v1 and v2).
pub async fn info_refs(
    repo: &Path,
    service: &str,
    git_protocol: Option<&str>,
) -> Result<(String, Vec<u8>), String> {
    let cmd_name = service.strip_prefix("git-").unwrap_or(service);

    let mut cmd = Command::new("git");
    cmd.arg(cmd_name)
        .args(["--stateless-rpc", "--advertise-refs"])
        .arg(repo);

    // Protocol v2: pass GIT_PROTOCOL env
    if let Some(proto) = git_protocol {
        cmd.env("GIT_PROTOCOL", proto);
    }

    let out = cmd.output().await.map_err(|e| e.to_string())?;

    let content_type = format!("application/x-{}-advertisement", service);

    let mut body = Vec::new();

    if git_protocol.map_or(false, |p| p.contains("version=2")) {
        // Protocol v2: no pkt-line service header needed
        body.extend(&out.stdout);
    } else {
        // Protocol v1: prepend pkt-line service header
        let header = format!("# service={}\n", service);
        let pkt = format!("{:04x}{}", header.len() + 4, header);
        body.extend(pkt.as_bytes());
        body.extend(b"0000");
        body.extend(&out.stdout);
    }

    Ok((content_type, body))
}

/// Run git upload-pack or receive-pack (stateless RPC).
pub async fn run_pack(
    repo: &Path,
    service: &str,
    input: &[u8],
    git_protocol: Option<&str>,
) -> Result<(String, Vec<u8>), String> {
    let cmd_name = service.strip_prefix("git-").unwrap_or(service);

    let mut cmd = Command::new("git");
    cmd.arg(cmd_name)
        .args(["--stateless-rpc"])
        .arg(repo)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped());

    if let Some(proto) = git_protocol {
        cmd.env("GIT_PROTOCOL", proto);
    }

    let mut child = cmd.spawn().map_err(|e| e.to_string())?;

    let mut stdin = child.stdin.take().unwrap();
    stdin.write_all(input).await.map_err(|e| e.to_string())?;
    drop(stdin);

    let out = child.wait_with_output().await.map_err(|e| e.to_string())?;

    let content_type = format!("application/x-{}-result", service);
    Ok((content_type, out.stdout))
}

/// Run git upload-pack or receive-pack directly (for SSH, non-stateless).
/// Returns the child process for piping.
pub async fn spawn_git(
    repo: &Path,
    command: &str,
) -> Result<tokio::process::Child, String> {
    let cmd_name = command.strip_prefix("git-").unwrap_or(command);

    Command::new("git")
        .arg(cmd_name)
        .arg(repo)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|e| format!("Failed to spawn git {}: {}", cmd_name, e))
}

/// Run git archive and return the archive bytes.
pub async fn archive(repo: &Path, tree: &str, format: &str) -> Result<Vec<u8>, String> {
    let out = Command::new("git")
        .args(["-C"])
        .arg(repo)
        .args(["archive", "--format", format, tree])
        .output()
        .await
        .map_err(|e| e.to_string())?;

    if !out.status.success() {
        return Err(format!(
            "git archive failed: {}",
            String::from_utf8_lossy(&out.stderr)
        ));
    }

    Ok(out.stdout)
}

/// Run git-upload-archive for SSH transport.
pub async fn spawn_upload_archive(repo: &Path) -> Result<tokio::process::Child, String> {
    Command::new("git")
        .arg("upload-archive")
        .arg(repo)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|e| format!("Failed to spawn git upload-archive: {}", e))
}