atomicfile

package module
v0.0.0-...-56ae5a8 Latest Latest
Warning

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

Go to latest
Published: May 25, 2020 License: MIT Imports: 3 Imported by: 0

README

atomicfile

Package atomicfile provides *os.File wrapper to allow atomic file writes. Works on Linux, macOS, and Windows.

All writes will go to a temporary file. Call Close() explicitly when you are done writing to atomically rename the file making the changes visible. Call Abort() to discard all your writes.

This allows for a file to always be in a consistent state and never represent an in-progress write.

Installation

Standard go get:

$ go get github.com/sashka/atomicfile

Example

import "github.com/sashka/atomicfile"

// Prepare to write a file.
f, err := atomicfile.New(path, 0o666)

// It's safe to call f.Abort() on a successfully closed file.
// Otherwise it's correct to discard the file changes.
defer f.Abort()

// Update the file.
if _, err := f.Write(content); err != nil {
    return err
}

// Make changes visible.
f.Close()

Documentation

Overview

Package atomicfile wraps os.File to allow atomic file updates.

All writes will go to a temporary file. Close the file when you are done writing to atomically make the changes visible. Abort to discard all your writes. This allows a file to be in a consistent state and never expose an in-progress write.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AtomicRename

func AtomicRename(oldpath, newpath string) error

AtomicRename atomically renames (moves) oldpath to newpath. It is guaranteed to either replace the target file entirely, or not change either file.

Types

type File

type File struct {
	*os.File
	// contains filtered or unexported fields
}

File behaves like os.File, but does an atomic rename operation at Close.

func New

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

New creates a new temporary file that will replace the file at the given path when Closed.

func (*File) Abort

func (f *File) Abort() error

Abort closes the file and removes it, discarding all the changes. It's safe to call Abort on a file which is already committed.

func (*File) Close

func (f *File) Close() error

Close the file replacing the original file.

Jump to

Keyboard shortcuts

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