| 1 | // Copyright 2018 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | // Package renameio writes files atomically by renaming temporary files. |
| 6 | // |
| 7 | // Deprecated: Use [github.com/google/renameio/v2] instead. |
| 8 | package renameio |
| 9 | |
| 10 | import ( |
| 11 | "bytes" |
| 12 | "io" |
| 13 | "os" |
| 14 | "path/filepath" |
| 15 | ) |
| 16 | |
| 17 | const patternSuffix = "*.tmp" |
| 18 | |
| 19 | // Pattern returns a glob pattern that matches the unrenamed temporary files |
| 20 | // created when writing to filename. |
| 21 | func Pattern(filename string) string { |
| 22 | return filepath.Join(filepath.Dir(filename), filepath.Base(filename)+patternSuffix) |
| 23 | } |
| 24 | |
| 25 | // WriteFile is like ioutil.WriteFile, but first writes data to an arbitrary |
| 26 | // file in the same directory as filename, then renames it atomically to the |
| 27 | // final name. |
| 28 | // |
| 29 | // That ensures that the final location, if it exists, is always a complete file. |
| 30 | func WriteFile(filename string, data []byte) (err error) { |
| 31 | return WriteToFile(filename, bytes.NewReader(data)) |
| 32 | } |
| 33 | |
| 34 | // WriteToFile is a variant of WriteFile that accepts the data as an io.Reader |
| 35 | // instead of a slice. |
| 36 | func WriteToFile(filename string, data io.Reader) (err error) { |
| 37 | f, err := os.CreateTemp(filepath.Dir(filename), filepath.Base(filename)+patternSuffix) |
| 38 | if err != nil { |
| 39 | return err |
| 40 | } |
| 41 | defer func() { |
| 42 | // Only call os.Remove on f.Name() if we failed to rename it: otherwise, |
| 43 | // some other process may have created a new file with the same name after |
| 44 | // that. |
| 45 | if err != nil { |
| 46 | f.Close() |
| 47 | os.Remove(f.Name()) |
| 48 | } |
| 49 | }() |
| 50 | |
| 51 | if _, err := io.Copy(f, data); err != nil { |
| 52 | return err |
| 53 | } |
| 54 | // Sync the file before renaming it: otherwise, after a crash the reader may |
| 55 | // observe a 0-length file instead of the actual contents. |
| 56 | // See https://golang.org/issue/22397#issuecomment-380831736. |
| 57 | if err := f.Sync(); err != nil { |
| 58 | return err |
| 59 | } |
| 60 | if err := f.Close(); err != nil { |
| 61 | return err |
| 62 | } |
| 63 | return os.Rename(f.Name(), filename) |
| 64 | } |