lotus/node/config/storage.go

71 lines
1.6 KiB
Go
Raw Normal View History

2020-03-03 22:19:22 +00:00
package config
import (
"encoding/json"
2023-10-30 23:45:09 +00:00
"errors"
2020-03-03 22:19:22 +00:00
"io"
2023-10-30 23:45:09 +00:00
"io/fs"
2020-03-03 22:19:22 +00:00
"os"
2023-10-30 23:45:09 +00:00
"path"
2020-03-03 22:19:22 +00:00
"golang.org/x/xerrors"
2022-11-01 11:01:31 +00:00
"github.com/filecoin-project/lotus/storage/sealer/storiface"
2020-03-03 22:19:22 +00:00
)
2022-11-01 11:01:31 +00:00
func StorageFromFile(path string, def *storiface.StorageConfig) (*storiface.StorageConfig, error) {
2020-03-03 22:19:22 +00:00
file, err := os.Open(path)
switch {
case os.IsNotExist(err):
if def == nil {
return nil, xerrors.Errorf("couldn't load storage config: %w", err)
}
return def, nil
case err != nil:
return nil, err
}
defer file.Close() //nolint:errcheck // The file is RO
return StorageFromReader(file)
2020-03-03 22:19:22 +00:00
}
2022-11-01 11:01:31 +00:00
func StorageFromReader(reader io.Reader) (*storiface.StorageConfig, error) {
var cfg storiface.StorageConfig
2020-03-03 22:19:22 +00:00
err := json.NewDecoder(reader).Decode(&cfg)
if err != nil {
return nil, err
}
return &cfg, nil
}
2023-10-30 23:45:09 +00:00
func WriteStorageFile(filePath string, config storiface.StorageConfig) error {
b, err := json.MarshalIndent(config, "", " ")
2020-03-03 22:19:22 +00:00
if err != nil {
return xerrors.Errorf("marshaling storage config: %w", err)
}
2023-10-30 23:45:09 +00:00
info, err := os.Stat(filePath)
if err != nil {
if !errors.Is(err, fs.ErrNotExist) {
return xerrors.Errorf("statting storage config (%s): %w", filePath, err)
}
if path.Base(filePath) == "." {
filePath = path.Join(filePath, "storage.json")
}
} else {
if info.IsDir() || path.Base(filePath) == "." {
filePath = path.Join(filePath, "storage.json")
}
}
if err := os.MkdirAll(path.Dir(filePath), 0755); err != nil {
return xerrors.Errorf("making storage config parent directory: %w", err)
}
if err := os.WriteFile(filePath, b, 0644); err != nil {
return xerrors.Errorf("persisting storage config (%s): %w", filePath, err)
2020-03-03 22:19:22 +00:00
}
return nil
}