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