windows_exporter/tools/collector-generator/generate-collector.go

61 lines
1.1 KiB
Go
Raw Normal View History

2016-09-24 09:49:09 +00:00
package main
import (
"encoding/json"
"io/ioutil"
"os"
"strings"
"text/template"
"unicode"
)
type TemplateData struct {
CollectorName string
Class string
Members []Member
}
type Member struct {
Name string
Type string
}
func main() {
bytes, err := ioutil.ReadAll(os.Stdin)
if err != nil {
panic(err)
}
var data TemplateData
2018-10-04 19:58:52 +00:00
if err = json.Unmarshal(bytes, &data); err != nil {
2016-09-24 09:49:09 +00:00
panic(err)
}
funcs := template.FuncMap{
"toLower": strings.ToLower,
"toSnakeCase": toSnakeCase,
}
2018-10-04 20:00:43 +00:00
tmpl, err := template.New("template").Funcs(funcs).ParseFiles("collector.template")
2016-09-24 09:49:09 +00:00
if err != nil {
panic(err)
}
2018-10-04 20:00:43 +00:00
err = tmpl.ExecuteTemplate(os.Stdout, "collector.template", data)
2016-09-24 09:49:09 +00:00
if err != nil {
panic(err)
}
}
// https://gist.github.com/elwinar/14e1e897fdbe4d3432e1
func toSnakeCase(in string) string {
runes := []rune(in)
length := len(runes)
var out []rune
for i := 0; i < length; i++ {
if i > 0 && unicode.IsUpper(runes[i]) && ((i+1 < length && unicode.IsLower(runes[i+1])) || unicode.IsLower(runes[i-1])) {
out = append(out, '_')
}
out = append(out, unicode.ToLower(runes[i]))
}
return string(out)
}