PlatformAtomicWriteFile atomically writes a file to disk with file locking to prevent concurrent writes. This is particularly useful on Windows where concurrent writes to the same file can cause "Access Denied" errors. The function acquires a lock on the target file and performs an atomic write, pr
(filename string, reader io.Reader, mode os.FileMode)
| 33 | // preserving the existing behaviour of overwriting any previous content once |
| 34 | // the lock is obtained. |
| 35 | func PlatformAtomicWriteFile(filename string, reader io.Reader, mode os.FileMode) error { |
| 36 | // Use a separate lock file to coordinate access between processes |
| 37 | // We cannot lock the target file directly as it would prevent the atomic rename |
| 38 | lockFileName := filename + ".lock" |
| 39 | fileLock := flock.New(lockFileName) |
| 40 | |
| 41 | // Lock() ensures serialized access - if another process is writing, this will wait |
| 42 | if err := fileLock.Lock(); err != nil { |
| 43 | return err |
| 44 | } |
| 45 | defer func() { |
| 46 | fileLock.Unlock() |
| 47 | // Clean up the lock file |
| 48 | // Ignore errors as the file might not exist or be in use by another process |
| 49 | os.Remove(lockFileName) |
| 50 | }() |
| 51 | |
| 52 | // Perform the atomic write while holding the lock |
| 53 | return AtomicWriteFile(filename, reader, mode) |
| 54 | } |
nothing calls this directly
no test coverage detected
searching dependent graphs…