-
Notifications
You must be signed in to change notification settings - Fork 2
/
mirror_git.go
79 lines (67 loc) · 1.43 KB
/
mirror_git.go
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
package gitdump
import (
"context"
"log"
"net/url"
"os"
"os/exec"
"github.com/yankeguo/rg"
)
type MirrorGitOptions struct {
Dir string
URL string
Username string
AskPassFile string
}
func MirrorGit(ctx context.Context, opts MirrorGitOptions) (err error) {
defer rg.Guard(&err)
var stat os.FileInfo
if stat, err = os.Stat(opts.Dir); err != nil {
if os.IsNotExist(err) {
err = nil
} else {
log.Println("failed checking directory:", opts.Dir)
return
}
} else if !stat.IsDir() {
log.Println("not a directory, deleting:", opts.Dir)
rg.Must0(os.RemoveAll(opts.Dir))
stat = nil
}
if stat == nil {
log.Println("creating directory:", opts.Dir)
rg.Must0(os.MkdirAll(opts.Dir, 0755))
log.Println("initializing git repository:", opts.Dir)
{
cmd := exec.CommandContext(ctx, "git", "init", "--bare")
cmd.Dir = opts.Dir
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
rg.Must0(cmd.Run())
}
}
// embed username in URL
upstream := rg.Must(url.Parse(opts.URL))
if upstream.User == nil {
upstream.User = url.User(opts.Username)
}
// fetch all refs
{
cmd := exec.CommandContext(
ctx,
"git",
"fetch",
"-t",
"-f",
upstream.String(),
"+refs/*:refs/*",
)
cmd.Env = append(os.Environ(), "GIT_ASKPASS="+opts.AskPassFile)
cmd.Dir = opts.Dir
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
rg.Must0(cmd.Run())
}
log.Println("done:", opts.URL)
return
}