Skip to content

Commit

Permalink
Merge pull request #147 from kragniz/gofmt-templates
Browse files Browse the repository at this point in the history
Format go templates
  • Loading branch information
droot authored May 11, 2018
2 parents a5bc55b + c4b82ae commit 7ed8000
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions cmd/kubebuilder/util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ limitations under the License.
package util

import (
"bytes"
"fmt"
"go/format"
"io/ioutil"
"log"
"os"
Expand Down Expand Up @@ -50,10 +52,6 @@ func WriteIfNotFound(path, templateName, templateValue string, data interface{})
}

func Write(path, templateName, templateValue string, data interface{}) bool {
if _, err := os.Stat(path); os.IsNotExist(err) {
create(path)
}

t := template.Must(template.New(templateName).Funcs(
template.FuncMap{
"title": strings.Title,
Expand All @@ -62,17 +60,22 @@ func Write(path, templateName, templateValue string, data interface{}) bool {
},
).Parse(templateValue))

f, err := os.OpenFile(path, os.O_WRONLY, 0)
var tmp bytes.Buffer
err := t.Execute(&tmp, data)
if err != nil {
log.Fatalf("Failed to create %s: %v", path, err)
log.Fatalf("Failed to render template %s: %v", templateName, err)
}
defer f.Close()

err = t.Execute(f, data)
if err != nil {
log.Fatalf("Failed to create %s: %v", path, err)
content := tmp.Bytes()
if filepath.Ext(path) == ".go" {
content, err = format.Source(content)
if err != nil {
log.Fatalf("Failed to format template %s: %v", templateName, err)
}
}

WriteString(path, string(content))

return true
}

Expand Down

0 comments on commit 7ed8000

Please sign in to comment.