github.com/inturn/pre-commit-gobuild@v1.0.12/hooks/composecheck/composecheck.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "log" 7 "os" 8 "path/filepath" 9 "regexp" 10 11 "gopkg.in/yaml.v2" 12 ) 13 14 func main() { 15 wd, err := os.Getwd() 16 if err != nil { 17 log.Fatal(err) 18 } 19 20 composeFiles := make([]string, 0) 21 22 filepath.Walk(wd, func(path string, f os.FileInfo, _ error) error { 23 if !f.IsDir() { 24 r, err := regexp.MatchString(`^docker-compose\.ya?ml$`, f.Name()) 25 if err == nil && r { 26 composeFiles = append(composeFiles, path) 27 } 28 } 29 return nil 30 }) 31 32 errs := make([]error, 0) 33 34 for _, fName := range composeFiles { 35 f, err := os.Open(fName) 36 if err != nil { 37 errs = append(errs, fmt.Errorf("failed to open file: %s --> %s", fName, err)) 38 continue 39 } 40 41 data, err := ioutil.ReadAll(f) 42 if err != nil { 43 errs = append(errs, fmt.Errorf("failed to read file: %s --> %s", fName, err)) 44 continue 45 } 46 47 dckComp := DockerCompose{} 48 if err := yaml.Unmarshal(data, &dckComp); err != nil { 49 errs = append(errs, fmt.Errorf("failed to unmarshal file: %s --> %s", fName, err)) 50 continue 51 } 52 53 // Validation 54 if dckComp.Version != "3.7" { 55 errs = append(errs, fmt.Errorf("required docker-compose version is 3.7: %s", f.Name())) 56 } 57 58 for _, svc := range dckComp.Services { 59 if m, err := regexp.MatchString(`(?i)^\s*.*:latest\s*$`, svc.Image); err != nil || m { 60 errs = append(errs, fmt.Errorf("%s image should not use the latest tag: %s", f.Name(), svc.Image)) 61 } 62 } 63 } 64 65 if len(errs) != 0 { 66 for _, e := range errs { 67 log.Println(e) 68 } 69 os.Exit(1) 70 } 71 os.Exit(0) 72 } 73 74 type DockerCompose struct { 75 Version string `yaml:"version"` 76 Services map[string]Service `yaml:"services"` 77 } 78 79 type Service struct { 80 Image string `yaml:"image"` 81 }