Guest User

Untitled

a guest
Oct 16th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. // +build ignore
  2.  
  3. package main
  4.  
  5. import (
  6. "bytes"
  7. "fmt"
  8. "go/parser"
  9. "go/token"
  10. "io/ioutil"
  11. "log"
  12. "os"
  13. "sort"
  14.  
  15. "github.com/dave/dst"
  16. "github.com/dave/dst/decorator"
  17. )
  18.  
  19. func main() {
  20. var file string
  21. for _, arg := range os.Args[1:] {
  22. if arg != "--" {
  23. file = arg
  24. break
  25. }
  26. }
  27.  
  28. if file == "" {
  29. fmt.Fprintf(os.Stderr, "usage %s <file>\n", os.Args[0])
  30. os.Exit(1)
  31. }
  32.  
  33. fset := token.NewFileSet()
  34. f, err := decorator.ParseFile(fset, file, nil, parser.ParseComments)
  35. must(err)
  36.  
  37. for i := 0; i < len(f.Decls); i++ {
  38. if !isFuncDecl(f.Decls[i]) {
  39. continue
  40. }
  41.  
  42. j := i
  43. for j < len(f.Decls) && isFuncDecl(f.Decls[j]) {
  44. j++
  45. }
  46.  
  47. funcs := f.Decls[i:j]
  48. sort.Slice(funcs, func(i, j int) bool {
  49. return funcs[i].(*dst.FuncDecl).Name.Name <
  50. funcs[j].(*dst.FuncDecl).Name.Name
  51. })
  52.  
  53. i = j
  54. }
  55.  
  56. for _, d := range f.Decls {
  57. g, ok := d.(*dst.GenDecl)
  58. if !ok || g.Tok != token.VAR {
  59. continue
  60. }
  61.  
  62. for _, s := range g.Specs {
  63. v, ok := s.(*dst.ValueSpec)
  64. if !ok {
  65. continue
  66. }
  67.  
  68. for _, vv := range v.Values {
  69. c, ok := vv.(*dst.CompositeLit)
  70. if !ok {
  71. continue
  72. }
  73.  
  74. _, ok = c.Type.(*dst.MapType)
  75. if !ok {
  76. continue
  77. }
  78.  
  79. sort.Slice(c.Elts, func(i, j int) bool {
  80. return c.Elts[i].(*dst.KeyValueExpr).Key.(*dst.Ident).Name <
  81. c.Elts[j].(*dst.KeyValueExpr).Key.(*dst.Ident).Name
  82. })
  83. }
  84. }
  85. }
  86.  
  87. var buf bytes.Buffer
  88. must(decorator.Fprint(&buf, f))
  89. must(ioutil.WriteFile(file, buf.Bytes(), 0644))
  90. }
  91.  
  92. func isFuncDecl(d dst.Decl) bool {
  93. _, ok := d.(*dst.FuncDecl)
  94. return ok
  95. }
  96.  
  97. func must(err error) {
  98. if err != nil {
  99. log.Fatal(err)
  100. }
  101. }
Add Comment
Please, Sign In to add comment