-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
283 lines (264 loc) · 6.94 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
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
package main
import (
"context"
"flag"
"fmt"
"os"
"path/filepath"
"time"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing/transport/http"
"github.com/greboid/go-log"
"github.com/imdario/mergo"
"github.com/kouhin/envflag"
"github.com/shurcooL/githubv4"
"go.uber.org/zap"
"golang.org/x/oauth2"
)
var (
checkoutPath = flag.String("checkoutpath", "/data", "Folder to clone repos into")
skipArchived = flag.Bool("skip-archived", false, "Skip archived repositories after the first run")
authToken = flag.String("authtoken", "", "Personal Access token")
duration = flag.Duration("duration", 0, "Number of seconds between executions")
starred = flag.Bool("starred", false, "Mirror starred repositories")
debug = flag.Bool("debug", false, "Output debug logging")
test = flag.Bool("test", false, "Test run only, don't actually clone/update")
log *zap.SugaredLogger
)
type Mirror struct {
ctx context.Context
client *githubv4.Client
auth *http.BasicAuth
login string
reposToSync map[Repository]bool
}
type ListRepositories struct {
User struct {
Repositories Repositories `graphql:"repositories(first: 100, after: $cursor)"`
} `graphql:"user(login: $login)"`
}
type ListStarredRepositories struct {
User struct {
Repositories Repositories `graphql:"starredRepositories(first: 100, after: $cursor)"`
} `graphql:"user(login: $login)"`
}
type Repositories struct {
PageInfo struct {
EndCursor *githubv4.String
HasNextPage bool
}
Edges []struct {
Node Repository
}
}
type Repository struct {
NameWithOwner string
Url string
Archived bool `graphql:"isArchived"`
}
func main() {
if err := envflag.Parse(); err != nil {
fmt.Printf("Unable to load config: %s\r\n", err.Error())
return
}
if *authToken == "" || *checkoutPath == "" {
flag.Usage()
return
}
log = logger.MustCreateLogger(*debug)
mirror := &Mirror{
ctx: context.Background(),
client: githubv4.NewClient(oauth2.NewClient(context.Background(), oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: *authToken},
))),
auth: &http.BasicAuth{
Username: "authToken", //Anything but blank
Password: *authToken,
},
reposToSync: make(map[Repository]bool),
}
user, err := mirror.getUser()
if err != nil {
log.Fatalf("Unable to get username: %s", err.Error())
return
}
mirror.login = user
if *duration < time.Minute {
if err = mirror.updateOrCloneRepos(); err != nil {
log.Fatalf("Error mirroring repos: %s", err.Error())
}
return
}
for {
log.Infof("Mirroring Repositories every %s", *duration)
if err = mirror.updateOrCloneRepos(); err != nil {
log.Fatalf("Error mirroring repos: %s", err.Error())
}
time.Sleep(*duration)
}
}
func (m *Mirror) updateOrClone(repo Repository) (bool, error) {
if *skipArchived && m.reposToSync[repo] && repo.Archived {
log.Debugf("Skipping sync: %s", repo.Url)
return true, nil
}
if _, err := os.Stat(filepath.Join(*checkoutPath, repo.NameWithOwner)); err == nil {
log.Debugf("Updating: %s", repo.Url)
if !*test {
return false, m.update(repo)
}
return false, nil
} else {
log.Debugf("Cloning: %s", repo.Url)
if !*test {
return false, m.clone(repo)
}
return false, nil
}
}
func (m *Mirror) updateOrCloneRepos() error {
log.Infof("Retrieving repository list")
log.Debugf("Getting normal repositories")
repos := m.getRepos()
err := mergo.Merge(&m.reposToSync, &repos)
if err != nil {
log.Errorf("Unable to merge repos: %s", err.Error())
}
if *starred {
log.Debugf("Getting starred repos")
repos = m.getStarredRepos()
err = mergo.Merge(&m.reposToSync, &repos)
if err != nil {
log.Errorf("Unable to merge starred repos: %s", err.Error())
}
}
log.Infof("Started mirroring %d repositories", len(m.reposToSync))
numSkips := 0
numErrors := 0
for repo := range m.reposToSync {
skipped, err := m.updateOrClone(repo)
if *test || err == nil {
m.reposToSync[repo] = true
} else {
numErrors++
}
if skipped {
numSkips++
}
}
log.Infof("Finished mirroring %d repositories: %d errors, %d skipped", len(m.reposToSync), numErrors, numSkips)
return nil
}
func (m *Mirror) getRepos() map[Repository]bool {
q := ListRepositories{}
variables := map[string]interface{}{
"login": githubv4.String(m.login),
"cursor": (*githubv4.String)(nil),
}
allRepos := make(map[Repository]bool)
for {
err := m.client.Query(m.ctx, &q, variables)
if err != nil {
log.Errorf("Unable to query for repositories: %s", err.Error())
return nil
}
for index := range q.User.Repositories.Edges {
allRepos[q.User.Repositories.Edges[index].Node] = false
}
if !q.User.Repositories.PageInfo.HasNextPage {
break
}
variables["cursor"] = q.User.Repositories.PageInfo.EndCursor
}
return allRepos
}
func (m *Mirror) getStarredRepos() map[Repository]bool {
q := ListStarredRepositories{}
variables := map[string]interface{}{
"login": githubv4.String(m.login),
"cursor": (*githubv4.String)(nil),
}
allRepos := make(map[Repository]bool)
for {
err := m.client.Query(m.ctx, &q, variables)
if err != nil {
log.Errorf("Unable to query for repositories: %s", err.Error())
return nil
}
for index := range q.User.Repositories.Edges {
allRepos[q.User.Repositories.Edges[index].Node] = false
}
if !q.User.Repositories.PageInfo.HasNextPage {
break
}
variables["cursor"] = q.User.Repositories.PageInfo.EndCursor
}
return allRepos
}
func (m *Mirror) clone(repo Repository) error {
_, err := git.PlainClone(filepath.Join(*checkoutPath, repo.NameWithOwner), false, &git.CloneOptions{
URL: repo.Url,
Tags: git.AllTags,
Auth: m.auth,
})
if err != nil {
log.Errorf("Error cloning: %s: %s", repo.NameWithOwner, err)
return err
}
return nil
}
func (m *Mirror) update(repo Repository) error {
gitRepo, err := git.PlainOpen(filepath.Join(*checkoutPath, repo.NameWithOwner))
if err != nil {
log.Errorf("Open error: %s: %s", repo.NameWithOwner, err)
return err
}
workTree, err := gitRepo.Worktree()
if err != nil {
log.Errorf("Worktree error: %s: %s", repo.NameWithOwner, err)
return err
}
err = gitRepo.Fetch(&git.FetchOptions{
Tags: git.AllTags,
Force: true,
Auth: m.auth,
})
if err != nil && err == git.NoErrAlreadyUpToDate {
return nil
}
if err != nil && err != git.NoErrAlreadyUpToDate {
log.Errorf("Fetch error: %s: %s", repo.NameWithOwner, err)
return err
}
err = workTree.Pull(&git.PullOptions{
Force: true,
Auth: m.auth,
})
if err == nil {
return nil
}
if err != git.ErrNonFastForwardUpdate {
log.Errorf("Pull error: %s: %s", repo.NameWithOwner, err)
return err
}
err = workTree.Reset(&git.ResetOptions{
Mode: git.HardReset,
})
if err != nil {
log.Errorf("Reset error: %s: %s", repo.NameWithOwner, err)
return err
}
return nil
}
func (m *Mirror) getUser() (string, error) {
var q struct {
Viewer struct {
Login string
}
}
err := m.client.Query(context.Background(), &q, nil)
if err != nil {
return "", err
}
return q.Viewer.Login, nil
}