Skip to content

Commit 44c011a

Browse files
authored
Merge pull request #24 from terrastruct/atomic-write
add atomic write
2 parents b88c69b + 2ba1ac9 commit 44c011a

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

xmain/xmain.go

+33
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,39 @@ func (ms *State) WritePath(fp string, p []byte) error {
182182
return os.WriteFile(fp, p, 0644)
183183
}
184184

185+
func (ms *State) AtomicWritePath(fp string, p []byte) error {
186+
if fp == "-" {
187+
return ms.WritePath(fp, p)
188+
}
189+
190+
dir := filepath.Dir(fp)
191+
base := filepath.Base(fp)
192+
tempFile, err := os.CreateTemp(dir, "tmp-"+base+"-")
193+
if err != nil {
194+
return err
195+
}
196+
defer func() {
197+
// Clean up temporary file if it still exists and there's an error
198+
if err != nil {
199+
os.Remove(tempFile.Name())
200+
}
201+
}()
202+
203+
if _, err = tempFile.Write(p); err != nil {
204+
return err
205+
}
206+
207+
if err = tempFile.Close(); err != nil {
208+
return err
209+
}
210+
211+
if err = os.Rename(tempFile.Name(), fp); err != nil {
212+
return err
213+
}
214+
215+
return nil
216+
}
217+
185218
// AbsPath joins the PWD with fp to give the absolute path to fp.
186219
func (ms *State) AbsPath(fp string) string {
187220
if fp == "-" || filepath.IsAbs(fp) {

0 commit comments

Comments
 (0)