You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

107 lines
1.6 KiB

//go:build generate
package main
import (
"bytes"
_ "embed"
"encoding/json"
"os"
"sort"
"strings"
"text/template"
"golang.org/x/tools/imports"
)
var (
//go:embed input.json
JSON []byte
keys []string
data map[string]string
)
//go:generate go run main.go
func main() {
if err := json.Unmarshal(JSON, &data); err != nil {
panic(err)
}
for key := range data {
if !strings.HasPrefix(key, "CI") {
continue
}
keys = append(keys, key)
}
sort.Strings(keys)
if err := envGo(); err != nil {
panic(err)
}
if err := envJSON(); err != nil {
panic(err)
}
}
func envGo() error {
fi, _ := os.Create("env.go")
defer fi.Close()
var buf bytes.Buffer
if err := tmpl.Execute(&buf, map[string]interface{}{
"keys": keys,
"data": data,
}); err != nil {
return err
}
out, err := imports.Process("env.go", buf.Bytes(), nil)
if err != nil {
return err
}
_, err = fi.Write(out)
return err
}
type CI struct {
Key string `json:"key"`
Comment string `json:"comment"`
}
func envJSON() error {
fi, _ := os.Create("env.json")
defer fi.Close()
var ci []CI
for _, key := range keys {
ci = append(ci, CI{
Key: key,
Comment: data[key],
})
}
out, err := json.MarshalIndent(ci, "", "\t")
if err != nil {
return err
}
_, err = fi.Write(out)
return err
}
var tmpl = template.Must(template.New("").Parse(`package env
import (
"os"
)
// List of CI env variables with an example value comment
var (
{{range $key := .keys}}{{$key}} string // Example: {{index $.data $key}}
{{end}})
func init() {
{{range $key := .keys}}{{$key}} = os.Getenv("{{$key}}")
{{end}}}`))