/
main.go
274 lines (232 loc) · 6.12 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
package main
import (
"bytes"
"flag"
"fmt"
"github.com/fatih/color"
"github.com/jcgay/parallel-git-repo/version"
"github.com/mitchellh/go-homedir"
"github.com/pelletier/go-toml"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
)
var home string
var (
quiet bool
printVersion bool
)
const help = `NAME:
Parallel Git Repositories - Execute commands on multiple Git repositories in parallel!
USAGE:
./parallel-git-repo [global options] command [arguments...]
VERSION:
%s (%s)
COMMANDS:
%s
GLOBAL OPTIONS:
-h show help
`
var ok = color.New(color.FgGreen).SprintFunc()("✔")
var ko = color.New(color.FgRed).SprintFunc()("✘")
func main() {
if home == "" {
var err error
home, err = homedir.Dir()
if err != nil {
log.Fatalf("Cannot read user home directory.\n%v", err)
}
}
flag.BoolVar(&quiet, "q", false, "do not print stdout commands result, only stderr will be shown")
flag.BoolVar(&printVersion, "v", false, "print current version")
var group string
flag.StringVar(&group, "g", "default", "execute command for a specific repositories group")
flag.Usage = func() {
fmt.Fprint(os.Stderr, fmt.Sprintf(help, version.VERSION, version.GITCOMMIT, listCommands()))
flag.PrintDefaults()
}
flag.Parse()
if printVersion {
fmt.Printf("version: %s (%s)", version.VERSION, version.GITCOMMIT)
} else {
configuration := newConfiguration(home)
if os.Args[1] == "list" {
repos := configuration.ListRepositories()
for key, repos := range repos {
fmt.Printf("%s:\n", key)
for _, repo := range repos {
fmt.Printf(" - %s\n", repo)
}
}
} else {
runCommand(configuration, withoutFlags(os.Args[1:]), group)
}
}
}
func listCommands() string {
config, err := tryNewConfiguration(home)
commands := make(map[string]string)
if err == nil {
commands = config.ListCommands()
}
maxSize := 3
for key := range commands {
if size := len(key); size > maxSize {
maxSize = size
}
}
result := fmt.Sprintf(" %-"+strconv.Itoa(maxSize)+"s %s\n", "run", "run an arbitrary command")
result += fmt.Sprintf(" %-"+strconv.Itoa(maxSize)+"s %s\n", "list", "list repositories where command will be run")
for key, value := range commands {
result += fmt.Sprintf(" %-"+strconv.Itoa(maxSize)+"s %s\n", key, value)
}
return result
}
func runCommand(config *configuration, args []string, group string) {
commandName := args[0]
var toExec []string
if commandName == "run" {
toExec = args[1:]
} else {
toExec = strings.Split(config.ListCommands()[commandName], " ")
}
runner := newRunner(&run{ToExec: toExec, Quiet: quiet}, config)
runner.Run(args[1:], group)
}
func withoutFlags(args []string) []string {
for i, value := range args {
if !strings.HasPrefix(value, "-") {
return args[i:]
}
}
return args
}
type repositories interface {
ListRepositories() map[string][]string
}
type commands interface {
ListCommands() map[string]string
}
type configuration struct {
content *toml.Tree
}
func newConfiguration(homeDir string) *configuration {
config, err := tryNewConfiguration(homeDir)
if err != nil {
log.Fatalf("Can't read configuration file %s/.parallel-git-repositories, verify that the file is valid...\n%v", homeDir, err)
}
return config
}
func tryNewConfiguration(homeDir string) (*configuration, error) {
config, err := toml.LoadFile(homeDir + "/.parallel-git-repositories")
if err != nil {
return nil, err
}
return &configuration{config}, nil
}
func (config *configuration) ListRepositories() map[string][]string {
repos := config.content.Get("repositories").(*toml.Tree)
result := make(map[string][]string)
for _, key := range repos.Keys() {
result[key] = toStringArray(repos.Get(key).([]interface{}))
}
return result
}
func toStringArray(values []interface{}) []string {
result := make([]string, len(values))
for i, value := range values {
result[i] = value.(string)
}
return result
}
func (config *configuration) ListCommands() map[string]string {
all := config.content.Get("commands").(*toml.Tree)
result := make(map[string]string)
for _, key := range all.Keys() {
result[key] = all.Get(key).(string)
}
return result
}
type runnableCommand interface {
Executable() string
Options() []string
Output(output string, err error) string
}
type runner struct {
runnableCommand
repos repositories
writer io.Writer
}
func newRunner(command runnableCommand, repos repositories) *runner {
return &runner{
runnableCommand: command,
repos: repos,
writer: os.Stdout,
}
}
func (runner *runner) Run(args []string, group string) {
wg := sync.WaitGroup{}
for key, repos := range runner.repos.ListRepositories() {
if key == group {
for _, repo := range repos {
wg.Add(1)
go func(repo string) {
defer wg.Done()
output := new(bytes.Buffer)
command := exec.Command(runner.runnableCommand.Executable(), forwardArgs(runner.runnableCommand.Options(), args)...)
command.Stdout = output
command.Stderr = output
command.Dir = repo
err := command.Run()
fmt.Fprintln(runner.writer, filepath.Base(repo)+": "+runner.runnableCommand.Output(strings.TrimSpace(output.String()), err))
}(repo)
}
}
}
wg.Wait()
}
var option = regexp.MustCompile(`\$([0-9]+)`)
func forwardArgs(opts []string, args []string) []string {
result := make([]string, 0)
for _, opt := range opts {
if opt == "$@" {
result = append(result, args...)
} else if option.MatchString(opt) {
result = append(result, option.ReplaceAllStringFunc(opt, func(substring string) string {
index, _ := strconv.Atoi(substring[1:])
return args[index-1]
}))
} else {
result = append(result, opt)
}
}
return result
}
type run struct {
ToExec []string
Quiet bool
}
func (command *run) Executable() string {
return command.ToExec[0]
}
func (command *run) Options() []string {
return command.ToExec[1:]
}
func (command *run) Output(output string, err error) string {
if err != nil {
if output == "" {
return fmt.Sprintf("%s\n %v", ko, err)
}
return fmt.Sprintf("%s\n %v\n %s", ko, err, output)
}
if output == "" || command.Quiet {
return ok
}
return fmt.Sprintf("%s\n %s", ok, output)
}