-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
262 lines (212 loc) · 5.43 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
package main
import (
"flag"
"fmt"
"log"
"net/url"
"os"
"path"
"strings"
"sync"
"time"
"code.google.com/p/goauth2/oauth"
"github.com/google/go-github/github"
"github.com/libgit2/git2go"
)
var VERSION = "dev" // set correctly by the linker (e.g. go build -ldflags "-X main.VERSION <semver>")
var (
cacheFile = flag.String("cache", "", "The access token cache file.")
accessToken = flag.String("token", "", "The OAuth access token.")
backupDir = flag.String("to", ".", "The base directory for repository backups.")
verbose = flag.Bool("verbose", false, "Be verbose.")
showVersion = flag.Bool("version", false, "Print version and exit")
showHelp = flag.Bool("help", false, "Print usage and exit")
credentialsCallback git.CredentialsCallback
)
func init() {
const usageMsg = `
DESCRIPTION
Backup GitHub repositories. All access to GitHub will use OAuth tokens. username/password authentication is not supported.
OPTIONS
-help
Print usage and exit
-token TOKEN
use TOKEN for the token instead of the value in the token cache file.
-cache FILE
if given a token (-token TOKEN), write its value into FILE. When -token is not used, read the token to use from FILE.
-to DIR
use DIR as the base directory for backups. Defaults to the current directory.
-verbose
Be verbose: log results for each repository.
-version
Print version and exit.
`
flag.Parse()
if *showHelp {
fmt.Print(usageMsg)
os.Exit(0)
}
if *showVersion {
fmt.Println(VERSION)
os.Exit(0)
}
if *accessToken == "" && *cacheFile == "" {
flag.Usage()
os.Exit(2)
}
if *backupDir == flag.Lookup("to").DefValue {
wd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
*backupDir = wd
}
}
func feedRepositoryQueue(client *github.Client, queue chan github.Repository, log chan string) {
defer close(queue)
opt := &github.RepositoryListOptions{}
for {
repos, resp, err := client.Repositories.List("", opt)
if err != nil {
log <- err.Error()
break
}
if opt.Page == 0 && len(repos) == 0 {
log <- "No user repositories available"
break
} else {
for _, repo := range repos {
queue <- repo
}
if resp.NextPage != 0 {
opt.Page = resp.NextPage
} else {
break
}
}
}
orgs, _, err := client.Organizations.List("", &github.ListOptions{})
if err != nil {
log <- err.Error()
}
for _, org := range orgs {
opt := &github.RepositoryListByOrgOptions{Type: "all"}
for {
repos, resp, err := client.Repositories.ListByOrg(*org.Login, opt)
if err != nil {
log <- err.Error()
break
}
if opt.Page == 0 && len(repos) == 0 {
log <- fmt.Sprintf("no %s repositories available", *org.Login)
break
} else {
for _, repo := range repos {
queue <- repo
}
if resp.NextPage != 0 {
opt.Page = resp.NextPage
} else {
break
}
}
}
}
}
func processQueue(queue chan github.Repository, verboseLog chan string, done chan int) {
wg := sync.WaitGroup{}
for repo := range queue {
wg.Add(1)
go func(repo github.Repository) {
remote, err := url.Parse(*repo.CloneURL)
if err != nil {
log.Println(*repo.Name, err)
} else {
verboseLog <- fmt.Sprintf("checking %s", remote.Path[1:])
mirrorPathSegments := make([]string, 0, 4)
mirrorPathSegments = append(mirrorPathSegments, *backupDir)
host := strings.Split(remote.Host, ":")[0] // strip off the port portion if it's there.
mirrorPathSegments = append(mirrorPathSegments, host)
mirrorPathSegments = append(mirrorPathSegments, strings.Split(remote.Path, "/")...)
mirrorPath := path.Join(mirrorPathSegments...)
mirror := NewMirror(mirrorPath, *remote, credentialsCallback)
err = mirror.Fetch()
if err != nil {
log.Println(remote.Path, err)
} else {
verboseLog <- fmt.Sprintf("%s complete", remote.Path[1:])
}
}
wg.Done()
}(repo)
}
wg.Wait()
done <- 1
}
func main() {
var (
err error
token *oauth.Token
transport *oauth.Transport
cache oauth.Cache
)
config := &oauth.Config{}
if *accessToken == "" {
cache = oauth.CacheFile(*cacheFile)
token, err = cache.Token()
if err != nil {
log.Fatal(err)
}
if *verbose {
log.Println("Token is cached in", cache)
}
} else {
token = &oauth.Token{AccessToken: *accessToken}
if *cacheFile != "" {
cache = oauth.CacheFile(*cacheFile)
cache.PutToken(token)
}
}
transport = &oauth.Transport{Config: config}
transport.Token = token
client := github.NewClient(transport.Client())
user, _, err := client.Users.Get("")
if err != nil {
log.Fatal(err)
}
if *verbose {
log.Println("Retrieving information from GitHub using credentials of", *user.Login)
}
credentialsCallback = func(url string, username_from_url string, allowed_type git.CredType) (int, *git.Cred) {
log.Println(username_from_url)
i, c := git.NewCredUserpassPlaintext(*user.Login, token.AccessToken)
return i, &c
}
msgQueue := make(chan string)
queue := make(chan github.Repository)
done := make(chan int)
go func(verbose bool, c chan string) {
select {
case msg := <-c:
if verbose {
log.Println(msg)
}
}
}(*verbose, msgQueue)
go feedRepositoryQueue(client, queue, msgQueue)
go processQueue(queue, msgQueue, done)
for {
select {
case <-time.After(2 * time.Second):
if !*verbose {
os.Stderr.WriteString(".")
}
case msg := <-msgQueue:
if *verbose {
log.Println(msg)
}
case <-done:
return
}
}
}