Simplify atomic file replacement and bounded reads
This commit is contained in:
32
internal/fileops/read_bounded.go
Normal file
32
internal/fileops/read_bounded.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package fileops
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ReadFileBounded reads at most limit bytes from path using ordinary workspace
|
||||
// path semantics. It does not return partial data when the limit is exceeded.
|
||||
func ReadFileBounded(path string, limit int64) ([]byte, error) {
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return nil, fmt.Errorf("file path is required")
|
||||
}
|
||||
if limit < 0 {
|
||||
return nil, fmt.Errorf("file read limit %d is invalid", limit)
|
||||
}
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open file %q: %w", path, err)
|
||||
}
|
||||
defer func() { _ = file.Close() }()
|
||||
data, err := io.ReadAll(io.LimitReader(file, limit+1))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read file %q: %w", path, err)
|
||||
}
|
||||
if int64(len(data)) > limit {
|
||||
return nil, fmt.Errorf("file %q exceeds %d-byte limit", path, limit)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
Reference in New Issue
Block a user