123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119 |
- // +build prebuild
- package main
- import (
- "bytes"
- "go/format"
- "io/ioutil"
- "os"
- "strings"
- "text/template"
- )
- func genInternalSortableTypes() []string {
- return []string{
- "string",
- "float32",
- "float64",
- "uint",
- "uint8",
- "uint16",
- "uint32",
- "uint64",
- "uintptr",
- "int",
- "int8",
- "int16",
- "int32",
- "int64",
- "bool",
- "time",
- "bytes",
- }
- }
- func genInternalSortablePlusTypes() []string {
- return []string{
- "string",
- "float64",
- "uint64",
- "uintptr",
- "int64",
- "bool",
- "time",
- "bytes",
- }
- }
- func genTypeForShortName(s string) string {
- switch s {
- case "time":
- return "time.Time"
- case "bytes":
- return "[]byte"
- }
- return s
- }
- func genArgs(args ...interface{}) map[string]interface{} {
- m := make(map[string]interface{}, len(args)/2)
- for i := 0; i < len(args); {
- m[args[i].(string)] = args[i+1]
- i += 2
- }
- return m
- }
- func genEndsWith(s0 string, sn ...string) bool {
- for _, s := range sn {
- if strings.HasSuffix(s0, s) {
- return true
- }
- }
- return false
- }
- func chkerr(err error) {
- if err != nil {
- panic(err)
- }
- }
- func run(fnameIn, fnameOut string) {
- var err error
- funcs := make(template.FuncMap)
- funcs["sortables"] = genInternalSortableTypes
- funcs["sortablesplus"] = genInternalSortablePlusTypes
- funcs["tshort"] = genTypeForShortName
- funcs["endswith"] = genEndsWith
- funcs["args"] = genArgs
- t := template.New("").Funcs(funcs)
- fin, err := os.Open(fnameIn)
- chkerr(err)
- defer fin.Close()
- fout, err := os.Create(fnameOut)
- chkerr(err)
- defer fout.Close()
- tmplstr, err := ioutil.ReadAll(fin)
- chkerr(err)
- t, err = t.Parse(string(tmplstr))
- chkerr(err)
- var out bytes.Buffer
- err = t.Execute(&out, 0)
- chkerr(err)
- bout, err := format.Source(out.Bytes())
- if err != nil {
- fout.Write(out.Bytes()) // write out if error, so we can still see.
- // w.Write(bout) // write out if error, as much as possible, so we can still see.
- }
- chkerr(err)
- _, err = fout.Write(bout)
- chkerr(err)
- }
- func main() {
- run("sort-slice.go.tmpl", "sort-slice.generated.go")
- }
|