fix(serialization): treat empty LoadFileIfExist paths like missing files

When a path exists but reads as empty or whitespace-only, return nil
without touching dst, matching the no-file case. This avoids
unmarshaler errors on blank files and matches the updated doc comment.
This commit is contained in:
yusing
2026-04-09 16:44:47 +08:00
parent 41d0d28ca8
commit 5e461842dc

View File

@@ -1,6 +1,7 @@
package serialization
import (
"bytes"
"errors"
"fmt"
"io"
@@ -727,7 +728,7 @@ func SaveFile[T any](path string, src *T, perm os.FileMode, marshaler marshalFun
// LoadFileIfExist reads a file and unmarshals its contents to a value.
// - The unmarshaler function converts the bytes to a value.
// - If the file does not exist, nil is returned and dst remains unchanged.
// - If the file does not exist or is empty, nil is returned and dst remains unchanged.
func LoadFileIfExist[T any](path string, dst *T, unmarshaler unmarshalFunc) error {
data, err := os.ReadFile(path)
if err != nil {
@@ -736,5 +737,8 @@ func LoadFileIfExist[T any](path string, dst *T, unmarshaler unmarshalFunc) erro
}
return err
}
if len(bytes.TrimSpace(data)) == 0 {
return nil
}
return unmarshaler(data, dst)
}