@@ -17,7 +17,9 @@ limitations under the License.
17
17
package util
18
18
19
19
import (
20
+ "bytes"
20
21
"fmt"
22
+ "go/format"
21
23
"io/ioutil"
22
24
"log"
23
25
"os"
@@ -50,10 +52,6 @@ func WriteIfNotFound(path, templateName, templateValue string, data interface{})
50
52
}
51
53
52
54
func Write (path , templateName , templateValue string , data interface {}) bool {
53
- if _ , err := os .Stat (path ); os .IsNotExist (err ) {
54
- create (path )
55
- }
56
-
57
55
t := template .Must (template .New (templateName ).Funcs (
58
56
template.FuncMap {
59
57
"title" : strings .Title ,
@@ -62,17 +60,22 @@ func Write(path, templateName, templateValue string, data interface{}) bool {
62
60
},
63
61
).Parse (templateValue ))
64
62
65
- f , err := os .OpenFile (path , os .O_WRONLY , 0 )
63
+ var tmp bytes.Buffer
64
+ err := t .Execute (& tmp , data )
66
65
if err != nil {
67
- log .Fatalf ("Failed to create %s: %v" , path , err )
66
+ log .Fatalf ("Failed to render template %s: %v" , templateName , err )
68
67
}
69
- defer f .Close ()
70
68
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
+ }
74
75
}
75
76
77
+ WriteString (path , string (content ))
78
+
76
79
return true
77
80
}
78
81
0 commit comments