aboutsummaryrefslogtreecommitdiff
path: root/yamldb
diff options
context:
space:
mode:
authorbodqhrohro <bodqhrohro@gmail.com>2019-11-11 02:50:50 +0300
committerbodqhrohro <bodqhrohro@gmail.com>2019-11-11 02:50:50 +0300
commitfbe99c65ec36bb0d8b3a508e0894a9830ff9c995 (patch)
treecaf1a1ced752de2e4188c383de82ba98f8bc9272 /yamldb
parent7185d4ac9b039bbb74291f57ee2dae6120c636f6 (diff)
Implementation of Ruby YAML::Store and read/save of the session database
Diffstat (limited to 'yamldb')
-rw-r--r--yamldb/yamldb.go47
1 files changed, 47 insertions, 0 deletions
diff --git a/yamldb/yamldb.go b/yamldb/yamldb.go
new file mode 100644
index 0000000..eec23be
--- /dev/null
+++ b/yamldb/yamldb.go
@@ -0,0 +1,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(), marshaller func() ([]byte, error)) error {
+ var err error
+
+ log.Debug("Enter transaction")
+ db.lock.Lock()
+ defer func() {
+ db.lock.Unlock()
+ log.Debug("Exit transaction")
+ }()
+
+ callback()
+
+ 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
+}