From 9effe3ea1a4aa7b1220da15f68da6bb26a3a36c6 Mon Sep 17 00:00:00 2001 From: Gnana Siva Sai V Date: Thu, 25 Jan 2024 22:54:28 +0530 Subject: [PATCH] implemented delete and has for storage --- storage.go | 39 +++++++++++++++++++++++++++++++++++++++ storage_test.go | 17 +++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/storage.go b/storage.go index 7e46463..063d91d 100644 --- a/storage.go +++ b/storage.go @@ -36,6 +36,14 @@ type PathKey struct { Filename string } +func (p PathKey) FirstPathFolder() string { + paths := strings.Split(p.Path, "/") + if len(paths) == 0 { + return "" + } + return paths[0] +} + func (p PathKey) FullPath() string { return fmt.Sprintf("%s/%s", p.Path, p.Filename) } @@ -60,6 +68,33 @@ func NewStore(opts StoreOpts) *Store { } } +func (s *Store) Has(key string) bool { + pathKey := s.PathTransformFunc(key) + fi, err := os.Stat(pathKey.FullPath()) + if err != nil { + if os.IsNotExist(err) { + return false + } + log.Fatal(err) + } + + if !fi.IsDir() { + return true + } + + return false +} + +func (s *Store) Delete(key string) error { + pathKey := s.PathTransformFunc(key) + + defer func() { + log.Printf("deleted from disk: %s", pathKey.Filename) + }() + + return os.RemoveAll(pathKey.FirstPathFolder()) +} + func (s *Store) Read(key string) (io.Reader, error) { f, err := s.readStream(key) if err != nil { @@ -94,6 +129,10 @@ func (s *Store) writeStream(key string, r io.Reader) error { if err != nil { return err } + defer func() { + log.Printf("closed file: %s", pathAndFilename) + f.Close() + }() n, err := io.Copy(f, r) if err != nil { diff --git a/storage_test.go b/storage_test.go index acdb04f..9bc701e 100644 --- a/storage_test.go +++ b/storage_test.go @@ -45,3 +45,20 @@ func TestStore(t *testing.T) { t.Errorf("expected %s, got %s", "dude chill!!!", string(b)) } } + +func TestDeleteKey(t *testing.T) { + opts := StoreOpts{ + PathTransformFunc: CASPathTransformFunc, + } + s := NewStore(opts) + key := "TripTomorrow" + data := bytes.NewReader([]byte("dude chill!!!")) + + if err := s.writeStream(key, data); err != nil { + t.Error(err) + } + + if err := s.Delete(key); err != nil { + t.Error(err) + } +}