1
0
mirror of https://github.com/schollz/cowyo.git synced 2023-08-10 21:13:00 +03:00
cowyo/db.go
Zack Scholl c40d23c03a Storing DIffs now...might not be compatible?
Former-commit-id: ce50508705b9727b310059116a2c07d2154d7a80 [formerly 5a63af13359b5a8a3d963c014517c709151312cc] [formerly 0703fe06fc408947ca4d70b97cba99e02c75879f [formerly b930aaa541b69221a634808ac68dd56b4b806aac [formerly 965989530c]]]
Former-commit-id: 9575b9b87113bd6a2ff0186464671666bbac18cf [formerly f825477fd790918e8d9247e3a540da391dbc687a]
Former-commit-id: 0c1e92517cc0e5ad864135711535021b4c170f19
Former-commit-id: 021e5d5a8e
2016-02-07 18:31:47 -05:00

117 lines
2.2 KiB
Go

package main
import (
"encoding/json"
"fmt"
"log"
"time"
"github.com/boltdb/bolt"
"github.com/sergi/go-diff/diffmatchpatch"
)
var db *bolt.DB
var open bool
// Open to create the database and open
func Open(filename string) error {
var err error
config := &bolt.Options{Timeout: 30 * time.Second}
db, err = bolt.Open(filename, 0600, config)
if err != nil {
fmt.Println("Opening BoltDB timed out")
log.Fatal(err)
}
open = true
return nil
}
// Close database
func Close() {
open = false
db.Close()
}
// Data for storing in DB
type CowyoData struct {
Title string
CurrentText string
Diffs []string
Timestamps []string
}
func (p *CowyoData) load(title string) error {
if !open {
return fmt.Errorf("db must be opened before saving!")
}
err := db.View(func(tx *bolt.Tx) error {
var err error
b := tx.Bucket([]byte("datas"))
if b == nil {
return nil
}
k := []byte(title)
val := b.Get(k)
if val == nil {
// make new one
p.Title = title
p.CurrentText = ""
p.Diffs = []string{}
p.Timestamps = []string{}
return nil
}
err = p.decode(val)
if err != nil {
return err
}
return nil
})
if err != nil {
fmt.Printf("Could not get CowyoData: %s", err)
return err
}
return nil
}
func (p *CowyoData) save(newText string) error {
if !open {
return fmt.Errorf("db must be opened before saving")
}
err := db.Update(func(tx *bolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists([]byte("datas"))
if err != nil {
return fmt.Errorf("create bucket: %s", err)
}
// find diffs
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(p.CurrentText, newText, true)
delta := dmp.DiffToDelta(diffs)
p.CurrentText = newText
p.Timestamps = append(p.Timestamps, time.Now().String())
p.Diffs = append(p.Diffs, delta)
enc, err := p.encode()
if err != nil {
return fmt.Errorf("could not encode CowyoData: %s", err)
}
err = bucket.Put([]byte(p.Title), enc)
return err
})
return err
}
func (p *CowyoData) encode() ([]byte, error) {
enc, err := json.Marshal(p)
if err != nil {
return nil, err
}
return enc, nil
}
func (p *CowyoData) decode(data []byte) error {
err := json.Unmarshal(data, &p)
if err != nil {
return err
}
return nil
}