refact: updated to islazy 1.8.0

This commit is contained in:
evilsocket 2018-10-15 15:01:57 -05:00
commit 90bb05cd5b
No known key found for this signature in database
GPG key ID: 1564D7F30393A456
6 changed files with 96 additions and 54 deletions

View file

@ -3,6 +3,7 @@ package data
import (
"bytes"
"encoding/gob"
"encoding/json"
"io/ioutil"
"os"
"sync"
@ -43,6 +44,32 @@ func NewUnsortedKV(fileName string, flushPolicy FlushPolicy) (*UnsortedKV, error
return ukv, nil
}
// NewDiskUnsortedKV returns an UnsortedKV that flushed data on disk
// every time it gets updated.
func NewDiskUnsortedKV(fileName string) (*UnsortedKV, error) {
return NewUnsortedKV(fileName, FlushOnEdit)
}
// NewDiskUnsortedKVReader returns an UnsortedKV from disk as a reader
// but it doesn't flush any modifications on disk.
func NewDiskUnsortedKVReader(fileName string) (*UnsortedKV, error) {
return NewUnsortedKV(fileName, FlushNone)
}
// NewMemUnsortedKV returns an UnsortedKV that only lives in
// memory and never persists on disk.
func NewMemUnsortedKV() (*UnsortedKV, error) {
return NewUnsortedKV("", FlushNone)
}
// MarshalJSON is used to serialize the UnsortedKV data structure to
// JSON correctly.
func (u *UnsortedKV) MarshalJSON() ([]byte, error) {
u.Lock()
defer u.Unlock()
return json.Marshal(u.m)
}
// Has return true if name exists in the store.
func (u *UnsortedKV) Has(name string) bool {
u.Lock()
@ -132,3 +159,10 @@ func (u *UnsortedKV) Each(cb func(k, v string) bool) {
}
}
}
// Empty returns bool if the store is empty.
func (u *UnsortedKV) Empty() bool {
u.Lock()
defer u.Unlock()
return len(u.m) == 0
}

View file

@ -5,6 +5,11 @@ import (
"os/user"
"path/filepath"
"strings"
"sync"
)
var (
cwdLock = sync.Mutex{}
)
// Expand will expand a path with ~ to a full path of the current user.
@ -23,3 +28,28 @@ func Exists(path string) bool {
}
return true
}
// Chdir changes the process current working directory to the specified
// one, executes the callback and then restores the original working directory.
func Chdir(path string, cb func() error) error {
cwdLock.Lock()
defer cwdLock.Unlock()
cwd, err := os.Getwd()
if err != nil {
return err
}
// make sure that whatever happens we restore the original
// working directory of the process
defer func() {
if err := os.Chdir(cwd); err != nil {
panic(err)
}
}()
// change folder
if err := os.Chdir(path); err != nil {
return err
}
// run the callback once inside the folder
return cb()
}