forked from Tnze/go-mc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gen_soundid.go
97 lines (80 loc) · 1.97 KB
/
gen_soundid.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
//go:build generate
// +build generate
// gen_soundid.go generates the enumeration of sound IDs.
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"sort"
"text/template"
)
const (
version = "1.17.1"
protocolURL = "https://pokechu22.github.io/Burger/" + version + ".json"
// language=gohtml
soundTmpl = `// Code generated by gen_soundid.go. DO NOT EDIT.
package soundid
// SoundID represents a sound ID used in the minecraft protocol.
type SoundID int32
// SoundNames - map of ids to names for sounds.
var SoundNames = map[SoundID]string{ {{range .}}
{{.ID}}: "{{.Name}}",{{end}}
}
// GetSoundNameByID helper method
func GetSoundNameByID(id SoundID) (string, bool) {
name, ok := SoundNames[id]
return name, ok
}`
)
type Sound struct {
ID int64
Name string
}
//go:generate go run $GOFILE
func main() {
fmt.Println("generating soundid.go")
sounds, err := downloadSoundInfo()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
f, err := os.Create("soundid.go")
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
defer f.Close()
if err := template.Must(template.New("").Parse(soundTmpl)).Execute(f, sounds); err != nil {
panic(err)
}
}
func downloadSoundInfo() ([]*Sound, error) {
resp, err := http.Get(protocolURL)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// I'm not sure why the response returns a list, it appears to ever only have a single object...
var data []struct {
Sounds map[string]Sound `json:"sounds"`
}
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
return nil, err
}
out := make([]*Sound, 0)
for _, d := range data {
if has := len(d.Sounds); has > 0 {
for _, val := range d.Sounds {
out = append(out, &Sound{ID: val.ID, Name: val.Name})
}
} else {
return nil, fmt.Errorf("no sounds found in data from %s", protocolURL)
}
}
sort.SliceStable(out, func(i, j int) bool {
return out[i].ID < out[j].ID
})
return out, nil
}