Beispiel #1
0
func execute(gen genex.Generator, src, name string, params map[string]interface{}) error {
	// Format the output.
	funcMap := map[string]interface{}{
		"join": func(s []string) string {
			return strings.Join(s, ",")
		},
	}
	t := template.Must(template.New("").Funcs(funcMap).Parse(src))
	var buf bytes.Buffer
	t.Execute(&buf, params)
	gen.Printf("%s", buf.String())
	formattedSrc := gen.Format()

	// Write to file.
	return ioutil.WriteFile(name, formattedSrc, 0644)
}
Beispiel #2
0
func run() int {
	var (
		args = flag.Args()
		g    genex.Generator
	)

	// Print the header and package clause.
	g.Printf("// Code generated by gen-config.\n")
	// Run generate for each type.
	filename := []string{}
	config := map[string]interface{}{}
	for _, fp := range genex.MustParseGlobs(args[:]) {
		if strings.HasSuffix(fp, ".tml") {
			if _, err := toml.DecodeFile(fp, &config); err == nil {
				g.Printf("// %s\n", fp)
				filename = append(filename, fp)
			}
		}
	}
	g.Printf("// DO NOT EDIT\n")
	g.Printf("\npackage %s\n", *pkg)

	// Generate two source files.
	params := map[string]interface{}{}
	params["ConfigDir"] = *confDir
	params["TypeBody"] = printer(config)
	params["Filename"] = func() (ret []string) {
		for _, v := range filename {
			ret = append(ret, strings.Replace(v, *confDir+"/", "", -1))
		}
		return
	}()
	params["StructName"] = func(cfg map[string]interface{}) (ret []map[string]string) {
		for k, _ := range cfg {
			elm := map[string]string{}
			elm["Struct"] = snaker.SnakeToCamel(k)
			elm["Tag"] = fmt.Sprintf("`toml:\"%s\"`", k)
			ret = append(ret, elm)
		}
		return
	}(config)

	// Format the output.
	t := template.Must(template.New("").Parse(text))
	var buf bytes.Buffer
	t.Execute(&buf, params)
	g.Printf("%s", buf.String())
	src := g.Format()

	// Write to file.
	outputName := *output
	if outputName == "" {
		baseName := OUTPUT
		outputName = filepath.Join(*srcDir, strings.ToLower(baseName))
	}
	err := ioutil.WriteFile(outputName, src, 0644)
	if err != nil {
		log.Fatalf("writing output: %s", err)
	}

	return 0
}