-
Notifications
You must be signed in to change notification settings - Fork 210
/
run.go
537 lines (446 loc) · 14.3 KB
/
run.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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
// +build !windows
package cmd
import (
"errors"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/Arkweid/lefthook/context"
arrop "github.com/adam-hanna/arrayOperations"
"github.com/gobwas/glob"
"github.com/kr/pty"
"github.com/spf13/afero"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var (
hooksGroup string
executableName string
sourcePath string
okList []string
failList []string
mutex sync.Mutex
envExcludeTags []string // store for LEFTHOOK_EXCLUDE=tag,tag
isPipeBroken bool
)
const (
runnerConfigKey string = "runner"
runConfigKey string = "run" // alias for runner
runnerArgsConfigKey string = "runner_args"
scriptsConfigKey string = "scripts"
commandsConfigKey string = "commands"
includeConfigKey string = "include"
excludeConfigKey string = "exclude"
globConfigKey string = "glob"
skipConfigKey string = "skip"
skipEmptyConfigKey string = "skip_empty"
filesConfigKey string = "files"
parallelConfigKey string = "parallel"
subFiles string = "{files}"
subAllFiles string = "{all_files}"
subStagedFiles string = "{staged_files}"
runnerWrapPattern string = "{cmd}"
tagsConfigKey string = "tags"
pipedConfigKey string = "piped"
excludeTagsConfigKey string = "exclude_tags"
minVersionConfigKey string = "min_version"
execMode os.FileMode = 0751
)
// runCmd represents the run command
var runCmd = &cobra.Command{
Use: "run",
Short: "Execute group of hooks",
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
err := RunCmdExecutor(args, appFs)
if err != nil {
os.Exit(1)
}
os.Exit(0)
},
}
func init() {
runCmd.SetUsageTemplate(`Usage:
lefthook run [hooksGroup]
Example:
lefthook run pre-commit
`)
rootCmd.AddCommand(runCmd)
}
// RunCmdExecutor run executables in hook groups
func RunCmdExecutor(args []string, fs afero.Fs) error {
if os.Getenv("LEFTHOOK") == "0" {
return nil
}
if !isVersionOk() {
log.Println(au.Brown("Config error! Current Lefhook version lower than config version or 'min_version' incorrect, check format: '0.6.0'"))
return errors.New("Current Lefhook version lower than config version or 'min_version' incorrect")
}
if tags := os.Getenv("LEFTHOOK_EXCLUDE"); tags != "" {
envExcludeTags = append(envExcludeTags, strings.Split(tags, ",")[:]...)
}
hooksGroup := args[0]
gitArgs := args[1:]
var wg sync.WaitGroup
startTime := time.Now()
log.Println(au.Cyan("RUNNING HOOKS GROUP:"), au.Bold(hooksGroup))
if isPipedAndParallel(hooksGroup) {
log.Println(au.Brown("Config error! Conflicted options 'piped' and 'parallel'. Remove one of this option from hook group."))
return errors.New("Piped and Parallel options in conflict.")
}
sourcePath := filepath.Join(getSourceDir(), hooksGroup)
executables, err := afero.ReadDir(fs, sourcePath)
if err == nil && len(executables) > 0 {
for _, executable := range executables {
wg.Add(1)
if getParallel(hooksGroup) {
go executeScript(hooksGroup, sourcePath, executable, &wg, gitArgs)
} else {
executeScript(hooksGroup, sourcePath, executable, &wg, gitArgs)
}
}
}
sourcePath = filepath.Join(getLocalSourceDir(), hooksGroup)
executables, err = afero.ReadDir(fs, sourcePath)
if err == nil && len(executables) > 0 {
for _, executable := range executables {
wg.Add(1)
if getParallel(hooksGroup) {
go executeScript(hooksGroup, sourcePath, executable, &wg, gitArgs)
} else {
executeScript(hooksGroup, sourcePath, executable, &wg, gitArgs)
}
}
}
commands := getCommands(hooksGroup)
if len(commands) != 0 {
for _, commandName := range commands {
wg.Add(1)
if getParallel(hooksGroup) {
go executeCommand(hooksGroup, commandName, &wg)
} else {
executeCommand(hooksGroup, commandName, &wg)
}
}
}
wg.Wait()
printSummary(time.Now().Sub(startTime))
if len(failList) == 0 {
return nil
}
return errors.New("Have failed script")
}
func executeCommand(hooksGroup, commandName string, wg *sync.WaitGroup) {
defer wg.Done()
if getPiped(hooksGroup) && isPipeBroken {
log.Println(au.Cyan("\n EXECUTE >"), au.Bold(commandName))
log.Println(au.Brown("(SKIP BY BROKEN PIPE)"))
return
}
files, _ := context.AllFiles()
runner := getRunner(hooksGroup, commandsConfigKey, commandName)
if strings.Contains(runner, subStagedFiles) {
files, _ = context.StagedFiles()
} else if strings.Contains(runner, subFiles) || getCommandFiles(hooksGroup, commandName) != "" {
files, _ = context.ExecGitCommand(getCommandFiles(hooksGroup, commandName))
}
files = FilterGlob(files, getCommandGlobRegexp(hooksGroup, commandName))
files = FilterInclude(files, getCommandIncludeRegexp(hooksGroup, commandName)) // NOTE: confusing option, suppose delete it
files = FilterExclude(files, getCommandExcludeRegexp(hooksGroup, commandName))
runner = strings.Replace(runner, subStagedFiles, strings.Join(files, " "), -1)
runner = strings.Replace(runner, subAllFiles, strings.Join(files, " "), -1)
runner = strings.Replace(runner, subFiles, strings.Join(files, " "), -1)
command := exec.Command("sh", "-c", runner)
command.Stdin = os.Stdin
ptyOut, err := pty.Start(command)
mutex.Lock()
defer mutex.Unlock()
log.Println(au.Cyan("\n EXECUTE >"), au.Bold(commandName))
if err != nil {
failList = append(failList, commandName)
setPipeBroken()
log.Println(err)
return
}
if isSkipCommmand(hooksGroup, commandName) {
log.Println(au.Brown("(SKIP BY SETTINGS)"))
return
}
if result, _ := arrop.Intersect(getExcludeTags(hooksGroup), getTags(hooksGroup, commandsConfigKey, commandName)); len(result.Interface().([]string)) > 0 {
log.Println(au.Brown("(SKIP BY TAGS)"))
return
}
if len(files) < 1 && isSkipEmptyCommmand(hooksGroup, commandName) {
log.Println(au.Brown("(SKIP. NO FILES FOR INSPECTING)"))
return
}
io.Copy(os.Stdout, ptyOut)
if command.Wait() == nil {
okList = append(okList, commandName)
} else {
failList = append(failList, commandName)
setPipeBroken()
}
}
func executeScript(hooksGroup, source string, executable os.FileInfo, wg *sync.WaitGroup, gitArgs []string) {
defer wg.Done()
executableName := executable.Name()
if getPiped(hooksGroup) && isPipeBroken {
log.Println(au.Cyan("\n EXECUTE >"), au.Bold(executableName))
log.Println(au.Brown("(SKIP BY BROKEN PIPE)"))
return
}
pathToExecutable := filepath.Join(source, executableName)
if err := isExecutable(executable); err != nil {
makeExecutable(pathToExecutable)
}
command := exec.Command(pathToExecutable, gitArgs[:]...)
if haveRunner(hooksGroup, scriptsConfigKey, executableName) {
runnerArg := strings.Split(getRunner(hooksGroup, scriptsConfigKey, executableName), " ")
runnerArg = append(runnerArg, pathToExecutable)
runnerArg = append(runnerArg, gitArgs[:]...)
command = exec.Command(runnerArg[0], runnerArg[1:]...)
}
command.Stdin = os.Stdin
ptyOut, err := pty.Start(command)
mutex.Lock()
defer mutex.Unlock()
log.Println(au.Cyan("\n EXECUTE >"), au.Bold(executableName))
if !isScriptExist(hooksGroup, executableName) {
log.Println(au.Bold(executableName), au.Brown("(SKIP BY NOT EXIST IN CONFIG)"))
return
}
if os.IsPermission(err) {
log.Println(au.Brown("(SKIP NOT EXECUTABLE FILE)"))
return
}
if err != nil {
failList = append(failList, executableName)
log.Println(err)
log.Println(au.Brown("TIP: Command start failed. Checkout `runner:` option for this script"))
setPipeBroken()
return
}
if isSkipScript(hooksGroup, executableName) {
log.Println(au.Brown("(SKIP BY SETTINGS)"))
return
}
if result, _ := arrop.Intersect(getExcludeTags(hooksGroup), getTags(hooksGroup, scriptsConfigKey, executableName)); len(result.Interface().([]string)) > 0 {
log.Println(au.Brown("(SKIP BY TAGS)"))
return
}
io.Copy(os.Stdout, ptyOut)
if command.Wait() == nil {
okList = append(okList, executableName)
} else {
failList = append(failList, executableName)
setPipeBroken()
}
}
func haveRunner(hooksGroup, source, executableName string) (out bool) {
if runner := getRunner(hooksGroup, source, executableName); runner != "" {
out = true
}
return
}
func getRunner(hooksGroup, source, executableName string) string {
key := strings.Join([]string{hooksGroup, source, executableName, runnerConfigKey}, ".")
runner := viper.GetString(key)
aliasKey := strings.Join([]string{hooksGroup, source, executableName, runConfigKey}, ".")
aliasRunner := viper.GetString(aliasKey)
if runner == "" && aliasRunner != "" {
runner = aliasRunner
}
// If runner have {cmd} substring, replace it from runner in lefthook.yaml
if res := strings.Contains(runner, runnerWrapPattern); res {
originRunner := originConfig.GetString(key)
runner = strings.Replace(runner, runnerWrapPattern, originRunner, -1)
}
return runner
}
func printSummary(execTime time.Duration) {
if len(okList) == 0 && len(failList) == 0 {
log.Println(au.Cyan("\nSUMMARY:"), au.Brown("(SKIP EMPTY)"))
} else {
log.Println(au.Cyan(fmt.Sprintf("\nSUMMARY: (done in %.2f seconds)", execTime.Seconds())))
}
for _, fileName := range okList {
log.Printf("✔️ %s\n", au.Green(fileName))
}
for _, fileName := range failList {
log.Printf("🥊 %s", au.Red(fileName))
}
}
func isScriptExist(hooksGroup, executableName string) bool {
key := strings.Join([]string{hooksGroup, scriptsConfigKey, executableName}, ".")
return viper.IsSet(key)
}
func isSkipScript(hooksGroup, executableName string) bool {
key := strings.Join([]string{hooksGroup, scriptsConfigKey, executableName, skipConfigKey}, ".")
return viper.GetBool(key)
}
func isSkipCommmand(hooksGroup, executableName string) bool {
key := strings.Join([]string{hooksGroup, commandsConfigKey, executableName, skipConfigKey}, ".")
return viper.GetBool(key)
}
// NOTE: confusing option, suppose it unnesecary and should be deleted.
func isSkipEmptyCommmand(hooksGroup, executableName string) bool {
key := strings.Join([]string{hooksGroup, commandsConfigKey, executableName, skipEmptyConfigKey}, ".")
if viper.IsSet(key) {
return viper.GetBool(key)
}
key = strings.Join([]string{hooksGroup, skipEmptyConfigKey}, ".")
if viper.IsSet(key) {
return viper.GetBool(key)
}
return true
}
func getCommands(hooksGroup string) []string {
key := strings.Join([]string{hooksGroup, commandsConfigKey}, ".")
commands := viper.GetStringMap(key)
keys := make([]string, 0, len(commands))
for k := range commands {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
func getCommandIncludeRegexp(hooksGroup, executableName string) string {
key := strings.Join([]string{hooksGroup, commandsConfigKey, executableName, includeConfigKey}, ".")
return viper.GetString(key)
}
func getCommandExcludeRegexp(hooksGroup, executableName string) string {
key := strings.Join([]string{hooksGroup, commandsConfigKey, executableName, excludeConfigKey}, ".")
return viper.GetString(key)
}
func getCommandGlobRegexp(hooksGroup, executableName string) string {
key := strings.Join([]string{hooksGroup, commandsConfigKey, executableName, globConfigKey}, ".")
if viper.GetString(key) != "" {
return viper.GetString(key)
}
key = strings.Join([]string{hooksGroup, globConfigKey}, ".")
return viper.GetString(key)
}
func getCommandFiles(hooksGroup, executableName string) string {
key := strings.Join([]string{hooksGroup, commandsConfigKey, executableName, filesConfigKey}, ".")
if viper.GetString(key) != "" {
return viper.GetString(key)
}
key = strings.Join([]string{hooksGroup, filesConfigKey}, ".")
if viper.GetString(key) != "" {
return viper.GetString(key)
}
return ""
}
func getTags(hooksGroup, source, executableName string) []string {
key := strings.Join([]string{hooksGroup, source, executableName, tagsConfigKey}, ".")
return strings.Split(viper.GetString(key), " ")
}
func getExcludeTags(hooksGroup string) []string {
key := strings.Join([]string{hooksGroup, excludeTagsConfigKey}, ".")
if len(viper.GetStringSlice(key)) > 0 {
return append(viper.GetStringSlice(key), envExcludeTags[:]...)
}
if len(viper.GetStringSlice(excludeTagsConfigKey)) > 0 {
return append(viper.GetStringSlice(excludeTagsConfigKey), envExcludeTags[:]...)
}
if len(envExcludeTags) > 0 {
return envExcludeTags
}
return []string{}
}
func getParallel(hooksGroup string) bool {
key := strings.Join([]string{hooksGroup, parallelConfigKey}, ".")
return viper.GetBool(key)
}
func getPiped(hooksGroup string) bool {
key := strings.Join([]string{hooksGroup, pipedConfigKey}, ".")
return viper.GetBool(key)
}
func isPipedAndParallel(hooksGroup string) bool {
return getParallel(hooksGroup) && getPiped(hooksGroup)
}
func setPipeBroken() {
isPipeBroken = true
}
func FilterGlob(vs []string, matcher string) []string {
if matcher == "" {
return vs
}
g := glob.MustCompile(matcher)
vsf := make([]string, 0)
for _, v := range vs {
if res := g.Match(v); res {
vsf = append(vsf, v)
}
}
return vsf
}
func FilterInclude(vs []string, matcher string) []string {
if matcher == "" {
return vs
}
vsf := make([]string, 0)
for _, v := range vs {
if res, _ := regexp.MatchString(matcher, v); res {
vsf = append(vsf, v)
}
}
return vsf
}
func FilterExclude(vs []string, matcher string) []string {
if matcher == "" {
return vs
}
vsf := make([]string, 0)
for _, v := range vs {
if res, _ := regexp.MatchString(matcher, v); !res {
vsf = append(vsf, v)
}
}
return vsf
}
func isExecutable(executable os.FileInfo) error {
mode := executable.Mode()
if !mode.IsRegular() {
return errors.New("ErrPermission")
}
if (mode & 0111) == 0 {
return errors.New("ErrPermission")
}
return nil
}
func makeExecutable(path string) {
if err := os.Chmod(path, execMode); err != nil {
log.Fatal(err)
}
}
func isVersionOk() bool {
if !viper.IsSet(minVersionConfigKey) {
return true
}
configVersion := viper.GetString(minVersionConfigKey)
configVersionSplited := strings.Split(configVersion, ".")
if len(configVersionSplited) != 3 {
VerbosePrint("Config min_version option have incorrect format")
return false
}
currentVersionSplited := strings.Split(version, ".")
for i, value := range currentVersionSplited {
currentNum, _ := strconv.ParseInt(value, 0, 64)
configNum, _ := strconv.ParseInt(configVersionSplited[i], 0, 64)
if currentNum < configNum {
return false
}
}
return true
}