-
Notifications
You must be signed in to change notification settings - Fork 2
/
config.go
238 lines (193 loc) · 4.89 KB
/
config.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
package main
import (
"crypto/sha1"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
"strings"
"sync"
"time"
)
type (
mirror struct {
cacheDir string
cleanupCacheDir bool
concurrentJobs int
jsonListFile string
srcKey string
dstKey string
refs refs
repoList []repo
}
repo struct {
dir string
src string
dst string
}
refs []string
)
func (r *refs) String() string {
return "refs"
}
func (r *refs) Set(value string) error {
*r = append(*r, value)
return nil
}
// git exec helper
func runGitCommand(dir string, args ...string) error {
cmd := exec.Command("git", args...)
cmd.Dir = dir
if output, err := cmd.CombinedOutput(); err != nil {
return errors.New(string(output))
}
return nil
}
// perform repository mirroring
func (r *repo) sync(cacheDir string, cleanupOnSuccess bool, refs *refs) error {
var scenario [][]string
// check if repository exists
_, s := os.Stat(path.Join(r.dir, "HEAD"))
if os.IsNotExist(s) {
if err := runGitCommand(cacheDir, "clone", "--mirror", r.src, r.dir); err != nil {
return err
}
} else {
scenario = append(scenario, []string{r.dir, "fetch", "-p", "origin"})
}
if len(*refs) > 0 {
runGitCommand(r.dir, "config", "--unset-all", "remote.origin.push")
for _, ref := range *refs {
refSpec := fmt.Sprintf("+refs/%s/*:refs/%s/*", ref, ref)
scenario = append(scenario, []string{r.dir, "config", "--add", "remote.origin.push", refSpec})
}
}
// add rest of commands..
scenario = append(scenario, [][]string{
{r.dir, "symbolic-ref", "HEAD", "refs/heads/master"},
{r.dir, "remote", "set-url", "origin", "--push", r.dst},
{r.dir, "push", "--mirror"},
}...)
for _, args := range scenario {
if err := runGitCommand(args[0], args[1:]...); err != nil {
return err
}
}
if cleanupOnSuccess {
return os.RemoveAll(r.dir)
}
return nil
}
// parse and validate provided command line arguments
func parseCommandLine() (mirror, error) {
var helpRequested bool
cfg := mirror{}
flag.Usage = func() {
fmt.Printf("Usage: %s ", os.Args[0])
fmt.Printf("[OPTIONS] repository_list.json srcKey dstKey\n\n")
fmt.Printf("Options:\n")
flag.PrintDefaults()
}
flag.StringVar(&cfg.cacheDir, "cacheDir", "", "Cache directory")
flag.BoolVar(&cfg.cleanupCacheDir, "cleanCache", false, "Cache cleanup (automatic when cache directory is not provided)")
flag.IntVar(&cfg.concurrentJobs, "concurrency", 5, "Number of workers")
flag.BoolVar(&helpRequested, "help", false, "This help")
flag.Var(&cfg.refs, "ref", "Refs to mirror (default all)")
flag.Parse()
// if help requested or argument mismatch count, just exit with usage
if helpRequested || flag.NArg() != 3 {
flag.Usage()
os.Exit(0)
}
if cfg.cacheDir == "" {
cfg.cleanupCacheDir = true
cfg.cacheDir = os.TempDir()
}
cfg.jsonListFile = flag.Arg(0)
cfg.srcKey = flag.Arg(1)
cfg.dstKey = flag.Arg(2)
return cfg, nil
}
// load and validate json
func (c *mirror) loadRepositoryList() error {
var confRawList []map[string]interface{}
jsonBytes, err := ioutil.ReadFile(c.jsonListFile)
if err != nil {
return err
}
if err := json.Unmarshal(jsonBytes, &confRawList); err != nil {
return err
}
for _, item := range confRawList {
src, _ := item[c.srcKey].(string)
dst, _ := item[c.dstKey].(string)
c.repoList = append(c.repoList, repo{
dir: fmt.Sprintf("%s/%x", c.cacheDir, sha1.Sum([]byte(src))),
src: src,
dst: dst,
})
}
return c.validate()
}
// validate slice of structures from parsed json
func (c *mirror) validate() error {
errorList := make([]string, 0)
for _, item := range c.repoList {
if item.src == "" {
errorList = append(
errorList,
fmt.Sprintf("- key '%s' not found or not a string", c.srcKey),
)
}
if item.dst == "" {
errorList = append(
errorList,
fmt.Sprintf("- key '%s' not found or not a string", c.dstKey),
)
}
}
if len(errorList) > 0 {
return errors.New(strings.Join(errorList, "\n"))
}
return nil
}
// perform mirroring process
func (c *mirror) process() (chan bool, chan string, chan error) {
var wg sync.WaitGroup
chGuard := make(chan bool, c.concurrentJobs)
chOut := make(chan string, c.concurrentJobs)
chErr := make(chan error, c.concurrentJobs)
chDone := make(chan bool)
startedAt := time.Now()
// start workers
for _, item := range c.repoList {
wg.Add(1)
go func(item repo) {
defer func() {
<-chGuard
wg.Done()
}()
chGuard <- true
started := time.Now()
if err := item.sync(c.cacheDir, c.cleanupCacheDir, &c.refs); err != nil {
chErr <- err
}
elapsed := time.Since(started).Round(time.Second)
chOut <- fmt.Sprintf("+ %s in %s", item.src, elapsed)
}(item)
}
// wait and finalize
go func() {
wg.Wait()
chOut <- fmt.Sprintf("> Finished in %s", time.Since(startedAt).Round(time.Second))
chDone <- true
close(chOut)
close(chErr)
close(chDone)
}()
return chDone, chOut, chErr
}