github.com/wawandco/oxpecker-plugins@v0.1.1/tools/standard/fixer.go (about) 1 package standard 2 3 import ( 4 "context" 5 "errors" 6 "fmt" 7 "io/ioutil" 8 "os" 9 "path/filepath" 10 11 "github.com/wawandco/oxpecker-plugins/lifecycle/fix" 12 "github.com/wawandco/oxpecker/plugins" 13 "golang.org/x/mod/modfile" 14 ) 15 16 var ( 17 _ plugins.Plugin = (*Fixer)(nil) 18 _ fix.Fixer = (*Fixer)(nil) 19 20 ErrModuleNameNeeded = errors.New("module name needed") 21 ErrModuleNameNotFound = errors.New("module name not found") 22 ErrFileMainNotExist = errors.New("main.go file does not exist") 23 ) 24 25 // Fixer is in charge of performing a Fix operation 26 // that moves the main.go to cmd/[name-of-the-module]/main.go 27 type Fixer struct{} 28 29 func (f Fixer) Name() string { 30 return "main" 31 } 32 33 // Fix does the main.go magic 34 // - Determine if the file exists 35 // - Determine if there is a go.mod 36 // - Determine the name of the module (last part when slicing go.mod by /) 37 // - Create folder 38 // - Copy/move main.go to that folder 39 func (f Fixer) Fix(ctx context.Context, root string, args []string) error { 40 _, err := f.fileExists() 41 if err != nil { 42 return err 43 } 44 45 base, err := f.findModuleName() 46 if err != nil { 47 return err 48 } 49 50 err = f.moveFile(base) 51 if err != nil { 52 return err 53 } 54 55 return nil 56 } 57 58 func (f Fixer) moveFile(s string) error { 59 if s == "" { 60 return ErrModuleNameNeeded 61 } 62 63 name := "main.go" 64 s = "cmd/" + s 65 err := os.MkdirAll(s, 0755) 66 if err != nil { 67 return err 68 } 69 70 finLoc := s + "/" + name 71 err = os.Rename(name, finLoc) 72 if err != nil { 73 return err 74 } 75 76 return nil 77 } 78 79 // Look for go.mod and extract the last part. 80 func (f Fixer) findModuleName() (string, error) { 81 mp := "go.mod" 82 file, err := ioutil.ReadFile(mp) 83 if err != nil { 84 return "", err 85 } 86 87 base := filepath.Base(modfile.ModulePath(file)) 88 89 if base != "." { 90 return base, nil 91 } 92 if base == "." { 93 return "", ErrModuleNameNotFound 94 } 95 return "", ErrModuleNameNotFound 96 } 97 98 func (f Fixer) fileExists() (bool, error) { 99 files, err := ioutil.ReadDir(".") 100 if err != nil { 101 return false, err 102 } 103 104 for _, f := range files { 105 if f.Name() == "main.go" { 106 fmt.Println(f.Name() + " found") 107 return true, nil 108 } 109 } 110 111 return false, ErrFileMainNotExist 112 }