urfave-cli/flag-gen/main.go

114 lines
2.1 KiB
Go
Raw Normal View History

//go:generate go run assets_generate.go
2019-03-06 15:04:18 +00:00
package main
import (
"encoding/json"
"fmt"
2019-03-06 15:04:18 +00:00
"github.com/urfave/cli"
"io/ioutil"
2019-03-06 15:04:18 +00:00
"log"
"os"
"text/template"
2019-03-06 15:04:18 +00:00
)
type CliFlagInfo struct {
PackageName string
Flags []FlagType
}
type FlagType struct {
Name string `json:"name"`
Type string `json:"type"`
Value bool `json:"value"`
Destination bool `json:"dest"`
Doctail string `json:"doctail"`
ContextDefault string `json:"context_default"`
ContextType string `json:"context_type"`
Parser string `json:"parser"`
ParserCast string `json:"parser_cast"`
}
func main() {
app := cli.NewApp()
2019-08-04 05:39:34 +00:00
app.Name = "flag-generator"
app.Usage = "Generate flag type code!"
app.Action = ActionFunc
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
func ActionFunc(_ *cli.Context) error {
var info CliFlagInfo
var tpl *template.Template
2019-03-06 15:04:18 +00:00
inFile, err := assets.Open("/source/flag-types.json")
if err != nil {
log.Fatal(err)
2019-03-06 15:04:18 +00:00
}
decoder := json.NewDecoder(inFile)
err = decoder.Decode(&info.Flags)
if err != nil {
log.Fatal(err)
}
err = inFile.Close()
if err != nil {
log.Fatal(err)
}
for _, packageName := range []string{"cli", "altsrc"} {
info.PackageName = packageName
bytes, err := ReadTemplate(packageName)
if err != nil {
log.Fatal(err)
}
tpl = template.Must(template.New("").Parse(string(bytes)))
var outFile *os.File
if packageName == "cli" {
outFile, err = os.Create("flag_generated.go")
} else {
outFile, err = os.Create("altsrc/flag_generated.go")
}
if err != nil {
log.Fatal(err)
}
err = tpl.Execute(outFile, info)
if err != nil {
log.Fatal(err)
}
err = outFile.Close()
if err != nil {
log.Fatal(err)
}
}
return nil
}
func ReadTemplate(packageName string) ([]byte, error) {
templateFile, err := assets.Open(fmt.Sprintf("/templates/%s_flags_generated.gotpl", packageName))
if err != nil {
return nil, err
}
templateFileBytes, err := ioutil.ReadAll(templateFile)
2019-03-06 15:04:18 +00:00
if err != nil {
return nil, err
2019-03-06 15:04:18 +00:00
}
return templateFileBytes, nil
2019-03-06 15:04:18 +00:00
}