aboutsummaryrefslogtreecommitdiff
path: root/yamldb/yamldb.go
blob: 1478cc78ed6a796dc460fc3c333e88d96ce2904e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package yamldb

import (
	"github.com/pkg/errors"
	"io/ioutil"
	"os"
	"sync"

	log "github.com/sirupsen/logrus"
)

// YamlDB represents a YAML file database instance
type YamlDB struct {
	Path    string
	PathNew string
	lock    sync.Mutex
}

// Transaction executes the given callback and safely saves
// the data after they are modified within the callback
func (db *YamlDB) Transaction(callback func() bool, marshaller func() ([]byte, error)) error {
	log.Debug("Enter transaction")
	db.lock.Lock()
	defer func() {
		db.lock.Unlock()
		log.Debug("Exit transaction")
	}()

	isDataChanged := callback()

	if isDataChanged {
		yamlData, err := marshaller()
		if err != nil {
			return errors.Wrap(err, "Data marshalling error")
		}
		err = ioutil.WriteFile(db.PathNew, yamlData, 0644)
		if err != nil {
			return errors.Wrap(err, "YamlDB write failure")
		}
		err = os.Rename(db.PathNew, db.Path)
		if err != nil {
			return errors.Wrap(err, "Couldn't rewrite an old YamlDB file")
		}
	}

	return nil
}