src

Go monorepo.
git clone git://code.dwrz.net/src
Log | Files | Refs

store.go (1096B)


      1 package store
      2 
      3 import (
      4 	"fmt"
      5 	"math/rand"
      6 	"os"
      7 	"sync"
      8 	"time"
      9 
     10 	"code.dwrz.net/src/pkg/log"
     11 )
     12 
     13 var random = rand.New(rand.NewSource(time.Now().UnixNano()))
     14 
     15 type Parameters struct {
     16 	Path string
     17 	Log  *log.Logger
     18 }
     19 
     20 type Store struct {
     21 	log  *log.Logger
     22 	path string
     23 
     24 	mu          sync.Mutex
     25 	collections map[string]*Collection
     26 }
     27 
     28 func New(p Parameters) (*Store, error) {
     29 	var s = &Store{
     30 		collections: map[string]*Collection{},
     31 		log:         p.Log,
     32 		path:        p.Path,
     33 	}
     34 
     35 	// Create the directory, if it doesn't exist.
     36 	if _, err := os.Stat(p.Path); os.IsNotExist(err) {
     37 		if err := os.MkdirAll(p.Path, os.ModeDir|fm); err != nil {
     38 			return nil, fmt.Errorf(
     39 				"failed to create directory: %w", err,
     40 			)
     41 		}
     42 	}
     43 
     44 	// Seed existing collections.
     45 	entries, err := os.ReadDir(s.path)
     46 	if err != nil {
     47 		return nil, fmt.Errorf("failed to read directory: %w", err)
     48 	}
     49 	for _, e := range entries {
     50 		if !e.IsDir() {
     51 			continue
     52 		}
     53 
     54 		if err := s.NewCollection(e.Name()); err != nil {
     55 			return nil, fmt.Errorf(
     56 				"failed to create new collection: %w", err,
     57 			)
     58 		}
     59 	}
     60 
     61 	return s, nil
     62 }