Created
March 4, 2022 12:23
-
-
Save jfjensen/12969f2c6688a119c2b76eda5b85a580 to your computer and use it in GitHub Desktop.
This is the main code for generating the builder design pattern from templates.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"bytes" | |
"fmt" | |
"github.com/Masterminds/sprig" | |
"go/format" | |
"html/template" | |
"log" | |
"os" | |
) | |
type Data struct { | |
ProductTarget string | |
ConcreteTargets []string | |
Properties []Property | |
} | |
type Property struct { | |
Name string | |
TypeName string | |
} | |
func main() { | |
data := Data{ | |
ProductTarget: "house", | |
ConcreteTargets: []string{"normal", "igloo"}, | |
Properties: []Property{ | |
{"windowType", "string"}, | |
{"doorType", "string"}, | |
{"floor", "int"}, | |
}, | |
} | |
processTemplate("iBuilder.tmpl", "iBuilder.go", data) | |
processTemplate("ProductTarget.tmpl", data.ProductTarget+".go", data) | |
processTemplate("director.tmpl", "director.go", data) | |
processTemplate("sample_main.tmpl", "sample_main.go", data) | |
processConcreteTargets("ConcreteTarget.tmpl", data) | |
fmt.Println("Remember to edit the files that contain the Concrete Targets!") | |
} | |
func processTemplate(fileName string, outputFile string, data Data) { | |
tmpl := template.Must(template.New("").Funcs(sprig.FuncMap()).ParseFiles(fileName)) | |
var processed bytes.Buffer | |
err := tmpl.ExecuteTemplate(&processed, fileName, data) | |
if err != nil { | |
log.Fatalf("Unable to parse data into template: %v\n", err) | |
} | |
formatted, err := format.Source(processed.Bytes()) | |
if err != nil { | |
log.Fatalf("Could not format processed template: %v\n", err) | |
} | |
outputPath := "./tmp/" + outputFile | |
fmt.Println("Writing file: ", outputPath) | |
f, _ := os.Create(outputPath) | |
w := bufio.NewWriter(f) | |
w.WriteString(string(formatted)) | |
w.Flush() | |
} | |
func processConcreteTargets(fileName string, data Data) { | |
for _, value := range data.ConcreteTargets { | |
newData := data | |
newData.ConcreteTargets = []string{value} | |
processTemplate(fileName, value+".go", newData) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment