Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Format go templates #147

Merged
merged 1 commit into from
May 11, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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