main
1package db
2
3import (
4 "bytes"
5 "errors"
6 "fmt"
7 "io/ioutil"
8 "os"
9 "path/filepath"
10
11 "github.com/xlgmokha/x/pkg/env"
12 "github.com/xlgmokha/x/pkg/serde"
13 "github.com/xlgmokha/x/pkg/x"
14)
15
16type Entity interface {
17 Identifier() string
18}
19
20type Storage[T Entity] struct {
21 dir string
22}
23
24func New[T Entity](dir string) *Storage[T] {
25 fullPath := x.Must(filepath.Abs(dir))
26 x.Check(os.MkdirAll(fullPath, 0700))
27
28 return &Storage[T]{
29 dir: fullPath,
30 }
31}
32
33func (db *Storage[T]) Save(item T) error {
34 if db.fileExistsFor(item) {
35 return nil
36 }
37
38 w := new(bytes.Buffer)
39 x.Check(serde.To(w, item, serde.YAML))
40 if env.Fetch("DUMP", "") != "" {
41 fmt.Println(w.String())
42 }
43
44 return ioutil.WriteFile(db.filePathFor(item), w.Bytes(), 0700)
45}
46
47func (db *Storage[T]) filePathFor(item T) string {
48 return fmt.Sprintf("%v/%v.yaml", db.dir, item.Identifier())
49}
50
51func (db *Storage[T]) fileExistsFor(item T) bool {
52 _, err := os.Stat(db.filePathFor(item))
53
54 if err != nil && errors.Is(err, os.ErrNotExist) {
55 return false
56 }
57
58 return true
59}