atomicfile

package
v1.7.20 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 18, 2024 License: Apache-2.0 Imports: 6 Imported by: 1

Documentation

Overview

Package atomicfile provides a mechanism (on Unix-like platforms) to present a consistent view of a file to separate processes even while the file is being written. This is accomplished by writing a temporary file, syncing to disk, and renaming over the destination file name.

Partial/inconsistent reads can occur due to:

  1. A process attempting to read the file while it is being written to (both in the case of a new file with a short/incomplete write or in the case of an existing, updated file where new bytes may be written at the beginning but old bytes may still be present after).
  2. Concurrent goroutines leading to multiple active writers of the same file.

The above mechanism explicitly protects against (1) as all writes are to a file with a temporary name.

There is no explicit protection against multiple, concurrent goroutines attempting to write the same file. However, atomically writing the file should mean only one writer will "win" and a consistent file will be visible.

Note: atomicfile is partially implemented for Windows. The Windows codepath performs the same operations, however Windows does not guarantee that a rename operation is atomic; a crash in the middle may leave the destination file truncated rather than with the expected content.

Index

Constants

This section is empty.

Variables

View Source
var ErrClosed = errors.New("file is closed")

ErrClosed is returned if Read or Write are called on a closed File.

Functions

This section is empty.

Types

type File

type File interface {
	io.ReadWriteCloser
	// Cancel abandons a change to a file. This can be called if a write fails or another error occurs.
	Cancel() error
}

File is an io.ReadWriteCloser that can also be Canceled if a change needs to be abandoned.

func New

func New(name string, mode os.FileMode) (File, error)

New returns a new atomic file. On Unix-like platforms, the writer (an io.ReadWriteCloser) is backed by a temporary file placed into the same directory as the destination file (using filepath.Dir to split the directory from the name). On a call to Close the temporary file is synced to disk and renamed to its final name, hiding any previous file by the same name.

Note: Take care to call Close and handle any errors that are returned. Errors returned from Close may indicate that the file was not written with its final name.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL