/
gen_entity.go
105 lines (90 loc) · 2.09 KB
/
gen_entity.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
//go:build generate
// +build generate
// gen_entity.go generates entity information.
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"text/template"
"github.com/iancoleman/strcase"
)
const (
version = "1.20"
infoURL = "https://raw.githubusercontent.com/PrismarineJS/minecraft-data/master/data/pc/" + version + "/entities.json"
// language=gohtml
entityTmpl = `// Code generated by gen_entity.go DO NOT EDIT.
// Package entity stores information about entities in Minecraft.
package entity
// ID describes the numeric ID of an entity.
type ID uint32
// Entity describes information about a type of entity.
type Entity struct {
ID ID
InternalID uint32
DisplayName string
Name string
Width float64
Height float64
Type string
}
var (
{{- range .}}
{{.CamelName}} = Entity{
ID: {{.ID}},
InternalID: {{.InternalID}},
DisplayName: "{{.DisplayName}}",
Name: "{{.Name}}",
Width: {{.Width}},
Height: {{.Height}},
Type: "{{.Type}}",
}{{end}}
)
// ByID is an index of minecraft entities by their ID.
var ByID = map[ID]*Entity{ {{range .}}
{{.ID}}: &{{.CamelName}},{{end}}
}`
)
type Entity struct {
ID uint32 `json:"id"`
InternalID uint32 `json:"internalId"`
CamelName string `json:"-"`
DisplayName string `json:"displayName"`
Name string `json:"name"`
Width float64 `json:"width"`
Height float64 `json:"height"`
Type string `json:"type"`
}
func downloadInfo() ([]*Entity, error) {
resp, err := http.Get(infoURL)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var data []*Entity
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
return nil, err
}
for _, d := range data {
d.CamelName = strcase.ToCamel(d.Name)
}
return data, nil
}
//go:generate go run $GOFILE
//go:generate go fmt entity.go
func main() {
fmt.Println("generating entity.go")
entities, err := downloadInfo()
if err != nil {
panic(err)
}
f, err := os.Create("entity.go")
if err != nil {
panic(err)
}
defer f.Close()
if err := template.Must(template.New("").Parse(entityTmpl)).Execute(f, entities); err != nil {
panic(err)
}
}