github.com/wawandco/ox@v0.13.6-0.20230809142027-913b3d837f2a/plugins/tools/standard/goimportsfixer.go (about) 1 package standard 2 3 import ( 4 "bytes" 5 "context" 6 "os" 7 "path/filepath" 8 9 "golang.org/x/tools/imports" 10 ) 11 12 // GoImportsFixer runs goimports for the given root directory. 13 type GoImportsFixer struct{} 14 15 func (ef GoImportsFixer) Name() string { 16 return "ox/fixer/adjustimports" 17 } 18 19 func (ef GoImportsFixer) Fix(ctx context.Context, root string, args []string) error { 20 err := filepath.Walk(root, func(path string, info os.FileInfo, _ error) error { 21 if info.IsDir() || filepath.Ext(info.Name()) != ".go" { 22 return nil 23 } 24 25 src, err := os.ReadFile(path) 26 if err != nil { 27 return err 28 } 29 30 res, err := imports.Process(path, src, nil) 31 if err != nil { 32 return err 33 } 34 35 if bytes.Equal(src, res) { 36 return nil 37 } 38 39 return os.WriteFile(path, res, 0644) 40 }) 41 42 return err 43 }