/
main.go
132 lines (117 loc) · 2.65 KB
/
main.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
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
// Command ghbackup is a super simple github repository backup script.
package main
import (
"context"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/config"
"github.com/google/go-github/v31/github"
"github.com/pkg/errors"
"golang.org/x/oauth2"
)
type refreshJob struct {
repo string
dest string
}
func cloneOrFetch(job refreshJob) error {
_, err := os.Stat(job.dest)
if err != nil {
if !os.IsNotExist(err) {
return errors.WithStack(err)
}
_, err = git.PlainClone(job.dest, true, &git.CloneOptions{
URL: job.repo,
})
return errors.WithStack(err)
}
repo, err := git.PlainOpen(job.dest)
if err != nil {
return errors.WithStack(err)
}
err = repo.Fetch(&git.FetchOptions{
RefSpecs: []config.RefSpec{
"+refs/heads/master:refs/heads/master",
"+refs/heads/*:refs/remotes/origin/*",
},
})
if err != nil && err != git.NoErrAlreadyUpToDate {
return errors.WithStack(err)
}
return nil
}
func refresh(wg *sync.WaitGroup, jobs chan refreshJob) {
defer wg.Done()
for job := range jobs {
if err := cloneOrFetch(job); err != nil {
fmt.Fprintf(os.Stderr, "for repo %q: %+v\n", job.repo, err)
}
}
}
func run() error {
fs := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
token := fs.String("token", "", "github token")
parallel := fs.Int("parallel", 5, "number of repositories to clone in parallel")
dest := fs.String("dest", "", "destination directory")
filter := fs.String("filter", "", "filter by repository name")
_ = fs.Parse(os.Args[1:])
if *token == "" {
return errors.New("-token must be provided")
}
if *dest == "" {
return errors.New("-dest must be provided")
}
jobs := make(chan refreshJob, *parallel*10)
var wg sync.WaitGroup
wg.Add(*parallel)
for i := 0; i < *parallel; i++ {
go refresh(&wg, jobs)
}
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{
AccessToken: *token,
},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
page := 0
for {
opts := github.RepositoryListOptions{
Affiliation: "owner",
ListOptions: github.ListOptions{
Page: page,
},
}
repos, resp, err := client.Repositories.List(ctx, "", &opts)
if err != nil {
return errors.WithStack(err)
}
for _, repo := range repos {
if *filter != "" && !strings.Contains(*repo.Name, *filter) {
continue
}
jobs <- refreshJob{
repo: *repo.SSHURL,
dest: filepath.Join(*dest, *repo.Name),
}
}
if resp.NextPage == 0 {
break
}
page = resp.NextPage
}
close(jobs)
wg.Wait()
return nil
}
func main() {
if err := run(); err != nil {
fmt.Fprintf(os.Stderr, "%+v\n", err)
os.Exit(1)
}
}