func (t *Template) Run() (result *task.Result, err error) { result, err = task.DoRun(func(result *task.Result) (err error) { result.Module = "template" result.Op = "create" result.Extra["path"] = t.Path result.Extra["content"] = t.Content result.Extra["data"] = t.Data result.Extra["mode"] = fmt.Sprintf("%o", t.Mode) tmpl, err := templateutil.NewWithString(t.Path, t.Content) if err != nil { return } changed, err := templateutil.WriteIfChanged(tmpl, t.Data, t.Path, t.Mode) if err != nil { return } if changed { result.Changed = true } else { result.Skipped = true } return }) return }
func TestWriteIfChanged(t *testing.T) { tmpl, err := templateutil.NewWithString("sample1.tmpl", SAMPLE1_TMPL) if err != nil { t.Fatal(err) } f, err := ioutil.TempFile("", "output-") if err != nil { t.Fatal(err) } defer os.Remove(f.Name()) data := map[string]interface{}{ "ntp_servers": []string{ "ntp.nict.jp", "ntp.jst.mfeed.ad.jp", "ntp.ring.gr.jp", }, } changed, err := templateutil.WriteIfChanged(tmpl, data, f.Name(), 0644) if err != nil { t.Fatal(err) } if !changed { t.Fatal("First write must change the file content") } changed, err = templateutil.WriteIfChanged(tmpl, data, f.Name(), 0644) if err != nil { t.Fatal(err) } if changed { t.Fatal("Second write must not overwrite because the content is the same.") } }