| 71 | ) |
| 72 | |
| 73 | func writeFromTemplate(path string, plan any, tmplName, generatedName string) (changed bool, err error) { |
| 74 | tmplKey := tmplName + ".tmpl" |
| 75 | tmpl := tmplCache[tmplKey] |
| 76 | if tmpl == nil { |
| 77 | tmpl = template.New(tmplKey) |
| 78 | tmpl.Funcs(templateFuncs) |
| 79 | |
| 80 | var err error |
| 81 | glob := "tmpl/" + tmplKey |
| 82 | tmpl, err = tmpl.ParseFS(tmplFS, glob) |
| 83 | if err != nil { |
| 84 | return false, redact.Errorf("parse embedded tmplFS glob %q: %v", redact.Safe(glob), redact.Safe(err)) |
| 85 | } |
| 86 | tmplCache[tmplKey] = tmpl |
| 87 | } |
| 88 | tmplBuf.Reset() |
| 89 | if err := tmpl.Execute(&tmplBuf, plan); err != nil { |
| 90 | return false, redact.Errorf("execute template %s: %v", redact.Safe(tmplKey), err) |
| 91 | } |
| 92 | |
| 93 | // In some circumstances, Nix looks at the mod time of a file when |
| 94 | // caching, so we only want to update the file if something has |
| 95 | // changed. Blindly overwriting the file could invalidate Nix's cache |
| 96 | // every time, slowing down evaluation considerably. |
| 97 | changed, err = overwriteFileIfChanged(filepath.Join(path, generatedName), tmplBuf.Bytes(), 0o644) |
| 98 | if err != nil { |
| 99 | return changed, redact.Errorf("write %s to file: %v", redact.Safe(tmplName), err) |
| 100 | } |
| 101 | return changed, nil |
| 102 | } |
| 103 | |
| 104 | // overwriteFileIfChanged checks that the contents of f == data, and overwrites |
| 105 | // f if they differ. It also ensures that f's permissions are set to perm. |