forked from sneak/util
Compare commits
1 Commits
proposal-r
...
proposal-a
| Author | SHA1 | Date | |
|---|---|---|---|
| 9708301eba |
56
atomicwrite.go
Normal file
56
atomicwrite.go
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
package util
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AtomicWriteFile writes data to path without ever leaving a half-written file
|
||||||
|
// behind. It writes to a temporary file in the same directory, flushes it to
|
||||||
|
// disk, gives it the mode in perm and renames it over path, so anything reading
|
||||||
|
// path sees either the previous contents or the complete new contents and
|
||||||
|
// never something in between. If any step fails, the temporary file is removed
|
||||||
|
// and path is left as it was.
|
||||||
|
//
|
||||||
|
// The temporary file has to live in the same directory as path, because a
|
||||||
|
// rename across two filesystems is not possible and would not be instant if it
|
||||||
|
// were.
|
||||||
|
//
|
||||||
|
// Two details differ from os.WriteFile. The mode is applied after the file is
|
||||||
|
// created, so perm is what the finished file ends up with rather than perm with
|
||||||
|
// the process umask taken out of it. And the directory holding the file is not
|
||||||
|
// flushed, so a machine that loses power immediately after this returns may
|
||||||
|
// come back with the rename undone, even though the data itself was written.
|
||||||
|
func AtomicWriteFile(path string, data []byte, perm os.FileMode) error {
|
||||||
|
directory := filepath.Dir(path)
|
||||||
|
|
||||||
|
temporary, err := os.CreateTemp(directory, "."+filepath.Base(path)+".tmp")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
temporaryPath := temporary.Name()
|
||||||
|
|
||||||
|
// Does nothing once the rename below has succeeded, because by then the
|
||||||
|
// temporary name no longer refers to anything.
|
||||||
|
defer os.Remove(temporaryPath)
|
||||||
|
|
||||||
|
if _, err := temporary.Write(data); err != nil {
|
||||||
|
temporary.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := temporary.Sync(); err != nil {
|
||||||
|
temporary.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := temporary.Close(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := os.Chmod(temporaryPath, perm); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return os.Rename(temporaryPath, path)
|
||||||
|
}
|
||||||
110
atomicwrite_test.go
Normal file
110
atomicwrite_test.go
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
package util
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAtomicWriteFile(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
existing string
|
||||||
|
data []byte
|
||||||
|
perm os.FileMode
|
||||||
|
}{
|
||||||
|
{"a new file", "", []byte("hello"), 0644},
|
||||||
|
{"replacing a shorter file", "old", []byte("a much longer set of contents"), 0644},
|
||||||
|
{"replacing a longer file", "a much longer set of contents", []byte("new"), 0644},
|
||||||
|
{"an empty payload", "something", []byte{}, 0644},
|
||||||
|
{"a nil payload", "something", nil, 0644},
|
||||||
|
{"a private mode", "", []byte("secret"), 0600},
|
||||||
|
{"an executable mode", "", []byte("#!/bin/sh\n"), 0755},
|
||||||
|
{"binary contents", "", []byte{0x00, 0xff, 0x10, 0x00}, 0644},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
directory := t.TempDir()
|
||||||
|
path := filepath.Join(directory, "target")
|
||||||
|
|
||||||
|
if test.existing != "" {
|
||||||
|
if err := os.WriteFile(path, []byte(test.existing), 0666); err != nil {
|
||||||
|
t.Fatalf("could not write the file to be replaced: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := AtomicWriteFile(path, test.data, test.perm); err != nil {
|
||||||
|
t.Fatalf("did not expect an error, got %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
written, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("could not read the file back: %v", err)
|
||||||
|
}
|
||||||
|
if string(written) != string(test.data) {
|
||||||
|
t.Errorf("expected contents %q got %q", string(test.data), string(written))
|
||||||
|
}
|
||||||
|
|
||||||
|
info, err := os.Stat(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("could not look at the file: %v", err)
|
||||||
|
}
|
||||||
|
if info.Mode().Perm() != test.perm {
|
||||||
|
t.Errorf("expected mode %v got %v", test.perm, info.Mode().Perm())
|
||||||
|
}
|
||||||
|
|
||||||
|
entries, err := os.ReadDir(directory)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("could not list the directory: %v", err)
|
||||||
|
}
|
||||||
|
if len(entries) != 1 {
|
||||||
|
names := make([]string, 0, len(entries))
|
||||||
|
for _, entry := range entries {
|
||||||
|
names = append(names, entry.Name())
|
||||||
|
}
|
||||||
|
t.Errorf("expected only the target file to be left, got %v", names)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAtomicWriteFileReportsAMissingDirectory(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "not-there", "target")
|
||||||
|
|
||||||
|
if err := AtomicWriteFile(path, []byte("hello"), 0644); err == nil {
|
||||||
|
t.Errorf("expected an error for a directory that does not exist")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAtomicWriteFileLeavesTheOldFileAloneOnFailure(t *testing.T) {
|
||||||
|
directory := t.TempDir()
|
||||||
|
path := filepath.Join(directory, "target")
|
||||||
|
|
||||||
|
if err := os.WriteFile(path, []byte("original"), 0644); err != nil {
|
||||||
|
t.Fatalf("could not write the file to be replaced: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A directory that cannot be written to means the temporary file cannot
|
||||||
|
// be created, so the write has to fail before anything is replaced.
|
||||||
|
if err := os.Chmod(directory, 0500); err != nil {
|
||||||
|
t.Fatalf("could not change the directory mode: %v", err)
|
||||||
|
}
|
||||||
|
defer os.Chmod(directory, 0700)
|
||||||
|
|
||||||
|
if os.Geteuid() == 0 {
|
||||||
|
t.Skip("running as root, which ignores the directory mode")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := AtomicWriteFile(path, []byte("replacement"), 0644); err == nil {
|
||||||
|
t.Fatalf("expected an error for a directory that cannot be written to")
|
||||||
|
}
|
||||||
|
|
||||||
|
existing, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("could not read the file back: %v", err)
|
||||||
|
}
|
||||||
|
if string(existing) != "original" {
|
||||||
|
t.Errorf("expected the original contents to survive, got %q", string(existing))
|
||||||
|
}
|
||||||
|
}
|
||||||
28
random.go
28
random.go
@@ -1,28 +0,0 @@
|
|||||||
package util
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/rand"
|
|
||||||
"encoding/hex"
|
|
||||||
"errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
// RandomHexString returns byteLength random bytes from the operating system's
|
|
||||||
// random source, written as lowercase hexadecimal, so the returned string is
|
|
||||||
// twice as long as byteLength. The bytes come from crypto/rand, which means the
|
|
||||||
// result is fit for session tokens, temporary filenames and anything else a
|
|
||||||
// stranger should not be able to guess.
|
|
||||||
//
|
|
||||||
// An error comes back only for a negative length or if the random source
|
|
||||||
// itself fails, which does not happen on a working system.
|
|
||||||
func RandomHexString(byteLength int) (string, error) {
|
|
||||||
if byteLength < 0 {
|
|
||||||
return "", errors.New("byte length cannot be negative")
|
|
||||||
}
|
|
||||||
|
|
||||||
buffer := make([]byte, byteLength)
|
|
||||||
if _, err := rand.Read(buffer); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
return hex.EncodeToString(buffer), nil
|
|
||||||
}
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
package util
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/hex"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestRandomHexStringLength(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
byteLength int
|
|
||||||
expectedLength int
|
|
||||||
}{
|
|
||||||
{"no bytes at all", 0, 0},
|
|
||||||
{"one byte", 1, 2},
|
|
||||||
{"eight bytes", 8, 16},
|
|
||||||
{"sixteen bytes", 16, 32},
|
|
||||||
{"thirty-two bytes", 32, 64},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, test := range tests {
|
|
||||||
t.Run(test.name, func(t *testing.T) {
|
|
||||||
got, err := RandomHexString(test.byteLength)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("did not expect an error, got %v", err)
|
|
||||||
}
|
|
||||||
if len(got) != test.expectedLength {
|
|
||||||
t.Errorf("expected a string of %d characters, got %d (%q)", test.expectedLength, len(got), got)
|
|
||||||
}
|
|
||||||
if _, err := hex.DecodeString(got); err != nil {
|
|
||||||
t.Errorf("expected valid hexadecimal, got %q: %v", got, err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRandomHexStringRejectsNegativeLength(t *testing.T) {
|
|
||||||
got, err := RandomHexString(-1)
|
|
||||||
if err == nil {
|
|
||||||
t.Errorf("expected an error for a negative length, got %q", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRandomHexStringDiffersBetweenCalls(t *testing.T) {
|
|
||||||
seen := make(map[string]struct{})
|
|
||||||
|
|
||||||
for i := 0; i < 100; i++ {
|
|
||||||
value, err := RandomHexString(16)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("did not expect an error, got %v", err)
|
|
||||||
}
|
|
||||||
if _, repeated := seen[value]; repeated {
|
|
||||||
t.Fatalf("got the same string twice: %q", value)
|
|
||||||
}
|
|
||||||
seen[value] = struct{}{}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user