github.com/Benchkram/bob@v0.0.0-20220321080157-7c8f3876e225/pkg/store/filestore/filestore.go (about)

     1  package filestore
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"os"
     7  	"path/filepath"
     8  
     9  	"github.com/Benchkram/bob/pkg/store"
    10  	"github.com/Benchkram/errz"
    11  )
    12  
    13  type s struct {
    14  	dir string
    15  }
    16  
    17  // New creates a filestore. The caller is responsible to pass a
    18  // existing directory.
    19  func New(dir string, opts ...Option) store.Store {
    20  	s := &s{
    21  		dir: dir,
    22  	}
    23  
    24  	for _, opt := range opts {
    25  		if opt == nil {
    26  			continue
    27  		}
    28  		opt(s)
    29  	}
    30  
    31  	return s
    32  }
    33  
    34  // NewArtifact creates a new file. The caller is responsible to call Close().
    35  // Existing artifacts are overwritten.
    36  func (s *s) NewArtifact(_ context.Context, id string) (store.Artifact, error) {
    37  	return os.Create(filepath.Join(s.dir, id))
    38  }
    39  
    40  // GetArtifact opens a file
    41  func (s *s) GetArtifact(_ context.Context, id string) (empty store.Artifact, _ error) {
    42  	return os.Open(filepath.Join(s.dir, id))
    43  }
    44  
    45  func (s *s) Clean(_ context.Context) (err error) {
    46  	defer errz.Recover(&err)
    47  
    48  	homeDir, err := os.UserHomeDir()
    49  	errz.Fatal(err)
    50  	if s.dir == "/" || s.dir == homeDir {
    51  		return fmt.Errorf("Cleanup of %s is not allowed", s.dir)
    52  	}
    53  
    54  	entrys, err := os.ReadDir(s.dir)
    55  	errz.Fatal(err)
    56  
    57  	for _, entry := range entrys {
    58  		if entry.IsDir() {
    59  			continue
    60  		}
    61  		_ = os.Remove(filepath.Join(s.dir, entry.Name()))
    62  	}
    63  
    64  	return nil
    65  }
    66  
    67  // List the items id's in the store
    68  func (s *s) List(_ context.Context) (items []string, err error) {
    69  	defer errz.Recover(&err)
    70  	entrys, err := os.ReadDir(s.dir)
    71  	errz.Fatal(err)
    72  
    73  	items = []string{}
    74  	for _, e := range entrys {
    75  		items = append(items, e.Name())
    76  	}
    77  
    78  	return items, nil
    79  }