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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
use std::path::PathBuf;
use std::sync::Arc;
use tokio::net::TcpListener;

use gitrub::http;
use gitrub::ssh;
use gitrub::Config;

const VERSION: &str = env!("CARGO_PKG_VERSION");

// ---------------------------------------------------------------------------
// Help text
// ---------------------------------------------------------------------------

fn print_main_help() {
    eprintln!(
        "\
gitrub {VERSION} — a local git server

USAGE:
    gitrub [OPTIONS]              Launch TUI (default) and auto-start server
    gitrub --notui [OPTIONS]      Headless mode (no TUI)
    gitrub help <command>         Show detailed help

OPTIONS:
    --root <DIR>       Repository root                  [default: .]
    --host <ADDR>      Bind address                     [default: 0.0.0.0]
    --port <PORT>      HTTP port                        [default: 3000]
    --ssh-port <PORT>  SSH port                         [default: 2222]
    --user <USER>      Username for auth
    --pass <PASS>      Password for auth
    --noauth           Disable authentication
    --hooks-dir <DIR>  Hook scripts directory
    --no-ssh           Disable SSH server
    --recursive        List repos recursively (nested paths)
    --notui            Headless mode (no interactive UI)

QUICKSTART:
    gitrub --noauth
    git clone http://localhost:3000/myproject.git"
    );
}

fn print_serve_help() {
    eprintln!(
        "\
gitrub serve — start the git server

USAGE:
    gitrub serve [OPTIONS]

AUTHENTICATION (one required):
    --user <USER>       Username for HTTP Basic / SSH password auth
    --pass <PASS>       Password (must be used with --user)
    --noauth            Disable authentication entirely

NETWORK:
    --host <ADDR>       Bind address                    [default: 0.0.0.0]
    --port <PORT>       HTTP port                       [default: 3000]
    --ssh-port <PORT>   SSH port                        [default: 2222]
    --no-ssh            Disable the built-in SSH server

STORAGE:
    --root <DIR>        Root directory for bare repos   [default: .]
    --recursive         List repos recursively (include nested paths)

HOOKS:
    --hooks-dir <DIR>   Directory of hook scripts to copy into every new repo.
                        Typical hooks: pre-receive, post-receive, update.
                        Scripts must be executable.

EXAMPLES:
    # Minimal — no auth, default ports
    gitrub serve --noauth

    # With auth
    gitrub serve --user admin --pass secret

    # Custom everything
    gitrub serve --user deploy --pass s3cret \\
                 --host 0.0.0.0 --port 8080 --ssh-port 2222 \\
                 --root /srv/git --hooks-dir /etc/gitrub/hooks

    # HTTP only, no SSH
    gitrub serve --noauth --no-ssh

CLONE / PUSH / PULL (after the server is running):

    # HTTP (no auth)
    git clone http://localhost:3000/org/project.git

    # HTTP (with auth — credentials in URL)
    git clone http://admin:secret@localhost:3000/org/project.git

    # SSH
    git clone ssh://git@localhost:2222/org/project.git

    # Push a new project (repo auto-creates on first push)
    cd my-project
    git init && git add . && git commit -m 'init'
    git remote add origin http://localhost:3000/me/my-project.git
    git push -u origin main

    # Switch an existing repo from GitHub
    git remote set-url origin http://localhost:3000/me/project.git
    git push --mirror

SHALLOW & PARTIAL CLONES:
    git clone --depth 1 http://localhost:3000/org/project.git
    git clone --filter=blob:none http://localhost:3000/org/project.git

ARCHIVE DOWNLOADS (HTTP only):
    curl -LO http://localhost:3000/org/project.git/archive/main.tar.gz
    curl -LO http://localhost:3000/org/project.git/archive/v1.0.zip
    curl -LO http://localhost:3000/org/project.git/archive/main.tar

GIT LFS:
    cd my-project
    git lfs install
    git lfs track '*.bin' '*.zip'
    git add .gitattributes
    git commit -m 'track large files with LFS'
    git push

    LFS objects are stored under <root>/<repo>/lfs/objects/.

SERVER-SIDE HOOKS:
    Create a directory with executable hook scripts:

        mkdir hooks
        cat > hooks/post-receive << 'HOOK'
        #!/bin/sh
        echo \"Push received on $(date)\"
        HOOK
        chmod +x hooks/post-receive

    Then start the server with --hooks-dir:

        gitrub serve --noauth --hooks-dir ./hooks

    Every new repo gets these hooks copied in. Supported hooks include
    pre-receive, update, post-receive, and any other git hook.

PROTOCOL V2:
    Protocol v2 is supported automatically. Clients that send the
    Git-Protocol header get v2 responses. Force it with:

        git -c protocol.version=2 clone http://localhost:3000/org/project.git

SSH DETAILS:
    The built-in SSH server generates an Ed25519 host key on first run,
    saved to <root>/.host_key. Clients authenticate with the same
    --user/--pass credentials. On first connect you will need to accept
    the host key:

        ssh-keyscan -p 2222 localhost >> ~/.ssh/known_hosts

    Then clone/push/pull as usual:

        git clone ssh://admin@localhost:2222/org/project.git"
    );
}

fn print_tui_help() {
    eprintln!(
        "\
gitrub tui — interactive terminal UI

USAGE:
    gitrub tui [OPTIONS]

OPTIONS:
    --root <DIR>        Root directory for repos         [default: .]
    --host <ADDR>       Bind address                     [default: 0.0.0.0]
    --port <PORT>       HTTP port                        [default: 3000]
    --ssh-port <PORT>   SSH port                         [default: 2222]
    --user <USER>       Username (pre-fill auth fields)
    --pass <PASS>       Password (pre-fill auth fields)
    --hooks-dir <DIR>   Pre-fill hooks directory
    --recursive         List repos recursively (include nested paths)

    All settings can be changed interactively in the TUI.

KEYBINDINGS:
    Tab         Switch focus between Settings and Repos
    ↑ / ↓       Navigate settings or repo list
    Enter       Edit selected setting (or toggle on/off fields)
    /           Search / filter repos
    s           Start or stop the server
    r           Refresh repo list
    PgUp/PgDn   Scroll repos by page
    Home/End    Jump to first/last repo
    q           Quit
    Ctrl-C      Force quit

DESCRIPTION:
    The TUI lets you browse repos, change server config, and
    start/stop the server — all from one screen.

    Settings are editable only when the server is stopped.
    Press Enter on a field to edit it, or toggle Auth/SSH on/off.
    Press 's' to start the server with current settings.

EXAMPLES:
    # Launch with defaults
    gitrub tui

    # Launch pointed at a specific root
    gitrub tui --root /srv/git

    # Pre-fill auth
    gitrub tui --root ./repos --user admin --pass secret"
    );
}

fn print_help_for(command: &str) {
    match command {
        "serve" => print_serve_help(),
        "tui" => print_tui_help(),
        "help" => {
            eprintln!("Usage: gitrub help <command>");
            eprintln!();
            eprintln!("Available commands: serve, tui");
        }
        other => {
            eprintln!("Unknown command: {}", other);
            eprintln!();
            print_main_help();
        }
    }
}

// ---------------------------------------------------------------------------
// Arg parsing
// ---------------------------------------------------------------------------

fn parse_serve_args(args: &[String]) -> Config {
    let mut root = String::from(".");
    let mut host = String::from("0.0.0.0");
    let mut port: u16 = 3000;
    let mut ssh_port: u16 = 2222;
    let mut user: Option<String> = None;
    let mut pass: Option<String> = None;
    let mut noauth = false;
    let mut hooks_dir: Option<PathBuf> = None;
    let mut enable_ssh = true;
    let mut recursive = false;

    let mut i = 0;
    while i < args.len() {
        match args[i].as_str() {
            "--root" => {
                i += 1;
                root = args.get(i).cloned().unwrap_or_else(|| {
                    eprintln!("Error: --root requires a value");
                    std::process::exit(1);
                });
            }
            "--host" => {
                i += 1;
                host = args.get(i).cloned().unwrap_or_else(|| {
                    eprintln!("Error: --host requires a value");
                    std::process::exit(1);
                });
            }
            "--port" => {
                i += 1;
                port = args
                    .get(i)
                    .and_then(|s| s.parse().ok())
                    .unwrap_or_else(|| {
                        eprintln!("Error: --port requires a valid number");
                        std::process::exit(1);
                    });
            }
            "--ssh-port" => {
                i += 1;
                ssh_port = args
                    .get(i)
                    .and_then(|s| s.parse().ok())
                    .unwrap_or_else(|| {
                        eprintln!("Error: --ssh-port requires a valid number");
                        std::process::exit(1);
                    });
            }
            "--user" => {
                i += 1;
                user = Some(args.get(i).cloned().unwrap_or_else(|| {
                    eprintln!("Error: --user requires a value");
                    std::process::exit(1);
                }));
            }
            "--pass" => {
                i += 1;
                pass = Some(args.get(i).cloned().unwrap_or_else(|| {
                    eprintln!("Error: --pass requires a value");
                    std::process::exit(1);
                }));
            }
            "--noauth" => noauth = true,
            "--hooks-dir" => {
                i += 1;
                hooks_dir = Some(PathBuf::from(args.get(i).cloned().unwrap_or_else(|| {
                    eprintln!("Error: --hooks-dir requires a value");
                    std::process::exit(1);
                })));
            }
            "--no-ssh" => enable_ssh = false,
            "--recursive" => recursive = true,
            "--help" | "-h" => {
                print_serve_help();
                std::process::exit(0);
            }
            other => {
                eprintln!("Error: unknown option '{}'\n", other);
                eprintln!("Run 'gitrub help serve' for usage.");
                std::process::exit(1);
            }
        }
        i += 1;
    }

    // Validate auth
    if noauth {
        user = None;
        pass = None;
    } else if user.is_none() && pass.is_none() {
        eprintln!("Error: must provide --user and --pass, or use --noauth\n");
        eprintln!("Run 'gitrub help serve' for usage.");
        std::process::exit(1);
    } else if user.is_some() != pass.is_some() {
        eprintln!("Error: --user and --pass must both be set\n");
        eprintln!("Run 'gitrub help serve' for usage.");
        std::process::exit(1);
    }

    // Validate hooks dir
    if let Some(ref dir) = hooks_dir {
        if !dir.is_dir() {
            eprintln!("Error: hooks directory does not exist: {}", dir.display());
            std::process::exit(1);
        }
    }

    // Ensure root exists
    std::fs::create_dir_all(&root).ok();
    let root = PathBuf::from(&root)
        .canonicalize()
        .expect("Cannot resolve root path");

    Config {
        root,
        host,
        port,
        ssh_port,
        user,
        pass,
        hooks_dir,
        enable_ssh,
        recursive,
    }
}

// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------

#[tokio::main]
async fn main() {
    let args: Vec<String> = std::env::args().collect();

    // Check for subcommands first
    if let Some(cmd) = args.get(1).map(|s| s.as_str()) {
        match cmd {
            "--help" | "-h" => {
                print_main_help();
                std::process::exit(0);
            }
            "--version" | "-V" => {
                println!("gitrub {}", VERSION);
                return;
            }
            "help" => {
                let topic = args.get(2).map(|s| s.as_str()).unwrap_or("help");
                print_help_for(topic);
                return;
            }
            // Legacy subcommands still work
            "serve" => {
                let config = Arc::new(parse_serve_args(&args[2..]));
                run_server(config).await;
                return;
            }
            "tui" => {
                run_unified(&args[2..], false).await;
                return;
            }
            _ => {}
        }
    }

    // Default: parse all args as unified options (TUI is default)
    run_unified(&args[1..], false).await;
}

async fn run_server(config: Arc<Config>) {
    let listener = TcpListener::bind((&*config.host, config.port))
        .await
        .unwrap_or_else(|e| {
            eprintln!(
                "Error: cannot bind to {}:{}{}",
                config.host, config.port, e
            );
            std::process::exit(1);
        });

    println!("gitrub {VERSION} — local git server");
    println!();
    let bind_all = config.host == "0.0.0.0" || config.host == "::";
    if bind_all {
        println!("  Listening on:");
        for ip in gitrub::local_ips() {
            print!("    http://{}:{}", ip, config.port);
            if config.enable_ssh {
                print!("  ssh://{}:{}", ip, config.ssh_port);
            }
            println!();
        }
    } else {
        print!("  HTTP:   http://{}:{}", config.host, config.port);
        if config.enable_ssh {
            print!("  SSH:    ssh://{}:{}", config.host, config.ssh_port);
        }
        println!();
    }
    if config.user.is_some() {
        println!(
            "  Auth:   enabled (user: {})",
            config.user.as_deref().unwrap()
        );
    } else {
        println!("  Auth:   disabled (--noauth)");
    }
    println!("  Root:   {}", config.root.display());
    if let Some(ref dir) = config.hooks_dir {
        println!("  Hooks:  {}", dir.display());
    }
    println!();

    // List repos asynchronously while the server starts
    let list_config = config.clone();
    tokio::spawn(async move {
        http::list_repos(&list_config.root, &list_config.host, list_config.port, list_config.recursive).await;
    });

    // Start SSH server in background
    if config.enable_ssh {
        let ssh_config = config.clone();
        let (_shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(false);
        tokio::spawn(async move {
            if let Err(e) = ssh::serve(ssh_config, shutdown_rx).await {
                eprintln!("SSH server error: {}", e);
            }
        });
    }

    // HTTP server (main loop)
    http::serve(listener, config).await;
}

async fn run_unified(args: &[String], notui_from_caller: bool) {
    let mut root = String::from(".");
    let mut host = String::from("0.0.0.0");
    let mut port: u16 = 3000;
    let mut ssh_port: u16 = 2222;
    let mut user: Option<String> = None;
    let mut pass: Option<String> = None;
    let mut hooks_dir: Option<PathBuf> = None;
    let mut enable_ssh = true;
    let mut noauth = false;
    let mut notui = notui_from_caller;
    let mut recursive = false;

    let mut i = 0;
    while i < args.len() {
        match args[i].as_str() {
            "--root" => {
                i += 1;
                root = args.get(i).cloned().unwrap_or_else(|| {
                    eprintln!("Error: --root requires a value");
                    std::process::exit(1);
                });
            }
            "--host" => {
                i += 1;
                host = args.get(i).cloned().unwrap_or_else(|| {
                    eprintln!("Error: --host requires a value");
                    std::process::exit(1);
                });
            }
            "--port" => {
                i += 1;
                port = args
                    .get(i)
                    .and_then(|s| s.parse().ok())
                    .unwrap_or_else(|| {
                        eprintln!("Error: --port requires a valid number");
                        std::process::exit(1);
                    });
            }
            "--ssh-port" => {
                i += 1;
                ssh_port = args
                    .get(i)
                    .and_then(|s| s.parse().ok())
                    .unwrap_or_else(|| {
                        eprintln!("Error: --ssh-port requires a valid number");
                        std::process::exit(1);
                    });
            }
            "--user" => {
                i += 1;
                user = Some(args.get(i).cloned().unwrap_or_else(|| {
                    eprintln!("Error: --user requires a value");
                    std::process::exit(1);
                }));
            }
            "--pass" => {
                i += 1;
                pass = Some(args.get(i).cloned().unwrap_or_else(|| {
                    eprintln!("Error: --pass requires a value");
                    std::process::exit(1);
                }));
            }
            "--hooks-dir" => {
                i += 1;
                hooks_dir = Some(PathBuf::from(args.get(i).cloned().unwrap_or_else(|| {
                    eprintln!("Error: --hooks-dir requires a value");
                    std::process::exit(1);
                })));
            }
            "--noauth" => noauth = true,
            "--no-ssh" => enable_ssh = false,
            "--recursive" => recursive = true,
            "--notui" => notui = true,
            "--help" | "-h" => {
                print_main_help();
                std::process::exit(0);
            }
            other => {
                eprintln!("Error: unknown option '{}'\n", other);
                print_main_help();
                std::process::exit(1);
            }
        }
        i += 1;
    }

    // Validate auth
    if noauth {
        user = None;
        pass = None;
    } else if !notui {
        // TUI mode: auth is optional, can be configured in the UI
    } else if user.is_none() && pass.is_none() {
        eprintln!("Error: must provide --user and --pass, or use --noauth\n");
        print_main_help();
        std::process::exit(1);
    } else if user.is_some() != pass.is_some() {
        eprintln!("Error: --user and --pass must both be set\n");
        print_main_help();
        std::process::exit(1);
    }

    std::fs::create_dir_all(&root).ok();

    if notui {
        // Headless mode — same as old `serve`
        let root = PathBuf::from(&root)
            .canonicalize()
            .expect("Cannot resolve root path");

        if let Some(ref dir) = hooks_dir {
            if !dir.is_dir() {
                eprintln!("Error: hooks directory does not exist: {}", dir.display());
                std::process::exit(1);
            }
        }

        let config = Arc::new(Config {
            root,
            host,
            port,
            ssh_port,
            user,
            pass,
            hooks_dir,
            enable_ssh,
            recursive,
        });
        run_server(config).await;
    } else {
        // TUI mode with auto-start
        if let Err(e) = gitrub::tui::run(
            root, host, port, ssh_port, user, pass, hooks_dir, enable_ssh, noauth, recursive,
        )
        .await
        {
            eprintln!("TUI error: {}", e);
            std::process::exit(1);
        }
    }
}