1
1
package main
2
2
3
3
import (
4
+ "bytes"
4
5
"encoding/json"
5
6
"flag"
6
7
"fmt"
@@ -122,7 +123,7 @@ func usage() {
122
123
println ("Usage: docker-gen [-config file] [-watch=false] [-notify=\" restart xyz\" ] <template> [<dest>]" )
123
124
}
124
125
125
- func generateFile (config Config , containers []* RuntimeContainer ) {
126
+ func generateFile (config Config , containers []* RuntimeContainer ) bool {
126
127
templatePath := config .Template
127
128
tmpl , err := template .New (filepath .Base (templatePath )).Funcs (template.FuncMap {
128
129
"contains" : contains ,
@@ -149,24 +150,40 @@ func generateFile(config Config, containers []*RuntimeContainer) {
149
150
dest , err = ioutil .TempFile ("" , "docker-gen" )
150
151
defer dest .Close ()
151
152
if err != nil {
152
- fmt .Println ("unable to create temp file: %s\n " , err )
153
+ fmt .Printf ("unable to create temp file: %s\n " , err )
153
154
os .Exit (1 )
154
155
}
155
156
}
156
157
157
- err = tmpl .ExecuteTemplate (dest , filepath .Base (templatePath ), containers )
158
+ var buf bytes.Buffer
159
+ multiwriter := io .MultiWriter (dest , & buf )
160
+ err = tmpl .ExecuteTemplate (multiwriter , filepath .Base (templatePath ), containers )
158
161
if err != nil {
159
162
fmt .Printf ("template error: %s\n " , err )
160
163
}
161
164
162
165
if config .Dest != "" {
163
- err = os .Rename (dest .Name (), config .Dest )
164
- if err != nil {
165
- fmt .Println ("unable to create dest file %s: %s\n " , config .Dest , err )
166
- os .Exit (1 )
166
+
167
+ contents := []byte {}
168
+ if _ , err := os .Stat (config .Dest ); err == nil {
169
+ contents , err = ioutil .ReadFile (config .Dest )
170
+ if err != nil {
171
+ fmt .Printf ("unable to compare current file contents: %s: %s\n " , config .Dest , err )
172
+ os .Exit (1 )
173
+ }
167
174
}
168
- }
169
175
176
+ if bytes .Compare (contents , buf .Bytes ()) != 0 {
177
+ err = os .Rename (dest .Name (), config .Dest )
178
+ if err != nil {
179
+ fmt .Printf ("unable to create dest file %s: %s\n " , config .Dest , err )
180
+ os .Exit (1 )
181
+ }
182
+ return true
183
+ }
184
+ return false
185
+ }
186
+ return true
170
187
}
171
188
172
189
func newConn () (* httputil.ClientConn , error ) {
@@ -274,8 +291,11 @@ func generateFromContainers(client *docker.Client) {
274
291
}
275
292
276
293
for _ , config := range configs .Config {
277
- generateFile (config , containers )
278
- runNotifyCmd (config )
294
+ changed := generateFile (config , containers )
295
+ if changed {
296
+ runNotifyCmd (config )
297
+ }
298
+
279
299
}
280
300
281
301
}
0 commit comments