Share bounded regular file read mechanics
This commit is contained in:
44
imports.go
44
imports.go
@@ -3,7 +3,6 @@ package configkit
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
@@ -382,47 +381,12 @@ func (s *importTraversal) readImport(relative, sourceID string, optional bool) (
|
||||
if limit < 0 {
|
||||
limit = 0
|
||||
}
|
||||
preflight, err := s.root.Stat(relative)
|
||||
if err != nil {
|
||||
if optional && errors.Is(err, fs.ErrNotExist) {
|
||||
data, failure := readRegularFile(relative, s.root.Stat, s.root.Open, limit)
|
||||
if failure != nil {
|
||||
if optional && failure.missingTarget {
|
||||
return nil, true, nil
|
||||
}
|
||||
value := classifySourceError(err, sourceID)
|
||||
return nil, false, &value
|
||||
}
|
||||
if !preflight.Mode().IsRegular() {
|
||||
value := sourceDiagnostic(CodeSourceNotRegular, sourceID, "source is not a regular file")
|
||||
return nil, false, &value
|
||||
}
|
||||
file, err := s.root.Open(relative)
|
||||
if err != nil {
|
||||
if optional && errors.Is(err, fs.ErrNotExist) {
|
||||
return nil, true, nil
|
||||
}
|
||||
value := classifySourceError(err, sourceID)
|
||||
return nil, false, &value
|
||||
}
|
||||
defer func() { _ = file.Close() }()
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
value := classifySourceError(err, sourceID)
|
||||
return nil, false, &value
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
value := sourceDiagnostic(CodeSourceNotRegular, sourceID, "source is not a regular file")
|
||||
return nil, false, &value
|
||||
}
|
||||
if info.Size() > limit {
|
||||
value := importDiagnostic(CodeImportLimitExceeded, "configuration exceeds a source or aggregate byte limit", &Location{SourceID: sourceID})
|
||||
return nil, false, &value
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(file, limit+1))
|
||||
if err != nil {
|
||||
value := classifySourceError(err, sourceID)
|
||||
return nil, false, &value
|
||||
}
|
||||
if int64(len(data)) > limit {
|
||||
value := importDiagnostic(CodeImportLimitExceeded, "configuration exceeds a source or aggregate byte limit", &Location{SourceID: sourceID})
|
||||
value := sourceReadDiagnostic(failure, sourceID, CodeImportLimitExceeded, "configuration exceeds a source or aggregate byte limit")
|
||||
return nil, false, &value
|
||||
}
|
||||
s.usedBytes += int64(len(data))
|
||||
|
||||
Reference in New Issue
Block a user