github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/gen/codegen/formatx/format.go (about) 1 package formatx 2 3 import ( 4 "bytes" 5 "fmt" 6 "go/ast" 7 "go/format" 8 "go/parser" 9 "go/token" 10 ) 11 12 type Proc func(fset *token.FileSet, f *ast.File, filename, group string) error 13 14 func Format(file, mod string, src []byte, procs ...Proc) ([]byte, error) { 15 fset, f, err := Parse(file, src) 16 if err != nil { 17 return nil, err 18 } 19 20 for _, proc := range procs { 21 if proc == nil { 22 continue 23 } 24 if err = proc(fset, f, file, mod); err != nil { 25 return nil, err 26 } 27 } 28 29 buf := bytes.NewBuffer(nil) 30 if err = format.Node(buf, fset, f); err != nil { 31 return nil, fmt.Errorf("[FORMAT] %s: %v", file, err) 32 } 33 return buf.Bytes(), nil 34 } 35 36 func Parse(file string, src []byte) (*token.FileSet, *ast.File, error) { 37 fset := token.NewFileSet() 38 f, err := parser.ParseFile(fset, file, src, parser.ParseComments) 39 if err != nil { 40 return nil, nil, fmt.Errorf("[PARSE] %s: %v", file, err) 41 } 42 return fset, f, nil 43 } 44 45 func MustFormat(file, mod string, src []byte, procs ...Proc) []byte { 46 code, err := Format(file, mod, src, procs...) 47 if err != nil { 48 panic(err) 49 } 50 return code 51 }