Snapshot verified references for extraction
This commit is contained in:
@@ -67,17 +67,29 @@ func CopyFileAtomicWithChecksum(src, dst string, perm os.FileMode) (string, erro
|
||||
}
|
||||
defer func() { _ = in.Close() }()
|
||||
|
||||
return WriteReaderAtomicWithChecksum(dst, in, perm)
|
||||
}
|
||||
|
||||
// WriteReaderAtomicWithChecksum streams src through the durable replacement
|
||||
// sequence and returns the SHA-256 checksum of the installed bytes. The caller
|
||||
// retains ownership of src.
|
||||
func WriteReaderAtomicWithChecksum(dst string, src io.Reader, perm os.FileMode) (string, error) {
|
||||
if strings.TrimSpace(dst) == "" {
|
||||
return "", fmt.Errorf("destination path is required")
|
||||
}
|
||||
if src == nil {
|
||||
return "", fmt.Errorf("source reader is required")
|
||||
}
|
||||
if err := EnsureWorkspaceDirectory(filepath.Dir(dst)); err != nil {
|
||||
return "", fmt.Errorf("create destination directory: %w", err)
|
||||
}
|
||||
|
||||
digest := sha256.New()
|
||||
err = replaceFileFromReaderConfined(
|
||||
if err := replaceFileFromReaderConfined(
|
||||
dst,
|
||||
io.TeeReader(in, digest),
|
||||
io.TeeReader(src, digest),
|
||||
ReplaceFileOptions{Mode: perm},
|
||||
)
|
||||
if err != nil {
|
||||
); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(digest.Sum(nil)), nil
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package fileops
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
@@ -74,6 +76,28 @@ func TestCopyFileAtomicWithChecksumMatchesDestination(t *testing.T) {
|
||||
assertNoMatchingTempFiles(t, filepath.Dir(dst), ".copied.txt.tmp-")
|
||||
}
|
||||
|
||||
func TestWriteReaderAtomicWithChecksumMatchesDestination(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
dst := filepath.Join(root, "nested", "snapshot.yml")
|
||||
payload := "verified reference bytes\n"
|
||||
|
||||
checksum, err := WriteReaderAtomicWithChecksum(dst, strings.NewReader(payload), WorkspaceFileMode)
|
||||
if err != nil {
|
||||
t.Fatalf("WriteReaderAtomicWithChecksum() error = %v", err)
|
||||
}
|
||||
wantChecksum := sha256.Sum256([]byte(payload))
|
||||
if checksum != hex.EncodeToString(wantChecksum[:]) {
|
||||
t.Fatalf("checksum = %q, want %q", checksum, hex.EncodeToString(wantChecksum[:]))
|
||||
}
|
||||
data, err := os.ReadFile(dst)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadFile() error = %v", err)
|
||||
}
|
||||
if string(data) != payload {
|
||||
t.Fatalf("destination = %q, want %q", data, payload)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCopyFileAtomicCleansTempFileOnInstallFailure(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
src := filepath.Join(root, "source.txt")
|
||||
|
||||
Reference in New Issue
Block a user