Skip to content

Commit

Permalink
implemented delete and has for storage
Browse files Browse the repository at this point in the history
  • Loading branch information
gnana997 committed Jan 25, 2024
1 parent add218a commit 9effe3e
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
39 changes: 39 additions & 0 deletions storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand All @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down
17 changes: 17 additions & 0 deletions storage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit 9effe3e

Please sign in to comment.