From 7ad9a2edb0a69d8b32f3df745e729285b5cae21c Mon Sep 17 00:00:00 2001 From: Jan Saidl Date: Mon, 1 Apr 2024 13:59:23 +0200 Subject: [PATCH] z0 - fix storage load/save --- src/storage/exists.go | 16 ---------------- src/storage/handler.go | 40 ++++++++++++++++------------------------ 2 files changed, 16 insertions(+), 40 deletions(-) delete mode 100644 src/storage/exists.go diff --git a/src/storage/exists.go b/src/storage/exists.go deleted file mode 100644 index ca85b772..00000000 --- a/src/storage/exists.go +++ /dev/null @@ -1,16 +0,0 @@ -package storage - -import ( - "os" -) - -func FileExists(path string) (bool, error) { - f, err := os.Stat(path) - if err == nil && !f.IsDir() { - return true, nil - } - if os.IsNotExist(err) { - return false, nil - } - return false, err -} diff --git a/src/storage/handler.go b/src/storage/handler.go index 2208a1d3..dd4d392c 100644 --- a/src/storage/handler.go +++ b/src/storage/handler.go @@ -34,43 +34,34 @@ func New[T any](config Config) (*Handler[T], error) { } func (h *Handler[T]) load() error { - storageFileExists, err := FileExists(h.config.FilePath) - if err != nil { - return errors.WithStack(err) - } - if !storageFileExists { - return nil + { + f, err := os.Stat(h.config.FilePath) + if os.IsNotExist(err) { + return nil + } + if err != nil { + return errors.WithStack(err) + } + if f.Size() == 0 { + if err := os.Remove(h.config.FilePath); err != nil { + return errors.WithStack(err) + } + return nil + } } - f, err := file.Open(h.config.FilePath, os.O_RDONLY, h.config.FileMode) + f, err := os.Open(h.config.FilePath) if err != nil { return errors.WithStack(err) } defer f.Close() - // If the file is empty, set the default value and save it. - fi, err := f.Stat() - if err != nil { - return errors.WithStack(err) - } - if fi.Size() == 0 { - return h.Clear() - } - if err := json.NewDecoder(f).Decode(&h.data); err != nil { return errors.WithMessagef(err, i18n.T(i18n.UnableToDecodeJsonFile, h.config.FilePath)) } - return nil } -func (h *Handler[T]) Clear() error { - h.lock.Lock() - defer h.lock.Unlock() - var data T - return h.save(data) -} - func (h *Handler[T]) Update(callback func(T) T) (T, error) { h.lock.Lock() defer h.lock.Unlock() @@ -95,6 +86,7 @@ func (h *Handler[T]) save(data T) error { }(); err != nil { return err } + os.Remove(h.config.FilePath) if err := os.Rename(h.config.FilePath+".new", h.config.FilePath); err != nil { return errors.WithStack(err) }