Skip to content

Commit 7ed8000

Browse files
authored
Merge pull request #147 from kragniz/gofmt-templates
Format go templates
2 parents a5bc55b + c4b82ae commit 7ed8000

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

cmd/kubebuilder/util/util.go

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@ limitations under the License.
1717
package util
1818

1919
import (
20+
"bytes"
2021
"fmt"
22+
"go/format"
2123
"io/ioutil"
2224
"log"
2325
"os"
@@ -50,10 +52,6 @@ func WriteIfNotFound(path, templateName, templateValue string, data interface{})
5052
}
5153

5254
func Write(path, templateName, templateValue string, data interface{}) bool {
53-
if _, err := os.Stat(path); os.IsNotExist(err) {
54-
create(path)
55-
}
56-
5755
t := template.Must(template.New(templateName).Funcs(
5856
template.FuncMap{
5957
"title": strings.Title,
@@ -62,17 +60,22 @@ func Write(path, templateName, templateValue string, data interface{}) bool {
6260
},
6361
).Parse(templateValue))
6462

65-
f, err := os.OpenFile(path, os.O_WRONLY, 0)
63+
var tmp bytes.Buffer
64+
err := t.Execute(&tmp, data)
6665
if err != nil {
67-
log.Fatalf("Failed to create %s: %v", path, err)
66+
log.Fatalf("Failed to render template %s: %v", templateName, err)
6867
}
69-
defer f.Close()
7068

71-
err = t.Execute(f, data)
72-
if err != nil {
73-
log.Fatalf("Failed to create %s: %v", path, err)
69+
content := tmp.Bytes()
70+
if filepath.Ext(path) == ".go" {
71+
content, err = format.Source(content)
72+
if err != nil {
73+
log.Fatalf("Failed to format template %s: %v", templateName, err)
74+
}
7475
}
7576

77+
WriteString(path, string(content))
78+
7679
return true
7780
}
7881

0 commit comments

Comments
 (0)