prebuild.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. // +build prebuild
  2. package main
  3. import (
  4. "bytes"
  5. "go/format"
  6. "io/ioutil"
  7. "os"
  8. "strings"
  9. "text/template"
  10. )
  11. func genInternalSortableTypes() []string {
  12. return []string{
  13. "string",
  14. "float32",
  15. "float64",
  16. "uint",
  17. "uint8",
  18. "uint16",
  19. "uint32",
  20. "uint64",
  21. "uintptr",
  22. "int",
  23. "int8",
  24. "int16",
  25. "int32",
  26. "int64",
  27. "bool",
  28. "time",
  29. "bytes",
  30. }
  31. }
  32. func genInternalSortablePlusTypes() []string {
  33. return []string{
  34. "string",
  35. "float64",
  36. "uint64",
  37. "uintptr",
  38. "int64",
  39. "bool",
  40. "time",
  41. "bytes",
  42. }
  43. }
  44. func genTypeForShortName(s string) string {
  45. switch s {
  46. case "time":
  47. return "time.Time"
  48. case "bytes":
  49. return "[]byte"
  50. }
  51. return s
  52. }
  53. func genArgs(args ...interface{}) map[string]interface{} {
  54. m := make(map[string]interface{}, len(args)/2)
  55. for i := 0; i < len(args); {
  56. m[args[i].(string)] = args[i+1]
  57. i += 2
  58. }
  59. return m
  60. }
  61. func genEndsWith(s0 string, sn ...string) bool {
  62. for _, s := range sn {
  63. if strings.HasSuffix(s0, s) {
  64. return true
  65. }
  66. }
  67. return false
  68. }
  69. func chkerr(err error) {
  70. if err != nil {
  71. panic(err)
  72. }
  73. }
  74. func run(fnameIn, fnameOut string) {
  75. var err error
  76. funcs := make(template.FuncMap)
  77. funcs["sortables"] = genInternalSortableTypes
  78. funcs["sortablesplus"] = genInternalSortablePlusTypes
  79. funcs["tshort"] = genTypeForShortName
  80. funcs["endswith"] = genEndsWith
  81. funcs["args"] = genArgs
  82. t := template.New("").Funcs(funcs)
  83. fin, err := os.Open(fnameIn)
  84. chkerr(err)
  85. defer fin.Close()
  86. fout, err := os.Create(fnameOut)
  87. chkerr(err)
  88. defer fout.Close()
  89. tmplstr, err := ioutil.ReadAll(fin)
  90. chkerr(err)
  91. t, err = t.Parse(string(tmplstr))
  92. chkerr(err)
  93. var out bytes.Buffer
  94. err = t.Execute(&out, 0)
  95. chkerr(err)
  96. bout, err := format.Source(out.Bytes())
  97. if err != nil {
  98. fout.Write(out.Bytes()) // write out if error, so we can still see.
  99. // w.Write(bout) // write out if error, as much as possible, so we can still see.
  100. }
  101. chkerr(err)
  102. _, err = fout.Write(bout)
  103. chkerr(err)
  104. }
  105. func main() {
  106. run("sort-slice.go.tmpl", "sort-slice.generated.go")
  107. }