Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // +build ignore
- package main
- import (
- "bytes"
- "fmt"
- "go/parser"
- "go/token"
- "io/ioutil"
- "log"
- "os"
- "sort"
- "github.com/dave/dst"
- "github.com/dave/dst/decorator"
- )
- func main() {
- var file string
- for _, arg := range os.Args[1:] {
- if arg != "--" {
- file = arg
- break
- }
- }
- if file == "" {
- fmt.Fprintf(os.Stderr, "usage %s <file>\n", os.Args[0])
- os.Exit(1)
- }
- fset := token.NewFileSet()
- f, err := decorator.ParseFile(fset, file, nil, parser.ParseComments)
- must(err)
- for i := 0; i < len(f.Decls); i++ {
- if !isFuncDecl(f.Decls[i]) {
- continue
- }
- j := i
- for j < len(f.Decls) && isFuncDecl(f.Decls[j]) {
- j++
- }
- funcs := f.Decls[i:j]
- sort.Slice(funcs, func(i, j int) bool {
- return funcs[i].(*dst.FuncDecl).Name.Name <
- funcs[j].(*dst.FuncDecl).Name.Name
- })
- i = j
- }
- for _, d := range f.Decls {
- g, ok := d.(*dst.GenDecl)
- if !ok || g.Tok != token.VAR {
- continue
- }
- for _, s := range g.Specs {
- v, ok := s.(*dst.ValueSpec)
- if !ok {
- continue
- }
- for _, vv := range v.Values {
- c, ok := vv.(*dst.CompositeLit)
- if !ok {
- continue
- }
- _, ok = c.Type.(*dst.MapType)
- if !ok {
- continue
- }
- sort.Slice(c.Elts, func(i, j int) bool {
- return c.Elts[i].(*dst.KeyValueExpr).Key.(*dst.Ident).Name <
- c.Elts[j].(*dst.KeyValueExpr).Key.(*dst.Ident).Name
- })
- }
- }
- }
- var buf bytes.Buffer
- must(decorator.Fprint(&buf, f))
- must(ioutil.WriteFile(file, buf.Bytes(), 0644))
- }
- func isFuncDecl(d dst.Decl) bool {
- _, ok := d.(*dst.FuncDecl)
- return ok
- }
- func must(err error) {
- if err != nil {
- log.Fatal(err)
- }
- }
Add Comment
Please, Sign In to add comment