diff --git a/.github/workflows/scripts/copywrite.hcl b/.github/workflows/scripts/copywrite.hcl deleted file mode 100644 index c9215e0..0000000 --- a/.github/workflows/scripts/copywrite.hcl +++ /dev/null @@ -1,15 +0,0 @@ -schema_version = 1 - -project { - license = "BSD-3-Clause" - copyright_holder = "CattleCloud LLC" - copyright_year = 2025 - header_ignore = [ - "**/*.sh", - ".src/**", - ".bin/**", - ".github/**", - ".golangci.yaml", - ] -} - diff --git a/.golangci.yaml b/.golangci.yaml deleted file mode 100644 index 56b632c..0000000 --- a/.golangci.yaml +++ /dev/null @@ -1,40 +0,0 @@ -run: - timeout: 5m -linters: - enable: - - asasalint - - asciicheck - - bidichk - - bodyclose - - dogsled - - dupword - - durationcheck - - errcheck - - errname - - errorlint - - exhaustive - - exportloopref - - gochecknoinits - - gocritic - - gofmt - - gosimple - - govet - - ineffassign - - makezero - - misspell - - musttag - - nilnil - - noctx - - perfsprint - - prealloc - - predeclared - - reassign - - revive - - rowserrcheck - - staticcheck - - sqlclosecheck - - tagalign - - tenv - - unused - - whitespace - diff --git a/Justfile b/Justfile index c06bf6d..bbd8b2d 100644 --- a/Justfile +++ b/Justfile @@ -42,4 +42,4 @@ lint: vet # locally install build dependencies [group('build')] init: - go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.11.4 + go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.15.0 diff --git a/README.md b/README.md index c4ee11f..e233d4b 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ A library for atomic filesystem operations in Go. # Overview -The `cattlecloud.net/go/atomicfs` module provides a package for performing atomic +The `cattlecloud.net/go/atomicfs/v2` module provides a package for performing atomic filesystem operations. #### Reading material @@ -25,18 +25,22 @@ go get cattlecloud.net/go/atomicfs@latest ``` ```go -import "cattlecloud.net/go/atomicfs" +import "cattlecloud.net/go/atomicfs/v2" ``` #### Examples +Written files default to mode `0660` (read-write for the owner and group). +Pass `atomicfs.WithMode` to override it: + ```go -writer := atomicfs.NewFileWriter(atomicfs.Options{ - TmpDirectory: "/tmp", - Mode: 0600, -}) +writer := atomicfs.New( + atomicfs.WithTempDir("/tmp"), + atomicfs.WithMode(0600), // custom file mode +) -_ = writer.Write(input, output) +input := strings.NewReader("hello, world") +_ = writer.WriteFile("/path/to/output.txt", input) ``` # Contributing diff --git a/atomicfs.go b/atomicfs.go index 9f28449..93fec17 100644 --- a/atomicfs.go +++ b/atomicfs.go @@ -12,108 +12,80 @@ import ( "os" "path/filepath" "strings" - "syscall" - - "cattlecloud.net/go/atomicfs/fs" - "cattlecloud.net/go/atomicfs/sys" ) -// A FileWriter is used to read content from a source and write it to a -// destination file, or die trying without producing corrupt data where the -// destination file should have been. +// A Writer writes the contents of an io.Reader to a destination file +// atomically, or fails without leaving corrupt data in place of the +// destination file. // -// The primary design goal of a FileWriter is correctness and reliability. +// The primary design goal of a Writer is correctness and reliability. // // Performance is not a consideration. -type FileWriter interface { - // WriteFile will write the contents of the io.Reader into a file at the - // given destination filepath. - WriteFile(string, io.Reader) error -} - -// Options are used to configure the behavior of a FileWriter when it is used -// to write a file. -type Options struct { - // TmpDirectory is where tmp files are generated during - // the process of writing a file in preparation for executing - // an atomic rename. Because of this, TmpDirectory *MUST* be on - // the same filesystem device as the destination file being - // written, otherwise, errors will be returned during the Write. - TmpDirectory string - - // TmpExtension is used to demarcate the tmp files generated - // during the Write operation from other normal files. The - // extension is appended to the end of the filename of the - // destination file being written. - TmpExtension string - - // Mode is the file mode of the destination file to be written. - // If no Mode is provided, write only permissions for the user - // are used (i.e. 0200). - Mode os.FileMode - - // FS is the underlying filesystem implementation to be used - // for writing files to disk. Typically this should be left - // nil, as then fs.FileSystem is used, which in turn is - // implemented using the file operations defined in the os - // package. - FS fs.FileSystem - - // Sys is the underlying syscall implementation to be used, - // in this case only for stat-ing files. Typically this should - // be left nil, as then sys.Syscall is used, which in turn is - // implemented using the syscall implementation provided by - // the go runtime. - Sys sys.Syscall +type Writer struct { + tempDir string + tempExt string + mode os.FileMode } -// New creates a new FileWriter backed by the configuration settings in the -// provided Options. Creating a FileWriter always succeeds, replacing empty -// options with sane defaults. -func New(options Options) FileWriter { - tmpExt := strings.TrimPrefix(options.TmpExtension, ".") - if tmpExt == "" { - tmpExt = "tmp" - } +// An Option configures the behavior of a Writer. +type Option func(*Writer) - tmpDir := options.TmpDirectory - if tmpDir == "" { - tmpDir = os.TempDir() +// WithTempDir sets the directory where temporary files are created during the +// process of writing a file in preparation for an atomic rename. +// +// The temp dir must be on the same filesystem device as the destination file, +// otherwise errors will be returned during the write. +// +// Defaults to os.TempDir(). +func WithTempDir(dir string) Option { + return func(w *Writer) { + if dir != "" { + w.tempDir = dir + } } +} - mode := options.Mode - if mode == 0 { - mode = os.FileMode(0200) +// WithTempExtension sets the extension used to demarcate the temporary files +// created during a write from other normal files. The extension is appended to +// the end of the destination file name; any leading dots are stripped. +// +// Defaults to "tmp". +func WithTempExtension(ext string) Option { + ext = strings.TrimLeft(ext, ".") + return func(w *Writer) { + if ext != "" { + w.tempExt = ext + } } +} - fileSystem := options.FS - if fileSystem == nil { - fileSystem = fs.New() +// WithMode sets the file mode of the destination file to be written. +// +// Defaults to 0660 (read-write for the owner and group). +func WithMode(mode os.FileMode) Option { + return func(w *Writer) { + if mode != 0 { + w.mode = mode + } } +} - systemCalls := options.Sys - if systemCalls == nil { - systemCalls = sys.New() +// New creates a Writer configured with the given options. The options are +// applied in order; later options override earlier ones. +func New(options ...Option) *Writer { + w := &Writer{ + tempDir: os.TempDir(), + tempExt: "tmp", + mode: os.FileMode(0660), } - - return &writer{ - tmpDir: tmpDir, - tmpExt: tmpExt, - fileMode: mode, - fs: fileSystem, - sys: systemCalls, + for _, option := range options { + option(w) } + return w } -type writer struct { - tmpDir string - tmpExt string - fileMode os.FileMode - fs fs.FileSystem - sys sys.Syscall -} - -func (w *writer) WriteFile(filePath string, source io.Reader) error { +// WriteFile writes the contents of source into a file at filePath, atomically. +func (w *Writer) WriteFile(filePath string, source io.Reader) error { fileDir := filepath.Dir(filePath) fileName := filepath.Base(filePath) @@ -128,31 +100,32 @@ func (w *writer) WriteFile(filePath string, source io.Reader) error { // a complete flush (fsync) tmpPath, err := w.writeTmp(source, fileName) if err != nil { - _ = w.fs.Remove(tmpPath) + if tmpPath != "" { + _ = os.Remove(tmpPath) + } return err } // 3) since we know the tmp file and destination file exist on the // same device, a filesystem rename will be an atomic operation if err := w.rename(tmpPath, filePath); err != nil { - _ = w.fs.Remove(tmpPath) + _ = os.Remove(tmpPath) return err } return nil } -func (w *writer) checkDevice(fileDir string) error { - var stat syscall.Stat_t - if err := w.sys.Stat(fileDir, &stat); err != nil { +func (w *Writer) checkDevice(fileDir string) error { + fileDirDeviceID, err := deviceID(fileDir) + if err != nil { return fmt.Errorf("atomicfs: unable to stat destination directory %s: %w", fileDir, err) } - fileDirDeviceID := stat.Dev - if err := w.sys.Stat(w.tmpDir, &stat); err != nil { - return fmt.Errorf("atomicfs: unable to stat tmp directory %s: %w", w.tmpDir, err) + tmpDirDeviceID, err := deviceID(w.tempDir) + if err != nil { + return fmt.Errorf("atomicfs: unable to stat tmp directory %s: %w", w.tempDir, err) } - tmpDirDeviceID := stat.Dev if fileDirDeviceID != tmpDirDeviceID { return errors.New("atomicfs: tmp & destination directories not on same device") @@ -161,16 +134,16 @@ func (w *writer) checkDevice(fileDir string) error { return nil } -func (w *writer) rename(previous, next string) error { - if err := w.fs.Rename(previous, next); err != nil { +func (w *Writer) rename(previous, next string) error { + if err := os.Rename(previous, next); err != nil { return fmt.Errorf("atomicfs: unable to rename tmp file %s to %s: %w", previous, next, err) } return w.syncDir(next) } -func (w *writer) syncDir(name string) error { +func (w *Writer) syncDir(name string) error { directory := filepath.Dir(name) - f, err := w.fs.Open(directory) + f, err := os.Open(directory) if err != nil { return fmt.Errorf("atomicfs: unable to open directory %s for syncing: %w", directory, err) } @@ -186,32 +159,32 @@ func (w *writer) syncDir(name string) error { return nil } -func (w *writer) writeTmp(source io.Reader, name string) (string, error) { - tmpName := fmt.Sprintf("%s.%s", name, w.tmpExt) +func (w *Writer) writeTmp(source io.Reader, name string) (string, error) { + tmpName := name + "." + w.tempExt - f, err := os.CreateTemp(w.tmpDir, tmpName) + f, err := os.CreateTemp(w.tempDir, tmpName) if err != nil { - return "", fmt.Errorf("atomicfs: unable to create tmp file in %s: %w", w.tmpDir, err) + return "", fmt.Errorf("atomicfs: unable to create tmp file in %s: %w", w.tempDir, err) } tmpPath := f.Name() - if err := f.Chmod(w.fileMode); err != nil { + if err := f.Chmod(w.mode); err != nil { _ = f.Close() - return tmpPath, fmt.Errorf("atomicfs: unable to chmod tmp file in %s: %w", w.tmpDir, err) + return tmpPath, fmt.Errorf("atomicfs: unable to chmod tmp file in %s: %w", w.tempDir, err) } if _, err := io.Copy(f, source); err != nil { _ = f.Close() - return tmpPath, fmt.Errorf("atomicfs: unable to copy source into tmp file in %s: %w", w.tmpDir, err) + return tmpPath, fmt.Errorf("atomicfs: unable to copy source into tmp file in %s: %w", w.tempDir, err) } if err := f.Sync(); err != nil { _ = f.Close() - return tmpPath, fmt.Errorf("atomicfs: unable to fsync tmp file in %s: %w", w.tmpDir, err) + return tmpPath, fmt.Errorf("atomicfs: unable to fsync tmp file in %s: %w", w.tempDir, err) } if err := f.Close(); err != nil { - return tmpPath, fmt.Errorf("atomicfs: unable to close tmp file in %s: %w", w.tmpDir, err) + return tmpPath, fmt.Errorf("atomicfs: unable to close tmp file in %s: %w", w.tempDir, err) } return tmpPath, nil diff --git a/atomicfs_test.go b/atomicfs_test.go index 842f82f..2f17191 100644 --- a/atomicfs_test.go +++ b/atomicfs_test.go @@ -4,28 +4,47 @@ package atomicfs import ( + "os" "path/filepath" "strings" "testing" - "cattlecloud.net/go/atomicfs/fs" - "cattlecloud.net/go/atomicfs/sys" "github.com/shoenig/test/must" ) -func TestFileWriter_WriteFile(t *testing.T) { - tmpDir := t.TempDir() +func TestWriter_WriteFile(t *testing.T) { + dir := t.TempDir() - writer := New(Options{ - TmpDirectory: tmpDir, - TmpExtension: ".tempfile", - Mode: 0600, - FS: fs.New(), - Sys: sys.New(), - }) + writer := New( + WithTempDir(dir), + WithTempExtension(".tempfile"), + WithMode(0600), + ) input := strings.NewReader("foobar") - filePath := filepath.Join(tmpDir, "out.txt") - err := writer.WriteFile(filePath, input) + filePath := filepath.Join(dir, "out.txt") + must.NoError(t, writer.WriteFile(filePath, input)) + + content, err := os.ReadFile(filePath) + must.NoError(t, err) + must.Eq(t, "foobar", string(content)) + + info, err := os.Stat(filePath) must.NoError(t, err) + must.Eq(t, os.FileMode(0600), info.Mode()) +} + +func TestWriter_WriteFile_defaults(t *testing.T) { + writer := New() + must.Eq(t, os.TempDir(), writer.tempDir) + must.Eq(t, "tmp", writer.tempExt) + must.Eq(t, os.FileMode(0660), writer.mode) +} + +func TestWriter_WriteFile_missingDirectory(t *testing.T) { + writer := New(WithTempDir(t.TempDir())) + + filePath := filepath.Join(t.TempDir(), "missing", "out.txt") + err := writer.WriteFile(filePath, strings.NewReader("x")) + must.Error(t, err) } diff --git a/device_unix.go b/device_unix.go new file mode 100644 index 0000000..635eea1 --- /dev/null +++ b/device_unix.go @@ -0,0 +1,29 @@ +// Copyright (c) CattleCloud LLC +// SPDX-License-Identifier: BSD-3-Clause + +//go:build !windows + +package atomicfs + +import ( + "errors" + "os" + "syscall" +) + +// deviceID returns the filesystem device identifier of the file or directory +// at path. It is used to ensure the tmp and destination directories reside on +// the same device, which is required for an atomic rename. +func deviceID(path string) (uint64, error) { + info, err := os.Stat(path) + if err != nil { + return 0, err + } + + stat, ok := info.Sys().(*syscall.Stat_t) + if !ok { + return 0, errors.New("atomicfs: unable to determine device id") + } + + return uint64(stat.Dev), nil +} diff --git a/device_windows.go b/device_windows.go new file mode 100644 index 0000000..7319343 --- /dev/null +++ b/device_windows.go @@ -0,0 +1,14 @@ +// Copyright (c) CattleCloud LLC +// SPDX-License-Identifier: BSD-3-Clause + +//go:build windows + +package atomicfs + +import "errors" + +// deviceID is unsupported on Windows, where same-device atomic rename and +// directory fsync do not apply. +func deviceID(string) (uint64, error) { + return 0, errors.New("atomicfs: atomic writes are not supported on windows") +} diff --git a/fs/filesystem.go b/fs/filesystem.go deleted file mode 100644 index 5dd2b8a..0000000 --- a/fs/filesystem.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) CattleCloud LLC -// SPDX-License-Identifier: BSD-3-Clause - -package fs - -import ( - "os" - "time" -) - -type FileSystem interface { - Create(name string) (File, error) - Mkdir(name string, perm os.FileMode) error - MkdirAll(path string, perm os.FileMode) error - Open(name string) (File, error) - OpenFile(name string, flag int, perm os.FileMode) (File, error) - Remove(name string) error - RemoveAll(path string) error - Rename(previous, next string) error - Stat(name string) (os.FileInfo, error) -} - -type File interface { - Chdir() error - Chmod(mode os.FileMode) error - Chown(uid, gid int) error - Close() error - Fd() uintptr - Name() string - Read(b []byte) (n int, err error) - ReadAt(b []byte, off int64) (n int, err error) - Readdir(n int) ([]os.FileInfo, error) - Readdirnames(n int) (names []string, err error) - Seek(offset int64, whence int) (ret int64, err error) - SetDeadline(t time.Time) error - SetReadDeadline(t time.Time) error - SetWriteDeadline(t time.Time) error - Stat() (os.FileInfo, error) - Sync() error - Truncate(size int64) error - Write(b []byte) (n int, err error) - WriteAt(b []byte, off int64) (n int, err error) - WriteString(s string) (n int, err error) -} diff --git a/fs/osfs.go b/fs/osfs.go deleted file mode 100644 index 220a91c..0000000 --- a/fs/osfs.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) CattleCloud LLC -// SPDX-License-Identifier: BSD-3-Clause - -package fs - -import "os" - -type osFS struct{} - -var _ FileSystem = (*osFS)(nil) -var _ File = (*os.File)(nil) - -func New() FileSystem { - return &osFS{} -} - -func (*osFS) Create(name string) (File, error) { - return os.Create(name) -} - -func (*osFS) Mkdir(name string, perm os.FileMode) error { - return os.Mkdir(name, perm) -} - -func (*osFS) MkdirAll(path string, perm os.FileMode) error { - return os.MkdirAll(path, perm) -} - -func (*osFS) Open(name string) (File, error) { - return os.Open(name) -} - -func (*osFS) OpenFile(name string, flag int, perm os.FileMode) (File, error) { - return os.OpenFile(name, flag, perm) -} - -func (*osFS) Remove(name string) error { - return os.Remove(name) -} - -func (*osFS) RemoveAll(path string) error { - return os.RemoveAll(path) -} - -func (*osFS) Rename(oldname, newname string) error { - return os.Rename(oldname, newname) -} - -func (*osFS) Stat(name string) (os.FileInfo, error) { - return os.Stat(name) -} diff --git a/fs/osfs_test.go b/fs/osfs_test.go deleted file mode 100644 index 2806a6c..0000000 --- a/fs/osfs_test.go +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright (c) CattleCloud LLC -// SPDX-License-Identifier: BSD-3-Clause - -package fs - -import ( - "os" - "testing" - - "github.com/shoenig/test/must" -) - -func Test_osFS_Create(t *testing.T) { - fs := New() - - f, err := fs.Create("foo.txt") - must.NoError(t, err) - - err = f.Close() - must.NoError(t, err) - - err = os.Remove(f.Name()) - must.NoError(t, err) -} - -func Test_osFS_Mkdir(t *testing.T) { - fs := New() - - err := fs.Mkdir("foo", 0700) - must.NoError(t, err) - - err = os.RemoveAll("foo") - must.NoError(t, err) -} - -func Test_osFS_MkdirAll(t *testing.T) { - fs := New() - - err := fs.MkdirAll("foo/bar/baz", 0700) - must.NoError(t, err) - - err = os.RemoveAll("foo") - must.NoError(t, err) -} - -func Test_osFS_Open(t *testing.T) { - fs := New() - - f, err := fs.Open("/etc/hosts") - must.NoError(t, err) - - err = f.Close() - must.NoError(t, err) -} - -func Test_osFS_OpenFile(t *testing.T) { - fs := New() - - f, err := fs.OpenFile("/etc/hosts", os.O_RDONLY, 0600) - must.NoError(t, err) - - err = f.Close() - must.NoError(t, err) -} - -func Test_osFS_Remove(t *testing.T) { - fs := New() - - f, err := fs.Create("foo.txt") - must.NoError(t, err) - - err = fs.Remove(f.Name()) - must.NoError(t, err) -} - -func Test_osFS_RemoveAll(t *testing.T) { - fs := New() - - err := fs.MkdirAll("foo/bar/baz/", 0700) - must.NoError(t, err) - - err = fs.RemoveAll("foo") - must.NoError(t, err) -} - -func Test_osFS_Rename(t *testing.T) { - fs := New() - - f, err := fs.Create("foo.txt") - must.NoError(t, err) - err = f.Close() - must.NoError(t, err) - - err = fs.Rename("foo.txt", "bar.txt") - must.NoError(t, err) - - err = os.Remove("bar.txt") - must.NoError(t, err) -} - -func Test_osFS_Stat(t *testing.T) { - fs := New() - - info, err := fs.Stat("/etc/hosts") - must.NoError(t, err) - - name := info.Name() - must.Eq(t, "hosts", name) -} diff --git a/go.mod b/go.mod index 0d92264..d9c64fb 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ -module cattlecloud.net/go/atomicfs +module cattlecloud.net/go/atomicfs/v2 -go 1.26 +go 1.27 require github.com/shoenig/test v1.13.2 diff --git a/sys/syscall.go b/sys/syscall.go deleted file mode 100644 index e4fc7b0..0000000 --- a/sys/syscall.go +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) CattleCloud LLC -// SPDX-License-Identifier: BSD-3-Clause - -package sys - -import "syscall" - -type Syscall interface { - Stat(string, *syscall.Stat_t) error -} - -type linuxSyscall struct{} - -var _ Syscall = (*linuxSyscall)(nil) - -func New() Syscall { - return &linuxSyscall{} -} - -func (s *linuxSyscall) Stat(path string, stat *syscall.Stat_t) error { - return syscall.Stat(path, stat) -} diff --git a/sys/syscall_test.go b/sys/syscall_test.go deleted file mode 100644 index 011ea8c..0000000 --- a/sys/syscall_test.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) CattleCloud LLC -// SPDX-License-Identifier: BSD-3-Clause - -package sys - -import ( - "syscall" - "testing" - - "github.com/shoenig/test/must" -) - -func Test_Syscall_Stat_file(t *testing.T) { - sc := New() - var stat syscall.Stat_t - err := sc.Stat("/etc/hosts", &stat) - must.NoError(t, err) - - t.Log("file dev:", stat.Dev) -} - -func Test_Syscall_Stat_dir(t *testing.T) { - sc := New() - var stat syscall.Stat_t - err := sc.Stat("/etc", &stat) - must.NoError(t, err) - - t.Log("etc dev:", stat.Dev) -}