-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
197 lines (180 loc) · 4.58 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
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"text/template"
kingpin "gopkg.in/alecthomas/kingpin.v2"
)
var (
dir = kingpin.Flag("dir", "The name of the directory to clone into").Short('d').Default(".").String()
dryRun = kingpin.Flag("dry-run", "Dry run").Bool()
reposFile = kingpin.Flag("file", "Repo is GitHub classroom repo").Short('f').ExistingFile()
classroom = kingpin.Flag("classroom", "Repo is GitHub classroom repo").Bool()
jobs = kingpin.Flag("jobs", "The number of repos fetched at the same time").Short('j').Default("8").Int()
verbose = kingpin.Flag("verbose", "Verbose").Bool()
mrconfig = kingpin.Flag("mrconfig", "Create a myrepos .mrconfig file in the output directory").Default("true").Bool()
nwo = kingpin.Arg("repo", "GitHub owner/repo").String()
repoRE = regexp.MustCompile(`^(?:https://github\.com/)?([^/]+)/([^/]+)$`)
)
func main() {
kingpin.Parse()
switch {
case *reposFile == "" && *nwo == "":
kingpin.FatalUsage("repo is a required argument")
case *reposFile != "" && *nwo != "":
kingpin.FatalUsage("--file and repo are exclusive")
case *nwo != "":
m := repoRE.FindStringSubmatch(*nwo)
if m == nil {
kingpin.FatalUsage("repo must be in the format owner/repo")
}
owner, name := m[1], m[2]
kingpin.FatalIfError(run(owner, name), "")
case *reposFile != "":
kingpin.FatalIfError(runWithFiles(*reposFile), "")
}
}
type repoEntry struct {
Dir, URL string
}
func runWithFiles(reposFile string) error {
dat, err := ioutil.ReadFile(reposFile)
if err != nil {
return err
}
var entries []repoEntry
re := regexp.MustCompile(`(?m)^(?:https://github\.com/)?([^/]+)/(.+?)(?:\.git)?\s*(?:#.*)?$`)
for _, m := range re.FindAllStringSubmatch(string(dat), -1) {
entries = append(entries, repoEntry{Dir: m[1], URL: strings.TrimSpace(m[0])})
}
if err := cloneRepos(entries, *dir); err != nil {
return err
}
if *mrconfig {
if err := writeMrConfig(entries, *dir); err != nil {
return err
}
}
return nil
}
func run(owner, name string) error {
repos, err := queryRepos(owner, name)
if err != nil {
return err
}
if len(repos) == 0 {
prep := "with"
if *classroom {
prep = "without"
}
fmt.Fprintf(os.Stderr, "No entries. Try again %s the --classroom option.\n", prep)
return nil
}
var entries []repoEntry
for _, repo := range repos {
entries = append(entries, repoEntry{Dir: repoAuthor(repo, name), URL: repo.URL})
}
if err := cloneRepos(entries, *dir); err != nil {
return err
}
if *mrconfig {
return writeMrConfig(entries, *dir)
}
return nil
}
func queryRepos(owner, name string) ([]repoRecord, error) {
client, err := newClient()
if err != nil {
return nil, err
}
switch *classroom {
case true:
return client.queryOrgRepos(owner, name)
default:
return client.queryRepoForks(owner, name)
}
}
func repoAuthor(repo repoRecord, name string) string {
switch *classroom {
case true:
return repo.Name[len(name)+1:]
default:
return repo.Owner
}
}
func cloneRepos(repos []repoEntry, dir string) error {
if !*dryRun {
if err := os.MkdirAll(dir, 0700); err != nil {
return err
}
}
var (
sem = make(chan bool, *jobs)
errors = make(chan error, 1)
outputs = make(chan []byte, 1)
)
for _, repo := range repos {
go func(repo repoEntry) {
sem <- true
defer func() { <-sem }()
args := []string{"git", "clone", repo.URL, repo.Dir}
if *dryRun {
args = append([]string{"echo"}, args...)
// time.Sleep(time.Second)
}
cmd := exec.Command(args[0], args[1:]...)
cmd.Dir = dir
stdoutStderr, err := cmd.CombinedOutput()
if err != nil {
errors <- fmt.Errorf("%s: %s while trying to clone %s", err, stdoutStderr, repo.URL)
} else {
outputs <- bytes.TrimSpace(stdoutStderr)
}
}(repo)
}
errorCount := 0
for n := len(repos); n > 0; {
select {
case output := <-outputs:
n--
fmt.Printf("%s\n", output)
case err := <-errors:
fmt.Fprintf(os.Stderr, "%s\n", err)
n--
errorCount++
}
}
if errorCount > 0 {
return fmt.Errorf("one or more clones failed")
}
return nil
}
func writeMrConfig(repos []repoEntry, dir string) error {
dst := filepath.Join(dir, ".mrconfig")
f := ioutil.Discard
if *dryRun {
fmt.Println("writing", dst)
} else {
f, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
return err
}
defer f.Close()
}
if *verbose {
mrConfigTpl.Execute(os.Stdout, repos)
}
return mrConfigTpl.Execute(f, repos)
}
var mrConfigTpl = template.Must(template.New("mrconfig").Parse(`
{{- range . -}}
[{{ .Dir }}]
checkout = git clone {{ .URL }} {{ .Dir }}
{{ end -}}
`))