Move all go files into an internal package
This commit is contained in:
@@ -0,0 +1,791 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"go.etcd.io/bbolt"
|
||||
)
|
||||
|
||||
/*
|
||||
BoltDB A Database, basically a collection of buckets
|
||||
*/
|
||||
type BoltDB struct {
|
||||
buckets []BoltBucket
|
||||
}
|
||||
|
||||
/*
|
||||
BoltBucket is just a struct representation of a Bucket in the Bolt DB
|
||||
*/
|
||||
type BoltBucket struct {
|
||||
name string
|
||||
pairs []BoltPair
|
||||
buckets []BoltBucket
|
||||
parent *BoltBucket
|
||||
expanded bool
|
||||
errorFlag bool
|
||||
isRoot bool
|
||||
}
|
||||
|
||||
/*
|
||||
BoltPair is just a struct representation of a Pair in the Bolt DB
|
||||
*/
|
||||
type BoltPair struct {
|
||||
parent *BoltBucket
|
||||
key string
|
||||
val string
|
||||
}
|
||||
|
||||
func (bd *BoltDB) getGenericFromPath(path []string) (*BoltBucket, *BoltPair, error) {
|
||||
// Check if 'path' leads to a pair
|
||||
p, err := bd.getPairFromPath(path)
|
||||
if err == nil {
|
||||
return nil, p, nil
|
||||
}
|
||||
// Nope, check if it leads to a bucket
|
||||
b, err := bd.getBucketFromPath(path)
|
||||
if err == nil {
|
||||
return b, nil, nil
|
||||
}
|
||||
// Nope, error
|
||||
return nil, nil, errors.New("Invalid Path")
|
||||
}
|
||||
|
||||
func (bd *BoltDB) getBucketFromPath(path []string) (*BoltBucket, error) {
|
||||
if len(path) > 0 {
|
||||
// Find the BoltBucket with a path == path
|
||||
var b *BoltBucket
|
||||
var err error
|
||||
// Find the root bucket
|
||||
b, err = memBolt.getBucket(path[0])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(path) > 1 {
|
||||
for p := 1; p < len(path); p++ {
|
||||
b, err = b.getBucket(path[p])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
return nil, errors.New("Invalid Path")
|
||||
}
|
||||
|
||||
func (bd *BoltDB) getPairFromPath(path []string) (*BoltPair, error) {
|
||||
if len(path) <= 0 {
|
||||
return nil, errors.New("No Path")
|
||||
}
|
||||
b, err := bd.getBucketFromPath(path[:len(path)-1])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Found the bucket, pull out the pair
|
||||
p, err := b.getPair(path[len(path)-1])
|
||||
return p, err
|
||||
}
|
||||
|
||||
func (bd *BoltDB) getVisibleItemCount(path []string) (int, error) {
|
||||
vis := 0
|
||||
var retErr error
|
||||
if len(path) == 0 {
|
||||
for i := range bd.buckets {
|
||||
n, err := bd.getVisibleItemCount(bd.buckets[i].GetPath())
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
vis += n
|
||||
}
|
||||
} else {
|
||||
b, err := bd.getBucketFromPath(path)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
// 1 for the bucket
|
||||
vis++
|
||||
if b.expanded {
|
||||
// This bucket is expanded, add up it's children
|
||||
// * 1 for each pair
|
||||
vis += len(b.pairs)
|
||||
// * recurse for buckets
|
||||
for i := range b.buckets {
|
||||
n, err := bd.getVisibleItemCount(b.buckets[i].GetPath())
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
vis += n
|
||||
}
|
||||
}
|
||||
}
|
||||
return vis, retErr
|
||||
}
|
||||
|
||||
func (bd *BoltDB) buildVisiblePathSlice(filter string) ([][]string, error) {
|
||||
var retSlice [][]string
|
||||
var retErr error
|
||||
// The root path, recurse for root buckets
|
||||
for i := range bd.buckets {
|
||||
bktS, bktErr := bd.buckets[i].buildVisiblePathSlice([]string{}, filter)
|
||||
if bktErr == nil {
|
||||
retSlice = append(retSlice, bktS...)
|
||||
} else {
|
||||
// Something went wrong, set the error flag
|
||||
bd.buckets[i].errorFlag = true
|
||||
}
|
||||
}
|
||||
return retSlice, retErr
|
||||
}
|
||||
|
||||
func (bd *BoltDB) isVisiblePath(path []string, filter string) bool {
|
||||
visPaths, err := bd.buildVisiblePathSlice(filter)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for _, pth := range visPaths {
|
||||
if len(pth) != len(path) {
|
||||
continue
|
||||
}
|
||||
isVisible := true
|
||||
for i := range path {
|
||||
if path[i] != pth[i] {
|
||||
isVisible = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if isVisible {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (bd *BoltDB) getPrevVisiblePath(path []string, filter string) []string {
|
||||
visPaths, err := bd.buildVisiblePathSlice(filter)
|
||||
if path == nil {
|
||||
if len(visPaths) > 0 {
|
||||
return visPaths[len(visPaths)-1]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err == nil {
|
||||
for idx, pth := range visPaths {
|
||||
isCurPath := true
|
||||
for i := range path {
|
||||
if len(pth) <= i || path[i] != pth[i] {
|
||||
isCurPath = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if isCurPath && idx > 0 {
|
||||
return visPaths[idx-1]
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (bd *BoltDB) getNextVisiblePath(path []string, filter string) []string {
|
||||
visPaths, err := bd.buildVisiblePathSlice(filter)
|
||||
if path == nil {
|
||||
if len(visPaths) > 0 {
|
||||
return visPaths[0]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err == nil {
|
||||
for idx, pth := range visPaths {
|
||||
isCurPath := true
|
||||
for i := range path {
|
||||
if len(pth) <= i || path[i] != pth[i] {
|
||||
isCurPath = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if isCurPath && len(visPaths) > idx+1 {
|
||||
return visPaths[idx+1]
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (bd *BoltDB) toggleOpenBucket(path []string) error {
|
||||
// Find the BoltBucket with a path == path
|
||||
b, err := bd.getBucketFromPath(path)
|
||||
if err == nil {
|
||||
b.expanded = !b.expanded
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (bd *BoltDB) closeBucket(path []string) error {
|
||||
// Find the BoltBucket with a path == path
|
||||
b, err := bd.getBucketFromPath(path)
|
||||
if err == nil {
|
||||
b.expanded = false
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (bd *BoltDB) openBucket(path []string) error {
|
||||
// Find the BoltBucket with a path == path
|
||||
b, err := bd.getBucketFromPath(path)
|
||||
if err == nil {
|
||||
b.expanded = true
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (bd *BoltDB) getBucket(k string) (*BoltBucket, error) {
|
||||
for i := range bd.buckets {
|
||||
if bd.buckets[i].name == k {
|
||||
return &bd.buckets[i], nil
|
||||
}
|
||||
}
|
||||
return nil, errors.New("Bucket Not Found")
|
||||
}
|
||||
|
||||
func (bd *BoltDB) openAllBuckets() {
|
||||
for i := range bd.buckets {
|
||||
bd.buckets[i].openAllBuckets()
|
||||
bd.buckets[i].expanded = true
|
||||
}
|
||||
}
|
||||
|
||||
func (bd *BoltDB) syncOpenBuckets(shadow *BoltDB) {
|
||||
// First test this bucket
|
||||
for i := range bd.buckets {
|
||||
for j := range shadow.buckets {
|
||||
if bd.buckets[i].name == shadow.buckets[j].name {
|
||||
bd.buckets[i].syncOpenBuckets(&shadow.buckets[j])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (bd *BoltDB) refreshDatabase() *BoltDB {
|
||||
// Reload the database into memBolt
|
||||
memBolt = new(BoltDB)
|
||||
db.View(func(tx *bbolt.Tx) error {
|
||||
err := tx.ForEach(func(nm []byte, b *bbolt.Bucket) error {
|
||||
bb, err := readBucket(b)
|
||||
if err == nil {
|
||||
bb.name = string(nm)
|
||||
bb.expanded = false
|
||||
memBolt.buckets = append(memBolt.buckets, *bb)
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
memBolt = new(BoltDB)
|
||||
// Check if there are key/values directly in the root
|
||||
bb, err := readBucket(tx.Cursor().Bucket())
|
||||
if err == nil {
|
||||
bb.isRoot = true
|
||||
bb.expanded = true
|
||||
memBolt.buckets = append(memBolt.buckets, *bb)
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
return err
|
||||
})
|
||||
return memBolt
|
||||
}
|
||||
|
||||
/*
|
||||
GetPath returns the database path leading to this BoltBucket
|
||||
*/
|
||||
func (b *BoltBucket) GetPath() []string {
|
||||
if b.parent != nil {
|
||||
return append(b.parent.GetPath(), b.name)
|
||||
}
|
||||
return []string{b.name}
|
||||
}
|
||||
|
||||
/*
|
||||
buildVisiblePathSlice builds a slice of string slices containing all visible paths in this bucket
|
||||
The passed prefix is the path leading to the current bucket
|
||||
*/
|
||||
func (b *BoltBucket) buildVisiblePathSlice(prefix []string, filter string) ([][]string, error) {
|
||||
var retSlice [][]string
|
||||
var retErr error
|
||||
retSlice = append(retSlice, append(prefix, b.name))
|
||||
if b.expanded {
|
||||
// Add subbuckets
|
||||
for i := range b.buckets {
|
||||
bktS, bktErr := b.buckets[i].buildVisiblePathSlice(append(prefix, b.name), filter)
|
||||
if bktErr != nil {
|
||||
return retSlice, bktErr
|
||||
}
|
||||
retSlice = append(retSlice, bktS...)
|
||||
}
|
||||
// Add pairs
|
||||
for i := range b.pairs {
|
||||
if filter != "" && !strings.Contains(b.pairs[i].key, filter) {
|
||||
continue
|
||||
}
|
||||
retSlice = append(retSlice, append(append(prefix, b.name), b.pairs[i].key))
|
||||
}
|
||||
}
|
||||
return retSlice, retErr
|
||||
}
|
||||
|
||||
func (b *BoltBucket) syncOpenBuckets(shadow *BoltBucket) {
|
||||
// First test this bucket
|
||||
b.expanded = shadow.expanded
|
||||
for i := range b.buckets {
|
||||
for j := range shadow.buckets {
|
||||
if b.buckets[i].name == shadow.buckets[j].name {
|
||||
b.buckets[i].syncOpenBuckets(&shadow.buckets[j])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (b *BoltBucket) openAllBuckets() {
|
||||
for i := range b.buckets {
|
||||
b.buckets[i].openAllBuckets()
|
||||
b.buckets[i].expanded = true
|
||||
}
|
||||
}
|
||||
|
||||
func (b *BoltBucket) getBucket(k string) (*BoltBucket, error) {
|
||||
for i := range b.buckets {
|
||||
if b.buckets[i].name == k {
|
||||
return &b.buckets[i], nil
|
||||
}
|
||||
}
|
||||
return nil, errors.New("Bucket Not Found")
|
||||
}
|
||||
|
||||
func (b *BoltBucket) getPair(k string) (*BoltPair, error) {
|
||||
for i := range b.pairs {
|
||||
if b.pairs[i].key == k {
|
||||
return &b.pairs[i], nil
|
||||
}
|
||||
}
|
||||
return nil, errors.New("Pair Not Found")
|
||||
}
|
||||
|
||||
/*
|
||||
GetPath Returns the path of the BoltPair
|
||||
*/
|
||||
func (p *BoltPair) GetPath() []string {
|
||||
return append(p.parent.GetPath(), p.key)
|
||||
}
|
||||
|
||||
/* This is a go-between function (between the boltbrowser structs
|
||||
* above, and the bolt convenience functions below)
|
||||
* for taking a boltbrowser bucket and recursively adding it
|
||||
* and all of it's children into the database.
|
||||
* Mainly used for moving a bucket from one path to another
|
||||
* as in the 'renameBucket' function below.
|
||||
*/
|
||||
func addBucketFromBoltBucket(path []string, bb *BoltBucket) error {
|
||||
if err := insertBucket(path, bb.name); err == nil {
|
||||
bucketPath := append(path, bb.name)
|
||||
for i := range bb.pairs {
|
||||
if err = insertPair(bucketPath, bb.pairs[i].key, bb.pairs[i].val); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for i := range bb.buckets {
|
||||
if err = addBucketFromBoltBucket(bucketPath, &bb.buckets[i]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func deleteKey(path []string) error {
|
||||
if AppArgs.ReadOnly {
|
||||
return errors.New("DB is in Read-Only Mode")
|
||||
}
|
||||
err := db.Update(func(tx *bbolt.Tx) error {
|
||||
// len(b.path)-1 is the key we need to delete,
|
||||
// the rest are buckets leading to that key
|
||||
if len(path) == 1 {
|
||||
// Deleting a root bucket
|
||||
return tx.DeleteBucket([]byte(path[0]))
|
||||
}
|
||||
b := tx.Bucket([]byte(path[0]))
|
||||
if b == nil {
|
||||
// Invalid path, try for the root bucket
|
||||
b = tx.Cursor().Bucket()
|
||||
}
|
||||
if b != nil {
|
||||
if len(path) > 1 {
|
||||
for i := range path[1 : len(path)-1] {
|
||||
b = b.Bucket([]byte(path[i+1]))
|
||||
if b == nil {
|
||||
return errors.New("deleteKey: Invalid Path")
|
||||
}
|
||||
}
|
||||
}
|
||||
// Now delete the last key in the path
|
||||
var err error
|
||||
if deleteBkt := b.Bucket([]byte(path[len(path)-1])); deleteBkt == nil {
|
||||
// Must be a pair
|
||||
err = b.Delete([]byte(path[len(path)-1]))
|
||||
} else {
|
||||
err = b.DeleteBucket([]byte(path[len(path)-1]))
|
||||
}
|
||||
return err
|
||||
}
|
||||
return errors.New("deleteKey: Invalid Path")
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func readBucket(b *bbolt.Bucket) (*BoltBucket, error) {
|
||||
bb := new(BoltBucket)
|
||||
if b == nil {
|
||||
return nil, errors.New("No bucket passed")
|
||||
}
|
||||
b.ForEach(func(k, v []byte) error {
|
||||
if v == nil {
|
||||
tb, err := readBucket(b.Bucket(k))
|
||||
tb.parent = bb
|
||||
if err == nil {
|
||||
tb.name = string(k)
|
||||
bb.buckets = append(bb.buckets, *tb)
|
||||
}
|
||||
} else {
|
||||
tp := BoltPair{key: string(k), val: string(v)}
|
||||
tp.parent = bb
|
||||
bb.pairs = append(bb.pairs, tp)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return bb, nil
|
||||
}
|
||||
|
||||
func renameBucket(path []string, name string) error {
|
||||
if name == path[len(path)-1] {
|
||||
// No change requested
|
||||
return nil
|
||||
}
|
||||
var bb *BoltBucket // For caching the current bucket
|
||||
err := db.View(func(tx *bbolt.Tx) error {
|
||||
// len(b.path)-1 is the key we need to delete,
|
||||
// the rest are buckets leading to that key
|
||||
b := tx.Bucket([]byte(path[0]))
|
||||
if b == nil {
|
||||
// Invalid path, try for the root bucket
|
||||
b = tx.Cursor().Bucket()
|
||||
}
|
||||
if b != nil {
|
||||
if len(path) > 1 {
|
||||
for i := range path[1:] {
|
||||
b = b.Bucket([]byte(path[i+1]))
|
||||
if b == nil {
|
||||
return errors.New("renameBucket: Invalid Path")
|
||||
}
|
||||
}
|
||||
}
|
||||
var err error
|
||||
// Ok, cache b
|
||||
bb, err = readBucket(b)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return errors.New("renameBucket: Invalid Bucket")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if bb == nil {
|
||||
return errors.New("renameBucket: Couldn't find Bucket")
|
||||
}
|
||||
|
||||
// Ok, we have the bucket cached, now delete the current instance
|
||||
if err = deleteKey(path); err != nil {
|
||||
return err
|
||||
}
|
||||
// Rechristen our cached bucket
|
||||
bb.name = name
|
||||
// And re-add it
|
||||
|
||||
parentPath := path[:len(path)-1]
|
||||
if err = addBucketFromBoltBucket(parentPath, bb); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func updatePairKey(path []string, k string) error {
|
||||
if AppArgs.ReadOnly {
|
||||
return errors.New("DB is in Read-Only Mode")
|
||||
}
|
||||
err := db.Update(func(tx *bbolt.Tx) error {
|
||||
// len(b.path)-1 is the key for the pair we're updating,
|
||||
// the rest are buckets leading to that key
|
||||
b := tx.Bucket([]byte(path[0]))
|
||||
if b == nil {
|
||||
// Invalid path, try for the root bucket
|
||||
b = tx.Cursor().Bucket()
|
||||
}
|
||||
if b != nil {
|
||||
if len(path) > 0 {
|
||||
for i := range path[1 : len(path)-1] {
|
||||
b = b.Bucket([]byte(path[i+1]))
|
||||
if b == nil {
|
||||
return errors.New("updatePairValue: Invalid Path")
|
||||
}
|
||||
}
|
||||
}
|
||||
bk := []byte(path[len(path)-1])
|
||||
v := b.Get(bk)
|
||||
err := b.Delete(bk)
|
||||
if err == nil {
|
||||
// Old pair has been deleted, now add the new one
|
||||
err = b.Put([]byte(k), v)
|
||||
}
|
||||
// Now update the last key in the path
|
||||
return err
|
||||
}
|
||||
return errors.New("updatePairValue: Invalid Path")
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func updatePairValue(path []string, v string) error {
|
||||
if AppArgs.ReadOnly {
|
||||
return errors.New("DB is in Read-Only Mode")
|
||||
}
|
||||
err := db.Update(func(tx *bbolt.Tx) error {
|
||||
// len(b.GetPath())-1 is the key for the pair we're updating,
|
||||
// the rest are buckets leading to that key
|
||||
b := tx.Bucket([]byte(path[0]))
|
||||
if b == nil {
|
||||
// Invalid path, try for the root bucket
|
||||
b = tx.Cursor().Bucket()
|
||||
}
|
||||
if b != nil {
|
||||
if len(path) > 0 {
|
||||
for i := range path[1 : len(path)-1] {
|
||||
b = b.Bucket([]byte(path[i+1]))
|
||||
if b == nil {
|
||||
return errors.New("updatePairValue: Invalid Path")
|
||||
}
|
||||
}
|
||||
}
|
||||
// Now update the last key in the path
|
||||
err := b.Put([]byte(path[len(path)-1]), []byte(v))
|
||||
return err
|
||||
}
|
||||
return errors.New("updatePairValue: Invalid Path")
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func insertBucket(path []string, n string) error {
|
||||
if AppArgs.ReadOnly {
|
||||
return errors.New("DB is in Read-Only Mode")
|
||||
}
|
||||
// Inserts a new bucket named 'n' at 'path'
|
||||
err := db.Update(func(tx *bbolt.Tx) error {
|
||||
if len(path) == 0 || path[0] == "" {
|
||||
// insert at root
|
||||
_, err := tx.CreateBucket([]byte(n))
|
||||
if err != nil {
|
||||
return fmt.Errorf("insertBucket: %s", err)
|
||||
}
|
||||
} else {
|
||||
rootBucket, path := path[0], path[1:]
|
||||
b := tx.Bucket([]byte(rootBucket))
|
||||
if b != nil {
|
||||
for len(path) > 0 {
|
||||
tstBucket := ""
|
||||
tstBucket, path = path[0], path[1:]
|
||||
nB := b.Bucket([]byte(tstBucket))
|
||||
if nB == nil {
|
||||
// Not a bucket, if we're out of path, just move on
|
||||
if len(path) != 0 {
|
||||
// Out of path, error
|
||||
return errors.New("insertBucket: Invalid Path 1")
|
||||
}
|
||||
} else {
|
||||
b = nB
|
||||
}
|
||||
}
|
||||
_, err := b.CreateBucket([]byte(n))
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("insertBucket: Invalid Path %s", rootBucket)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func insertPair(path []string, k string, v string) error {
|
||||
if AppArgs.ReadOnly {
|
||||
return errors.New("DB is in Read-Only Mode")
|
||||
}
|
||||
// Insert a new pair k => v at path
|
||||
err := db.Update(func(tx *bbolt.Tx) error {
|
||||
if len(path) == 0 {
|
||||
// We cannot insert a pair at root
|
||||
return errors.New("insertPair: Cannot insert pair at root")
|
||||
}
|
||||
var err error
|
||||
b := tx.Bucket([]byte(path[0]))
|
||||
if b == nil {
|
||||
// Invalid path, try for the root bucket
|
||||
b = tx.Cursor().Bucket()
|
||||
}
|
||||
if b != nil {
|
||||
if len(path) > 0 {
|
||||
for i := 1; i < len(path); i++ {
|
||||
b = b.Bucket([]byte(path[i]))
|
||||
if b == nil {
|
||||
return fmt.Errorf("insertPair: %s", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
err := b.Put([]byte(k), []byte(v))
|
||||
if err != nil {
|
||||
return fmt.Errorf("insertPair: %s", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func exportValue(path []string, fName string) error {
|
||||
return db.View(func(tx *bbolt.Tx) error {
|
||||
// len(b.path)-1 is the key whose value we want to export
|
||||
// the rest are buckets leading to that key
|
||||
b := tx.Bucket([]byte(path[0]))
|
||||
if b == nil {
|
||||
// Invalid path, try for the root bucket
|
||||
b = tx.Cursor().Bucket()
|
||||
}
|
||||
if b != nil {
|
||||
if len(path) > 1 {
|
||||
for i := range path[1 : len(path)-1] {
|
||||
b = b.Bucket([]byte(path[i+1]))
|
||||
if b == nil {
|
||||
return errors.New("exportValue: Invalid Path: " + strings.Join(path, "/"))
|
||||
}
|
||||
}
|
||||
}
|
||||
bk := []byte(path[len(path)-1])
|
||||
v := b.Get(bk)
|
||||
return writeToFile(fName, string(v), os.O_CREATE|os.O_WRONLY|os.O_TRUNC)
|
||||
}
|
||||
return errors.New("exportValue: Invalid Bucket")
|
||||
})
|
||||
}
|
||||
|
||||
func exportJSON(path []string, fName string) error {
|
||||
return db.View(func(tx *bbolt.Tx) error {
|
||||
// len(b.path)-1 is the key whose value we want to export
|
||||
// the rest are buckets leading to that key
|
||||
b := tx.Bucket([]byte(path[0]))
|
||||
if b == nil {
|
||||
// Invalid path, try for the root bucket
|
||||
b = tx.Cursor().Bucket()
|
||||
}
|
||||
if b != nil {
|
||||
if len(path) > 1 {
|
||||
for i := range path[1 : len(path)-1] {
|
||||
b = b.Bucket([]byte(path[i+1]))
|
||||
if b == nil {
|
||||
return errors.New("exportValue: Invalid Path: " + strings.Join(path, "/"))
|
||||
}
|
||||
}
|
||||
}
|
||||
bk := []byte(path[len(path)-1])
|
||||
if v := b.Get(bk); v != nil {
|
||||
return writeToFile(fName, "{\""+string(bk)+"\":\""+string(v)+"\"}", os.O_CREATE|os.O_WRONLY|os.O_TRUNC)
|
||||
}
|
||||
if b.Bucket(bk) != nil {
|
||||
return writeToFile(fName, genJSONString(b.Bucket(bk)), os.O_CREATE|os.O_WRONLY|os.O_TRUNC)
|
||||
}
|
||||
return writeToFile(fName, genJSONString(b), os.O_CREATE|os.O_WRONLY|os.O_TRUNC)
|
||||
}
|
||||
return errors.New("exportValue: Invalid Bucket")
|
||||
})
|
||||
}
|
||||
|
||||
func genJSONString(b *bbolt.Bucket) string {
|
||||
ret := "{"
|
||||
b.ForEach(func(k, v []byte) error {
|
||||
ret = fmt.Sprintf("%s\"%s\":", ret, string(k))
|
||||
if v == nil {
|
||||
ret = fmt.Sprintf("%s%s,", ret, genJSONString(b.Bucket(k)))
|
||||
} else {
|
||||
ret = fmt.Sprintf("%s\"%s\",", ret, string(v))
|
||||
}
|
||||
return nil
|
||||
})
|
||||
ret = fmt.Sprintf("%s}", ret[:len(ret)-1])
|
||||
return ret
|
||||
}
|
||||
|
||||
func logToFile(s string) error {
|
||||
return writeToFile("bolt-log", s+"\n", os.O_RDWR|os.O_APPEND)
|
||||
}
|
||||
|
||||
func writeToFile(fn, s string, mode int) error {
|
||||
var f *os.File
|
||||
var err error
|
||||
if f == nil {
|
||||
f, err = os.OpenFile(fn, mode, 0660)
|
||||
}
|
||||
defer f.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = f.WriteString(s); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = f.Sync(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func importValue(path []string, fName string) error {
|
||||
if AppArgs.ReadOnly {
|
||||
return errors.New("DB is in Read-Only Mode")
|
||||
}
|
||||
return db.Update(func(tx *bbolt.Tx) error {
|
||||
// len(b.GetPath())-1 is the key for the pair we're updating,
|
||||
// the rest are buckets leading to that key
|
||||
b := tx.Bucket([]byte(path[0]))
|
||||
if b == nil {
|
||||
// Invalid path, try for the root bucket
|
||||
b = tx.Cursor().Bucket()
|
||||
}
|
||||
if b != nil {
|
||||
if len(path) > 0 {
|
||||
for i := range path[1 : len(path)-1] {
|
||||
b = b.Bucket([]byte(path[i+1]))
|
||||
if b == nil {
|
||||
return errors.New("updatePairValue: Invalid Path")
|
||||
}
|
||||
}
|
||||
}
|
||||
// Now update the last key in the path
|
||||
bk := []byte(path[len(path)-1])
|
||||
v, err := os.ReadFile(fName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return b.Put(bk, v)
|
||||
}
|
||||
return errors.New("importValue: Invalid Bucket")
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package main
|
||||
|
||||
type Cursor struct {
|
||||
x int
|
||||
y int
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/nsf/termbox-go"
|
||||
"go.etcd.io/bbolt"
|
||||
)
|
||||
|
||||
var ProgramName = "boltbrowser"
|
||||
var VersionNum = 2.0
|
||||
|
||||
var databaseFiles []string
|
||||
var db *bbolt.DB
|
||||
var memBolt *BoltDB
|
||||
|
||||
var currentFilename string
|
||||
|
||||
const DefaultDBOpenTimeout = time.Second
|
||||
|
||||
var AppArgs struct {
|
||||
DBOpenTimeout time.Duration
|
||||
ReadOnly bool
|
||||
NoValue bool
|
||||
}
|
||||
|
||||
func init() {
|
||||
AppArgs.DBOpenTimeout = DefaultDBOpenTimeout
|
||||
AppArgs.ReadOnly = false
|
||||
}
|
||||
|
||||
func parseArgs() {
|
||||
var err error
|
||||
if len(os.Args) == 1 {
|
||||
printUsage(nil)
|
||||
}
|
||||
parms := os.Args[1:]
|
||||
for i := range parms {
|
||||
// All 'option' arguments start with "-"
|
||||
if !strings.HasPrefix(parms[i], "-") {
|
||||
databaseFiles = append(databaseFiles, parms[i])
|
||||
continue
|
||||
}
|
||||
if strings.Contains(parms[i], "=") {
|
||||
// Key/Value pair Arguments
|
||||
pts := strings.Split(parms[i], "=")
|
||||
key, val := pts[0], pts[1]
|
||||
switch key {
|
||||
case "-timeout":
|
||||
AppArgs.DBOpenTimeout, err = time.ParseDuration(val)
|
||||
if err != nil {
|
||||
// See if we can successfully parse by adding a 's'
|
||||
AppArgs.DBOpenTimeout, err = time.ParseDuration(val + "s")
|
||||
}
|
||||
// If err is still not nil, print usage
|
||||
if err != nil {
|
||||
printUsage(err)
|
||||
}
|
||||
case "-readonly", "-ro":
|
||||
if val == "true" {
|
||||
AppArgs.ReadOnly = true
|
||||
}
|
||||
case "-no-value":
|
||||
if val == "true" {
|
||||
AppArgs.NoValue = true
|
||||
}
|
||||
case "-help":
|
||||
printUsage(nil)
|
||||
default:
|
||||
printUsage(errors.New("Invalid option"))
|
||||
}
|
||||
} else {
|
||||
// Single-word arguments
|
||||
switch parms[i] {
|
||||
case "-readonly", "-ro":
|
||||
AppArgs.ReadOnly = true
|
||||
case "-no-value":
|
||||
AppArgs.NoValue = true
|
||||
case "-help":
|
||||
printUsage(nil)
|
||||
default:
|
||||
printUsage(errors.New("Invalid option"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func printUsage(err error) {
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, err.Error())
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "Usage: %s [OPTIONS] <filename(s)>\nOptions:\n", ProgramName)
|
||||
fmt.Fprintf(os.Stderr, " -timeout=duration\n DB file open timeout (default 1s)\n")
|
||||
fmt.Fprintf(os.Stderr, " -ro, -readonly \n Open the DB in read-only mode\n")
|
||||
fmt.Fprintf(os.Stderr, " -no-value \n Do not display a value in left pane\n")
|
||||
}
|
||||
|
||||
func main() {
|
||||
var err error
|
||||
|
||||
parseArgs()
|
||||
|
||||
err = termbox.Init()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer termbox.Close()
|
||||
style := defaultStyle()
|
||||
termbox.SetOutputMode(termbox.Output256)
|
||||
|
||||
for _, databaseFile := range databaseFiles {
|
||||
currentFilename = databaseFile
|
||||
db, err = bbolt.Open(databaseFile, 0600, &bbolt.Options{Timeout: AppArgs.DBOpenTimeout})
|
||||
if err == bbolt.ErrTimeout {
|
||||
termbox.Close()
|
||||
fmt.Printf("File %s is locked. Make sure it's not used by another app and try again\n", databaseFile)
|
||||
os.Exit(1)
|
||||
} else if err != nil {
|
||||
if len(databaseFiles) > 1 {
|
||||
mainLoop(nil, style)
|
||||
continue
|
||||
} else {
|
||||
termbox.Close()
|
||||
fmt.Printf("Error reading file: %q\n", err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// First things first, load the database into memory
|
||||
memBolt.refreshDatabase()
|
||||
if AppArgs.ReadOnly {
|
||||
// If we're opening it in readonly mode, close it now
|
||||
db.Close()
|
||||
}
|
||||
|
||||
// Kick off the UI loop
|
||||
mainLoop(memBolt, style)
|
||||
defer db.Close()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
//go:build !windows
|
||||
// +build !windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
|
||||
"github.com/nsf/termbox-go"
|
||||
)
|
||||
|
||||
func mainLoop(memBolt *BoltDB, style Style) {
|
||||
screens := defaultScreensForData(memBolt)
|
||||
displayScreen := screens[BrowserScreenIndex]
|
||||
layoutAndDrawScreen(displayScreen, style)
|
||||
for {
|
||||
event := termbox.PollEvent()
|
||||
if event.Type == termbox.EventKey {
|
||||
if event.Key == termbox.KeyCtrlZ {
|
||||
process, _ := os.FindProcess(os.Getpid())
|
||||
termbox.Close()
|
||||
process.Signal(syscall.SIGSTOP)
|
||||
termbox.Init()
|
||||
}
|
||||
newScreenIndex := displayScreen.handleKeyEvent(event)
|
||||
if newScreenIndex < len(screens) {
|
||||
displayScreen = screens[newScreenIndex]
|
||||
layoutAndDrawScreen(displayScreen, style)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
if event.Type == termbox.EventResize {
|
||||
layoutAndDrawScreen(displayScreen, style)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//go:build windows
|
||||
|
||||
package main
|
||||
|
||||
// Windows doesn't support process backgrounding like *nix.
|
||||
// So we have a separate loop for it.
|
||||
|
||||
import "github.com/nsf/termbox-go"
|
||||
|
||||
func mainLoop(memBolt *BoltDB, style Style) {
|
||||
screens := defaultScreensForData(memBolt)
|
||||
displayScreen := screens[BrowserScreenIndex]
|
||||
layoutAndDrawScreen(displayScreen, style)
|
||||
for {
|
||||
event := termbox.PollEvent()
|
||||
if event.Type == termbox.EventKey {
|
||||
newScreenIndex := displayScreen.handleKeyEvent(event)
|
||||
if newScreenIndex < len(screens) {
|
||||
displayScreen = screens[newScreenIndex]
|
||||
layoutAndDrawScreen(displayScreen, style)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
if event.Type == termbox.EventResize {
|
||||
layoutAndDrawScreen(displayScreen, style)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package main
|
||||
|
||||
import "github.com/nsf/termbox-go"
|
||||
|
||||
// Screen is a basic structure for all of the applications screens
|
||||
type Screen interface {
|
||||
handleKeyEvent(event termbox.Event) int
|
||||
performLayout()
|
||||
drawScreen(style Style)
|
||||
}
|
||||
|
||||
const (
|
||||
// BrowserScreenIndex is the index
|
||||
BrowserScreenIndex = iota
|
||||
// AboutScreenIndex The idx number for the 'About' Screen
|
||||
AboutScreenIndex
|
||||
// ExitScreenIndex The idx number for Exiting
|
||||
ExitScreenIndex
|
||||
)
|
||||
|
||||
func defaultScreensForData(db *BoltDB) []Screen {
|
||||
browserScreen := BrowserScreen{db: db, rightViewPort: ViewPort{}, leftViewPort: ViewPort{}}
|
||||
aboutScreen := AboutScreen(0)
|
||||
screens := [...]Screen{
|
||||
&browserScreen,
|
||||
&aboutScreen,
|
||||
}
|
||||
|
||||
return screens[:]
|
||||
}
|
||||
|
||||
func drawBackground(bg termbox.Attribute) {
|
||||
termbox.Clear(0, bg)
|
||||
}
|
||||
|
||||
func layoutAndDrawScreen(screen Screen, style Style) {
|
||||
screen.performLayout()
|
||||
drawBackground(style.defaultBg)
|
||||
screen.drawScreen(style)
|
||||
termbox.Flush()
|
||||
}
|
||||
|
||||
type Line struct {
|
||||
Text string
|
||||
Fg termbox.Attribute
|
||||
Bg termbox.Attribute
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
termboxUtil "github.com/br0xen/termbox-util"
|
||||
"github.com/nsf/termbox-go"
|
||||
)
|
||||
|
||||
/*
|
||||
Command is a struct for associating descriptions to keys
|
||||
*/
|
||||
type Command struct {
|
||||
key string
|
||||
description string
|
||||
}
|
||||
|
||||
/*
|
||||
AboutScreen is just a basic 'int' type that we can extend to make this screen
|
||||
*/
|
||||
type AboutScreen int
|
||||
|
||||
func drawCommandAtPoint(cmd Command, xPos int, yPos int, style Style) {
|
||||
termboxUtil.DrawStringAtPoint(fmt.Sprintf("%6s", cmd.key), xPos, yPos, style.defaultFg, style.defaultBg)
|
||||
termboxUtil.DrawStringAtPoint(cmd.description, xPos+8, yPos, style.defaultFg, style.defaultBg)
|
||||
}
|
||||
|
||||
func (screen *AboutScreen) handleKeyEvent(event termbox.Event) int {
|
||||
return BrowserScreenIndex
|
||||
}
|
||||
|
||||
func (screen *AboutScreen) performLayout() {}
|
||||
|
||||
func (screen *AboutScreen) drawScreen(style Style) {
|
||||
defaultFg := style.defaultFg
|
||||
defaultBg := style.defaultBg
|
||||
width, height := termbox.Size()
|
||||
template := [...]string{
|
||||
" _______ _______ ___ _______ _______ ______ _______ _ _ _______ _______ ______ ",
|
||||
"| _ || || | | || _ || _ | | || | _ | || || || _ | ",
|
||||
"| |_| || _ || | |_ _|| |_| || | || | _ || || || || _____|| ___|| | || ",
|
||||
"| || | | || | | | | || |_||_ | | | || || |_____ | |___ | |_||_ ",
|
||||
"| _ | | |_| || |___ | | | _ | | __ || |_| || ||_____ || ___|| __ |",
|
||||
"| |_| || || || | | |_| || | | || || _ | _____| || |___ | | | |",
|
||||
"|_______||_______||_______||___| |_______||___| |_||_______||__| |__||_______||_______||___| |_|",
|
||||
}
|
||||
if width < 100 {
|
||||
template = [...]string{
|
||||
" ____ ____ _ _____ ____ ____ ____ _ _ ____ ___ ____ ",
|
||||
"| _ || || | | || _ || _ | | || | _ | || || || _ | ",
|
||||
"| |_||| _ || | |_ _|| |_||| | || | _ || || || || ___|| _|| | || ",
|
||||
"| ||| | || | | | | || |_|| || | || |||___ | |_ | |_||_ ",
|
||||
"| _ |||_| || |___| | | _ || _ |||_| || ||__ || _|| __ |",
|
||||
"| |_||| || | | | |_||| | | || || _ | __| || |_ | | | |",
|
||||
"|____||____||_____|_| |____||_| |_||____||__| |__||____||___||_| |_|",
|
||||
}
|
||||
}
|
||||
firstLine := template[0]
|
||||
startX := (width - len(firstLine)) / 2
|
||||
//startX := (width - len(firstLine)) / 2
|
||||
startY := ((height - 2*len(template)) / 2) - 2
|
||||
xPos := startX
|
||||
yPos := startY
|
||||
if height <= 20 {
|
||||
title := "BoltBrowser"
|
||||
startY = 0
|
||||
yPos = 0
|
||||
termboxUtil.DrawStringAtPoint(title, (width-len(title))/2, startY, style.titleFg, style.titleBg)
|
||||
} else {
|
||||
if height < 25 {
|
||||
startY = 0
|
||||
yPos = 0
|
||||
}
|
||||
for _, line := range template {
|
||||
xPos = startX
|
||||
for _, runeValue := range line {
|
||||
bg := defaultBg
|
||||
displayRune := ' '
|
||||
if runeValue != ' ' {
|
||||
//bg = termbox.Attribute(125)
|
||||
displayRune = runeValue
|
||||
termbox.SetCell(xPos, yPos, displayRune, defaultFg, bg)
|
||||
}
|
||||
xPos++
|
||||
}
|
||||
yPos++
|
||||
}
|
||||
}
|
||||
yPos++
|
||||
versionString := fmt.Sprintf("Version: %0.1f", VersionNum)
|
||||
termboxUtil.DrawStringAtPoint(versionString, (width-len(versionString))/2, yPos, style.defaultFg, style.defaultBg)
|
||||
|
||||
commands1 := []Command{
|
||||
{"h,←", "close parent"},
|
||||
{"j,↓", "down"},
|
||||
{"k,↑", "up"},
|
||||
{"l,→", "open item"},
|
||||
{"J", "scroll right pane down"},
|
||||
{"K", "scroll right pane up"},
|
||||
{"", ""},
|
||||
{"g", "goto top"},
|
||||
{"G", "goto bottom"},
|
||||
{"", ""},
|
||||
{"ctrl+f", "jump down"},
|
||||
{"ctrl+b", "jump up"},
|
||||
}
|
||||
|
||||
commands2 := []Command{
|
||||
{"p,P", "create pair/at parent"},
|
||||
{"b,B", "create bucket/at parent"},
|
||||
{"e", "edit value of pair"},
|
||||
{"r", "rename pair/bucket"},
|
||||
{"", ""},
|
||||
{"D", "delete item"},
|
||||
{"x,X", "export as string/json to file"},
|
||||
{"i", "import file to value of pair"},
|
||||
{"", ""},
|
||||
{"?", "this screen"},
|
||||
{"q", "quit program"},
|
||||
}
|
||||
var maxCmd1 int
|
||||
for k := range commands1 {
|
||||
tst := len(commands1[k].key) + 1 + len(commands1[k].description)
|
||||
if tst > maxCmd1 {
|
||||
maxCmd1 = tst
|
||||
}
|
||||
}
|
||||
var maxCmd2 int
|
||||
for k := range commands2 {
|
||||
tst := len(commands2[k].key) + 1 + len(commands2[k].description)
|
||||
if tst > maxCmd2 {
|
||||
maxCmd2 = tst
|
||||
}
|
||||
}
|
||||
xPos = (width / 2) - ((maxCmd1 + maxCmd2) / 2)
|
||||
yPos++
|
||||
|
||||
for k := range commands1 {
|
||||
drawCommandAtPoint(commands1[k], xPos, yPos+1+k, style)
|
||||
}
|
||||
for k := range commands2 {
|
||||
drawCommandAtPoint(commands2[k], xPos+40, yPos+1+k, style)
|
||||
}
|
||||
exitTxt := "Press any key to return to browser"
|
||||
termboxUtil.DrawStringAtPoint(exitTxt, (width-len(exitTxt))/2, height-1, style.titleFg, style.titleBg)
|
||||
}
|
||||
@@ -0,0 +1,998 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
termboxUtil "github.com/br0xen/termbox-util"
|
||||
"github.com/nsf/termbox-go"
|
||||
)
|
||||
|
||||
/*
|
||||
ViewPort helps keep track of what's being displayed on the screen
|
||||
*/
|
||||
type ViewPort struct {
|
||||
bytesPerRow int
|
||||
numberOfRows int
|
||||
firstRow int
|
||||
scrollRow int
|
||||
}
|
||||
|
||||
/*
|
||||
BrowserScreen holds all that's going on :D
|
||||
*/
|
||||
type BrowserScreen struct {
|
||||
db *BoltDB
|
||||
leftViewPort ViewPort
|
||||
rightViewPort ViewPort
|
||||
queuedCommand string
|
||||
currentPath []string
|
||||
currentType int
|
||||
message string
|
||||
filter string
|
||||
mode BrowserMode
|
||||
inputModal *termboxUtil.InputModal
|
||||
confirmModal *termboxUtil.ConfirmModal
|
||||
messageTimeout time.Duration
|
||||
messageTime time.Time
|
||||
|
||||
leftPaneBuffer []Line
|
||||
rightPaneBuffer []Line
|
||||
}
|
||||
|
||||
/*
|
||||
BrowserMode is just for designating the mode that we're in
|
||||
*/
|
||||
type BrowserMode int
|
||||
|
||||
const (
|
||||
modeBrowse = 16 // 0000 0001 0000
|
||||
modeChange = 32 // 0000 0010 0000
|
||||
modeChangeKey = 33 // 0000 0010 0001
|
||||
modeChangeVal = 34 // 0000 0010 0010
|
||||
modeFilter = 35 // 0100 0010 0011
|
||||
modeInsert = 64 // 0000 0100 0000
|
||||
modeInsertBucket = 65 // 0000 0100 0001
|
||||
modeInsertPair = 68 // 0000 0100 0100
|
||||
modeInsertPairKey = 69 // 0000 0100 0101
|
||||
modeInsertPairVal = 70 // 0000 0100 0110
|
||||
modeDelete = 256 // 0001 0000 0000
|
||||
modeModToParent = 8 // 0000 0000 1000
|
||||
modeIO = 512 // 0010 0000 0000
|
||||
modeIOExportValue = 513 // 0010 0000 0001
|
||||
modeIOExportJSON = 514 // 0010 0000 0010
|
||||
modeIOImportValue = 516 // 0010 0000 0100
|
||||
)
|
||||
|
||||
/*
|
||||
BoltType is just for tracking what type of db item we're looking at
|
||||
*/
|
||||
type BoltType int
|
||||
|
||||
const (
|
||||
typeBucket = iota
|
||||
typePair
|
||||
)
|
||||
|
||||
func (screen *BrowserScreen) handleKeyEvent(event termbox.Event) int {
|
||||
if screen.mode == 0 {
|
||||
screen.mode = modeBrowse
|
||||
}
|
||||
if screen.mode == modeBrowse {
|
||||
return screen.handleBrowseKeyEvent(event)
|
||||
} else if screen.mode&modeChange == modeChange {
|
||||
return screen.handleInputKeyEvent(event)
|
||||
} else if screen.mode&modeInsert == modeInsert {
|
||||
return screen.handleInsertKeyEvent(event)
|
||||
} else if screen.mode == modeDelete {
|
||||
return screen.handleDeleteKeyEvent(event)
|
||||
} else if screen.mode&modeIO == modeIO {
|
||||
return screen.handleIOKeyEvent(event)
|
||||
}
|
||||
return BrowserScreenIndex
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) handleBrowseKeyEvent(event termbox.Event) int {
|
||||
if event.Ch == '?' {
|
||||
// About
|
||||
return AboutScreenIndex
|
||||
|
||||
} else if event.Ch == 'q' || event.Key == termbox.KeyEsc || event.Key == termbox.KeyCtrlC {
|
||||
// Quit
|
||||
return ExitScreenIndex
|
||||
|
||||
} else if event.Ch == 'g' {
|
||||
// Jump to Beginning
|
||||
screen.currentPath = screen.db.getNextVisiblePath(nil, screen.filter)
|
||||
|
||||
} else if event.Ch == 'G' {
|
||||
// Jump to End
|
||||
screen.currentPath = screen.db.getPrevVisiblePath(nil, screen.filter)
|
||||
|
||||
} else if event.Key == termbox.KeyCtrlR {
|
||||
screen.refreshDatabase()
|
||||
|
||||
} else if event.Key == termbox.KeyCtrlF {
|
||||
// Jump forward half a screen
|
||||
_, h := termbox.Size()
|
||||
half := h / 2
|
||||
screen.jumpCursorDown(half)
|
||||
|
||||
} else if event.Key == termbox.KeyCtrlB {
|
||||
_, h := termbox.Size()
|
||||
half := h / 2
|
||||
screen.jumpCursorUp(half)
|
||||
|
||||
} else if event.Ch == 'j' || event.Key == termbox.KeyArrowDown {
|
||||
screen.moveCursorDown()
|
||||
|
||||
} else if event.Ch == 'k' || event.Key == termbox.KeyArrowUp {
|
||||
screen.moveCursorUp()
|
||||
|
||||
} else if event.Ch == 'J' {
|
||||
screen.moveRightPaneDown()
|
||||
|
||||
} else if event.Ch == 'K' {
|
||||
screen.moveRightPaneUp()
|
||||
|
||||
} else if event.Ch == 'p' {
|
||||
// p creates a new pair at the current level
|
||||
screen.startInsertItem(typePair)
|
||||
} else if event.Ch == 'P' {
|
||||
// P creates a new pair at the parent level
|
||||
screen.startInsertItemAtParent(typePair)
|
||||
|
||||
} else if event.Ch == 'b' {
|
||||
// b creates a new bucket at the current level
|
||||
screen.startInsertItem(typeBucket)
|
||||
} else if event.Ch == 'B' {
|
||||
// B creates a new bucket at the parent level
|
||||
screen.startInsertItemAtParent(typeBucket)
|
||||
|
||||
} else if event.Ch == 'e' {
|
||||
b, p, _ := screen.db.getGenericFromPath(screen.currentPath)
|
||||
if b != nil {
|
||||
screen.setMessage("Cannot edit a bucket, did you mean to (r)ename?")
|
||||
} else if p != nil {
|
||||
screen.startEditItem()
|
||||
}
|
||||
} else if event.Ch == '/' {
|
||||
screen.startFilter()
|
||||
|
||||
} else if event.Ch == 'r' {
|
||||
screen.startRenameItem()
|
||||
|
||||
} else if event.Key == termbox.KeyEnter {
|
||||
b, p, _ := screen.db.getGenericFromPath(screen.currentPath)
|
||||
if b != nil {
|
||||
screen.db.toggleOpenBucket(screen.currentPath)
|
||||
} else if p != nil {
|
||||
screen.startEditItem()
|
||||
}
|
||||
|
||||
} else if event.Ch == 'l' || event.Key == termbox.KeyArrowRight {
|
||||
b, p, _ := screen.db.getGenericFromPath(screen.currentPath)
|
||||
// Select the current item
|
||||
if b != nil {
|
||||
screen.db.toggleOpenBucket(screen.currentPath)
|
||||
} else if p != nil {
|
||||
screen.startEditItem()
|
||||
} else {
|
||||
screen.setMessage("Not sure what to do here...")
|
||||
}
|
||||
|
||||
} else if event.Ch == 'h' || event.Key == termbox.KeyArrowLeft {
|
||||
// If we are _on_ a bucket that's open, close it
|
||||
b, _, e := screen.db.getGenericFromPath(screen.currentPath)
|
||||
if e == nil && b != nil && b.expanded {
|
||||
screen.db.closeBucket(screen.currentPath)
|
||||
} else {
|
||||
if len(screen.currentPath) > 1 {
|
||||
parentBucket, err := screen.db.getBucketFromPath(screen.currentPath[:len(screen.currentPath)-1])
|
||||
if err == nil {
|
||||
screen.db.closeBucket(parentBucket.GetPath())
|
||||
// Figure out how far up we need to move the cursor
|
||||
screen.currentPath = parentBucket.GetPath()
|
||||
}
|
||||
} else {
|
||||
screen.db.closeBucket(screen.currentPath)
|
||||
}
|
||||
}
|
||||
|
||||
} else if event.Ch == 'D' {
|
||||
screen.startDeleteItem()
|
||||
} else if event.Ch == 'x' {
|
||||
// Export Value to a file
|
||||
screen.startExportValue()
|
||||
} else if event.Ch == 'X' {
|
||||
// Export Key/Value (or Bucket) as JSON
|
||||
screen.startExportJSON()
|
||||
} else if event.Ch == 'i' {
|
||||
// Import value from a file
|
||||
screen.startImportValue()
|
||||
}
|
||||
return BrowserScreenIndex
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) handleInputKeyEvent(event termbox.Event) int {
|
||||
if event.Key == termbox.KeyEsc {
|
||||
screen.mode = modeBrowse
|
||||
screen.inputModal.Clear()
|
||||
} else {
|
||||
screen.inputModal.HandleEvent(event)
|
||||
if screen.inputModal.IsDone() {
|
||||
b, p, _ := screen.db.getGenericFromPath(screen.currentPath)
|
||||
if screen.mode == modeFilter {
|
||||
screen.filter = screen.inputModal.GetValue()
|
||||
if !screen.db.isVisiblePath(screen.currentPath, screen.filter) {
|
||||
screen.currentPath = screen.currentPath[:len(screen.currentPath)-1]
|
||||
}
|
||||
}
|
||||
if b != nil {
|
||||
if screen.mode == modeChangeKey {
|
||||
newName := screen.inputModal.GetValue()
|
||||
if renameBucket(screen.currentPath, newName) != nil {
|
||||
screen.setMessage("Error renaming bucket.")
|
||||
} else {
|
||||
b.name = newName
|
||||
screen.currentPath[len(screen.currentPath)-1] = b.name
|
||||
screen.setMessage("Bucket Renamed!")
|
||||
screen.refreshDatabase()
|
||||
}
|
||||
}
|
||||
} else if p != nil {
|
||||
if screen.mode == modeChangeKey {
|
||||
newKey := screen.inputModal.GetValue()
|
||||
if err := updatePairKey(screen.currentPath, newKey); err != nil {
|
||||
screen.setMessage("Error occurred updating Pair.")
|
||||
} else {
|
||||
p.key = newKey
|
||||
screen.currentPath[len(screen.currentPath)-1] = p.key
|
||||
screen.setMessage("Pair updated!")
|
||||
screen.refreshDatabase()
|
||||
}
|
||||
} else if screen.mode == modeChangeVal {
|
||||
newVal := screen.inputModal.GetValue()
|
||||
if err := updatePairValue(screen.currentPath, newVal); err != nil {
|
||||
screen.setMessage("Error occurred updating Pair.")
|
||||
} else {
|
||||
p.val = newVal
|
||||
screen.setMessage("Pair updated!")
|
||||
screen.refreshDatabase()
|
||||
}
|
||||
}
|
||||
}
|
||||
screen.mode = modeBrowse
|
||||
screen.inputModal.Clear()
|
||||
}
|
||||
}
|
||||
return BrowserScreenIndex
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) handleDeleteKeyEvent(event termbox.Event) int {
|
||||
screen.confirmModal.HandleEvent(event)
|
||||
if screen.confirmModal.IsDone() {
|
||||
if screen.confirmModal.IsAccepted() {
|
||||
holdNextPath := screen.db.getNextVisiblePath(screen.currentPath, screen.filter)
|
||||
holdPrevPath := screen.db.getPrevVisiblePath(screen.currentPath, screen.filter)
|
||||
if deleteKey(screen.currentPath) == nil {
|
||||
screen.refreshDatabase()
|
||||
// Move the current path endpoint appropriately
|
||||
//found_new_path := false
|
||||
if holdNextPath != nil {
|
||||
if len(holdNextPath) > 2 {
|
||||
if holdNextPath[len(holdNextPath)-2] == screen.currentPath[len(screen.currentPath)-2] {
|
||||
screen.currentPath = holdNextPath
|
||||
} else if holdPrevPath != nil {
|
||||
screen.currentPath = holdPrevPath
|
||||
} else {
|
||||
// Otherwise, go to the parent
|
||||
screen.currentPath = screen.currentPath[:(len(holdNextPath) - 2)]
|
||||
}
|
||||
} else {
|
||||
// Root bucket deleted, set to next
|
||||
screen.currentPath = holdNextPath
|
||||
}
|
||||
} else if holdPrevPath != nil {
|
||||
screen.currentPath = holdPrevPath
|
||||
} else {
|
||||
screen.currentPath = screen.currentPath[:0]
|
||||
}
|
||||
}
|
||||
}
|
||||
screen.mode = modeBrowse
|
||||
screen.confirmModal.Clear()
|
||||
}
|
||||
return BrowserScreenIndex
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) handleInsertKeyEvent(event termbox.Event) int {
|
||||
if event.Key == termbox.KeyEsc {
|
||||
if len(screen.db.buckets) == 0 {
|
||||
return ExitScreenIndex
|
||||
}
|
||||
screen.mode = modeBrowse
|
||||
screen.inputModal.Clear()
|
||||
} else {
|
||||
screen.inputModal.HandleEvent(event)
|
||||
if screen.inputModal.IsDone() {
|
||||
newVal := screen.inputModal.GetValue()
|
||||
screen.inputModal.Clear()
|
||||
var insertPath []string
|
||||
if len(screen.currentPath) > 0 {
|
||||
_, p, e := screen.db.getGenericFromPath(screen.currentPath)
|
||||
if e != nil {
|
||||
screen.setMessage("Error Inserting new item. Invalid Path.")
|
||||
}
|
||||
insertPath = screen.currentPath
|
||||
// where are we inserting?
|
||||
if p != nil {
|
||||
// If we're sitting on a pair, we have to go to it's parent
|
||||
screen.mode = screen.mode | modeModToParent
|
||||
}
|
||||
if screen.mode&modeModToParent == modeModToParent {
|
||||
if len(screen.currentPath) > 1 {
|
||||
insertPath = screen.currentPath[:len(screen.currentPath)-1]
|
||||
} else {
|
||||
insertPath = make([]string, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
parentB, _, _ := screen.db.getGenericFromPath(insertPath)
|
||||
if screen.mode&modeInsertBucket == modeInsertBucket {
|
||||
err := insertBucket(insertPath, newVal)
|
||||
if err != nil {
|
||||
screen.setMessage(fmt.Sprintf("%s => %s", err, insertPath))
|
||||
} else {
|
||||
if parentB != nil {
|
||||
parentB.expanded = true
|
||||
}
|
||||
}
|
||||
screen.currentPath = append(insertPath, newVal)
|
||||
|
||||
screen.refreshDatabase()
|
||||
screen.mode = modeBrowse
|
||||
screen.inputModal.Clear()
|
||||
} else if screen.mode&modeInsertPair == modeInsertPair {
|
||||
err := insertPair(insertPath, newVal, "")
|
||||
if err != nil {
|
||||
screen.setMessage(fmt.Sprintf("%s => %s", err, insertPath))
|
||||
screen.refreshDatabase()
|
||||
screen.mode = modeBrowse
|
||||
screen.inputModal.Clear()
|
||||
} else {
|
||||
if parentB != nil {
|
||||
parentB.expanded = true
|
||||
}
|
||||
screen.currentPath = append(insertPath, newVal)
|
||||
screen.refreshDatabase()
|
||||
screen.startEditItem()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return BrowserScreenIndex
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) handleIOKeyEvent(event termbox.Event) int {
|
||||
if event.Key == termbox.KeyEsc {
|
||||
screen.mode = modeBrowse
|
||||
screen.inputModal.Clear()
|
||||
} else {
|
||||
screen.inputModal.HandleEvent(event)
|
||||
if screen.inputModal.IsDone() {
|
||||
b, p, _ := screen.db.getGenericFromPath(screen.currentPath)
|
||||
fileName := screen.inputModal.GetValue()
|
||||
if screen.mode&modeIOExportValue == modeIOExportValue {
|
||||
// Exporting the value
|
||||
if p != nil {
|
||||
if err := exportValue(screen.currentPath, fileName); err != nil {
|
||||
//screen.setMessage("Error exporting to file " + fileName + ".")
|
||||
screen.setMessage(err.Error())
|
||||
} else {
|
||||
screen.setMessage("Value exported to file: " + fileName)
|
||||
}
|
||||
}
|
||||
} else if screen.mode&modeIOExportJSON == modeIOExportJSON {
|
||||
if b != nil || p != nil {
|
||||
if exportJSON(screen.currentPath, fileName) != nil {
|
||||
screen.setMessage("Error exporting to file " + fileName + ".")
|
||||
} else {
|
||||
screen.setMessage("Value exported to file: " + fileName)
|
||||
}
|
||||
}
|
||||
} else if screen.mode&modeIOImportValue == modeIOImportValue {
|
||||
if p != nil {
|
||||
if err := importValue(screen.currentPath, fileName); err != nil {
|
||||
screen.setMessage(err.Error())
|
||||
} else {
|
||||
screen.setMessage("Value imported from file: " + fileName)
|
||||
screen.refreshDatabase()
|
||||
}
|
||||
}
|
||||
}
|
||||
screen.mode = modeBrowse
|
||||
screen.inputModal.Clear()
|
||||
}
|
||||
}
|
||||
return BrowserScreenIndex
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) jumpCursorUp(distance int) bool {
|
||||
// Jump up 'distance' lines
|
||||
visPaths, err := screen.db.buildVisiblePathSlice(screen.filter)
|
||||
if err == nil {
|
||||
findPath := screen.currentPath
|
||||
for idx, pth := range visPaths {
|
||||
startJump := true
|
||||
for i := range pth {
|
||||
if len(screen.currentPath) > i && pth[i] != screen.currentPath[i] {
|
||||
startJump = false
|
||||
}
|
||||
}
|
||||
if startJump {
|
||||
distance--
|
||||
if distance == 0 {
|
||||
screen.currentPath = visPaths[len(visPaths)-1-idx]
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
isCurPath := true
|
||||
for i := range screen.currentPath {
|
||||
if screen.currentPath[i] != findPath[i] {
|
||||
isCurPath = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if isCurPath {
|
||||
screen.currentPath = screen.db.getNextVisiblePath(nil, screen.filter)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func (screen *BrowserScreen) jumpCursorDown(distance int) bool {
|
||||
visPaths, err := screen.db.buildVisiblePathSlice(screen.filter)
|
||||
if err == nil {
|
||||
findPath := screen.currentPath
|
||||
for idx, pth := range visPaths {
|
||||
startJump := true
|
||||
|
||||
for i := range pth {
|
||||
if len(screen.currentPath) > i && pth[i] != screen.currentPath[i] {
|
||||
startJump = false
|
||||
}
|
||||
}
|
||||
if startJump {
|
||||
distance--
|
||||
if distance == 0 {
|
||||
screen.currentPath = visPaths[idx]
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
isCurPath := true
|
||||
for i := range screen.currentPath {
|
||||
if screen.currentPath[i] != findPath[i] {
|
||||
isCurPath = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if isCurPath {
|
||||
screen.currentPath = screen.db.getNextVisiblePath(nil, screen.filter)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) moveCursorUp() bool {
|
||||
newPath := screen.db.getPrevVisiblePath(screen.currentPath, screen.filter)
|
||||
if newPath != nil {
|
||||
screen.currentPath = newPath
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (screen *BrowserScreen) moveCursorDown() bool {
|
||||
newPath := screen.db.getNextVisiblePath(screen.currentPath, screen.filter)
|
||||
if newPath != nil {
|
||||
screen.currentPath = newPath
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (screen *BrowserScreen) moveRightPaneUp() bool {
|
||||
if screen.rightViewPort.scrollRow > 0 {
|
||||
screen.rightViewPort.scrollRow--
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (screen *BrowserScreen) moveRightPaneDown() bool {
|
||||
screen.rightViewPort.scrollRow++
|
||||
return true
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) performLayout() {}
|
||||
|
||||
func (screen *BrowserScreen) drawScreen(style Style) {
|
||||
if screen.db == nil {
|
||||
screen.drawHeader(style)
|
||||
screen.setMessage("Invalid DB. Press 'q' to quit, '?' for help")
|
||||
screen.drawFooter(style)
|
||||
return
|
||||
}
|
||||
if len(screen.db.buckets) == 0 && screen.mode&modeInsertBucket != modeInsertBucket {
|
||||
// Force a bucket insert
|
||||
screen.startInsertItemAtParent(typeBucket)
|
||||
}
|
||||
if screen.message == "" {
|
||||
screen.setMessageWithTimeout("Press '?' for help", -1)
|
||||
}
|
||||
screen.drawLeftPane(style)
|
||||
screen.drawRightPane(style)
|
||||
screen.drawHeader(style)
|
||||
screen.drawFooter(style)
|
||||
|
||||
if screen.inputModal != nil {
|
||||
screen.inputModal.Draw()
|
||||
}
|
||||
if screen.mode == modeDelete {
|
||||
screen.confirmModal.Draw()
|
||||
}
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) drawHeader(style Style) {
|
||||
width, _ := termbox.Size()
|
||||
headerStringLen := func(fileName string) int {
|
||||
return len(ProgramName) + len(fileName) + 1
|
||||
}
|
||||
headerFileName := currentFilename
|
||||
if headerStringLen(headerFileName) > width {
|
||||
headerFileName = filepath.Base(headerFileName)
|
||||
}
|
||||
headerString := ProgramName + ": " + headerFileName
|
||||
count := ((width - len(headerString)) / 2) + 1
|
||||
if count < 0 {
|
||||
count = 0
|
||||
}
|
||||
spaces := strings.Repeat(" ", count)
|
||||
termboxUtil.DrawStringAtPoint(fmt.Sprintf("%s%s%s", spaces, headerString, spaces), 0, 0, style.titleFg, style.titleBg)
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) drawFooter(style Style) {
|
||||
if screen.messageTimeout > 0 && time.Since(screen.messageTime) > screen.messageTimeout {
|
||||
screen.clearMessage()
|
||||
}
|
||||
_, height := termbox.Size()
|
||||
termboxUtil.DrawStringAtPoint(screen.message, 0, height-1, style.defaultFg, style.defaultBg)
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) buildLeftPane(style Style) {
|
||||
screen.leftPaneBuffer = nil
|
||||
if len(screen.currentPath) == 0 {
|
||||
screen.currentPath = screen.db.getNextVisiblePath(nil, screen.filter)
|
||||
}
|
||||
for i := range screen.db.buckets {
|
||||
screen.leftPaneBuffer = append(screen.leftPaneBuffer, screen.bucketToLines(&screen.db.buckets[i], style)...)
|
||||
}
|
||||
// Find the cursor in the leftPane
|
||||
for k, v := range screen.leftPaneBuffer {
|
||||
if v.Fg == style.cursorFg {
|
||||
screen.leftViewPort.scrollRow = k
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) drawLeftPane(style Style) {
|
||||
screen.buildLeftPane(style)
|
||||
w, h := termbox.Size()
|
||||
if w > 80 {
|
||||
w = w / 2
|
||||
}
|
||||
screen.leftViewPort.bytesPerRow = w
|
||||
screen.leftViewPort.numberOfRows = h - 2
|
||||
termboxUtil.FillWithChar('=', 0, 1, w, 1, style.defaultFg, style.defaultBg)
|
||||
startX, startY := 0, 3
|
||||
screen.leftViewPort.firstRow = startY
|
||||
treeOffset := 0
|
||||
maxCursor := screen.leftViewPort.numberOfRows * 2 / 3
|
||||
|
||||
if screen.leftViewPort.scrollRow > maxCursor {
|
||||
treeOffset = screen.leftViewPort.scrollRow - maxCursor
|
||||
}
|
||||
if len(screen.leftPaneBuffer) > 0 {
|
||||
for k, v := range screen.leftPaneBuffer[treeOffset:] {
|
||||
termboxUtil.DrawStringAtPoint(v.Text, startX, (startY + k - 1), v.Fg, v.Bg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) buildRightPane(style Style) {
|
||||
screen.rightPaneBuffer = nil
|
||||
b, p, err := screen.db.getGenericFromPath(screen.currentPath)
|
||||
if err == nil {
|
||||
if b != nil {
|
||||
screen.rightPaneBuffer = append(screen.rightPaneBuffer,
|
||||
Line{fmt.Sprintf("Path: %s", strings.Join(stringifyPath(b.GetPath()), " → ")), style.defaultFg, style.defaultBg})
|
||||
screen.rightPaneBuffer = append(screen.rightPaneBuffer,
|
||||
Line{fmt.Sprintf("Buckets: %d", len(b.buckets)), style.defaultFg, style.defaultBg})
|
||||
screen.rightPaneBuffer = append(screen.rightPaneBuffer,
|
||||
Line{fmt.Sprintf("Pairs: %d", len(b.pairs)), style.defaultFg, style.defaultBg})
|
||||
} else if p != nil {
|
||||
screen.rightPaneBuffer = append(screen.rightPaneBuffer,
|
||||
Line{fmt.Sprintf("Path: %s", strings.Join(stringifyPath(p.GetPath()), " → ")), style.defaultFg, style.defaultBg})
|
||||
screen.rightPaneBuffer = append(screen.rightPaneBuffer,
|
||||
Line{fmt.Sprintf("Key: %s", stringify([]byte(p.key))), style.defaultFg, style.defaultBg})
|
||||
|
||||
value := strings.Split(string(formatValue([]byte(p.val))), "\n")
|
||||
if len(value) == 1 {
|
||||
screen.rightPaneBuffer = append(screen.rightPaneBuffer,
|
||||
Line{fmt.Sprintf("Value: %s", value[0]), style.defaultFg, style.defaultBg})
|
||||
} else {
|
||||
screen.rightPaneBuffer = append(screen.rightPaneBuffer,
|
||||
Line{"Value:", style.defaultFg, style.defaultBg})
|
||||
for _, v := range value {
|
||||
screen.rightPaneBuffer = append(screen.rightPaneBuffer,
|
||||
Line{v, style.defaultFg, style.defaultBg})
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
screen.rightPaneBuffer = append(screen.rightPaneBuffer,
|
||||
Line{fmt.Sprintf("Path: %s", strings.Join(stringifyPath(screen.currentPath), " → ")), style.defaultFg, style.defaultBg})
|
||||
screen.rightPaneBuffer = append(screen.rightPaneBuffer,
|
||||
Line{err.Error(), termbox.ColorRed, termbox.ColorBlack})
|
||||
}
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) drawRightPane(style Style) {
|
||||
screen.buildRightPane(style)
|
||||
w, h := termbox.Size()
|
||||
if w > 80 {
|
||||
screen.rightViewPort.bytesPerRow = w / 2
|
||||
screen.rightViewPort.numberOfRows = h - 2
|
||||
// Screen is wide enough, split it
|
||||
termboxUtil.FillWithChar('=', 0, 1, w, 1, style.defaultFg, style.defaultBg)
|
||||
termboxUtil.FillWithChar('|', (w / 2), screen.rightViewPort.firstRow-1, (w / 2), h, style.defaultFg, style.defaultBg)
|
||||
// Clear the right pane
|
||||
termboxUtil.FillWithChar(' ', (w/2)+1, screen.rightViewPort.firstRow+2, w, h, style.defaultFg, style.defaultBg)
|
||||
|
||||
startX := (w / 2) + 2
|
||||
startY := 3
|
||||
maxScroll := len(screen.rightPaneBuffer) - screen.rightViewPort.numberOfRows
|
||||
if maxScroll < 0 {
|
||||
maxScroll = 0
|
||||
}
|
||||
if screen.rightViewPort.scrollRow > maxScroll {
|
||||
screen.rightViewPort.scrollRow = maxScroll
|
||||
}
|
||||
if len(screen.rightPaneBuffer) > 0 {
|
||||
for k, v := range screen.rightPaneBuffer[screen.rightViewPort.scrollRow:] {
|
||||
termboxUtil.DrawStringAtPoint(v.Text, startX, (startY + k - 1), v.Fg, v.Bg)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func formatValue(val []byte) []byte {
|
||||
// Attempt JSON parsing and formatting
|
||||
out, err := formatValueJSON(val)
|
||||
if err == nil {
|
||||
return out
|
||||
}
|
||||
return []byte(stringify([]byte(val)))
|
||||
}
|
||||
|
||||
func formatValueJSON(val []byte) ([]byte, error) {
|
||||
var jsonOut interface{}
|
||||
err := json.Unmarshal(val, &jsonOut)
|
||||
if err != nil {
|
||||
return val, err
|
||||
}
|
||||
out, err := json.MarshalIndent(jsonOut, "", " ")
|
||||
if err != nil {
|
||||
return val, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) bucketToLines(bkt *BoltBucket, style Style) []Line {
|
||||
var ret []Line
|
||||
bfg, bbg := style.defaultFg, style.defaultBg
|
||||
if comparePaths(screen.currentPath, bkt.GetPath()) {
|
||||
bfg, bbg = style.cursorFg, style.cursorBg
|
||||
}
|
||||
bktPrefix := strings.Repeat(" ", len(bkt.GetPath())*2)
|
||||
if bkt.expanded {
|
||||
ret = append(ret, Line{bktPrefix + "- " + stringify([]byte(bkt.name)), bfg, bbg})
|
||||
for i := range bkt.buckets {
|
||||
ret = append(ret, screen.bucketToLines(&bkt.buckets[i], style)...)
|
||||
}
|
||||
for _, bp := range bkt.pairs {
|
||||
if screen.filter != "" && !strings.Contains(bp.key, screen.filter) {
|
||||
continue
|
||||
}
|
||||
pfg, pbg := style.defaultFg, style.defaultBg
|
||||
if comparePaths(screen.currentPath, bp.GetPath()) {
|
||||
pfg, pbg = style.cursorFg, style.cursorBg
|
||||
}
|
||||
prPrefix := strings.Repeat(" ", len(bp.GetPath())*2)
|
||||
var pairString string
|
||||
if AppArgs.NoValue {
|
||||
pairString = fmt.Sprintf("%s%s", prPrefix, stringify([]byte(bp.key)))
|
||||
} else {
|
||||
pairString = fmt.Sprintf("%s%s: %s", prPrefix, stringify([]byte(bp.key)), stringify([]byte(bp.val)))
|
||||
}
|
||||
ret = append(ret, Line{pairString, pfg, pbg})
|
||||
}
|
||||
} else {
|
||||
ret = append(ret, Line{bktPrefix + "+ " + stringify([]byte(bkt.name)), bfg, bbg})
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) startDeleteItem() bool {
|
||||
b, p, e := screen.db.getGenericFromPath(screen.currentPath)
|
||||
if e == nil {
|
||||
w, h := termbox.Size()
|
||||
inpW, inpH := (w / 2), 6
|
||||
inpX, inpY := ((w / 2) - (inpW / 2)), ((h / 2) - inpH)
|
||||
mod := termboxUtil.CreateConfirmModal("", inpX, inpY, inpW, inpH, termbox.ColorWhite, termbox.ColorBlack)
|
||||
if b != nil {
|
||||
mod.SetTitle(termboxUtil.AlignText(fmt.Sprintf("Delete Bucket '%s'?", b.name), inpW-1, termboxUtil.AlignCenter))
|
||||
} else if p != nil {
|
||||
mod.SetTitle(termboxUtil.AlignText(fmt.Sprintf("Delete Pair '%s'?", p.key), inpW-1, termboxUtil.AlignCenter))
|
||||
}
|
||||
mod.Show()
|
||||
mod.SetText(termboxUtil.AlignText("This cannot be undone!", inpW-1, termboxUtil.AlignCenter))
|
||||
screen.confirmModal = mod
|
||||
screen.mode = modeDelete
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) startFilter() bool {
|
||||
_, _, e := screen.db.getGenericFromPath(screen.currentPath)
|
||||
if e == nil {
|
||||
w, h := termbox.Size()
|
||||
inpW, inpH := (w / 2), 6
|
||||
inpX, inpY := ((w / 2) - (inpW / 2)), ((h / 2) - inpH)
|
||||
mod := termboxUtil.CreateInputModal("", inpX, inpY, inpW, inpH, termbox.ColorWhite, termbox.ColorBlack)
|
||||
mod.SetTitle(termboxUtil.AlignText("Filter", inpW, termboxUtil.AlignCenter))
|
||||
mod.SetValue(screen.filter)
|
||||
mod.Show()
|
||||
screen.inputModal = mod
|
||||
screen.mode = modeFilter
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) startEditItem() bool {
|
||||
_, p, e := screen.db.getGenericFromPath(screen.currentPath)
|
||||
if e == nil {
|
||||
w, h := termbox.Size()
|
||||
inpW, inpH := (w / 2), 6
|
||||
inpX, inpY := ((w / 2) - (inpW / 2)), ((h / 2) - inpH)
|
||||
mod := termboxUtil.CreateInputModal("", inpX, inpY, inpW, inpH, termbox.ColorWhite, termbox.ColorBlack)
|
||||
if p != nil {
|
||||
mod.SetTitle(termboxUtil.AlignText(fmt.Sprintf("Input new value for '%s'", p.key), inpW, termboxUtil.AlignCenter))
|
||||
mod.SetValue(p.val)
|
||||
}
|
||||
mod.Show()
|
||||
screen.inputModal = mod
|
||||
screen.mode = modeChangeVal
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) startRenameItem() bool {
|
||||
b, p, e := screen.db.getGenericFromPath(screen.currentPath)
|
||||
if e == nil {
|
||||
w, h := termbox.Size()
|
||||
inpW, inpH := (w / 2), 6
|
||||
inpX, inpY := ((w / 2) - (inpW / 2)), ((h / 2) - inpH)
|
||||
mod := termboxUtil.CreateInputModal("", inpX, inpY, inpW, inpH, termbox.ColorWhite, termbox.ColorBlack)
|
||||
if b != nil {
|
||||
mod.SetTitle(termboxUtil.AlignText(fmt.Sprintf("Rename Bucket '%s' to:", b.name), inpW, termboxUtil.AlignCenter))
|
||||
mod.SetValue(b.name)
|
||||
} else if p != nil {
|
||||
mod.SetTitle(termboxUtil.AlignText(fmt.Sprintf("Rename Key '%s' to:", p.key), inpW, termboxUtil.AlignCenter))
|
||||
mod.SetValue(p.key)
|
||||
}
|
||||
mod.Show()
|
||||
screen.inputModal = mod
|
||||
screen.mode = modeChangeKey
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) startInsertItemAtParent(tp BoltType) bool {
|
||||
w, h := termbox.Size()
|
||||
inpW, inpH := w-1, 7
|
||||
if w > 80 {
|
||||
inpW, inpH = (w / 2), 7
|
||||
}
|
||||
inpX, inpY := ((w / 2) - (inpW / 2)), ((h / 2) - inpH)
|
||||
mod := termboxUtil.CreateInputModal("", inpX, inpY, inpW, inpH, termbox.ColorWhite, termbox.ColorBlack)
|
||||
screen.inputModal = mod
|
||||
if len(screen.currentPath) <= 0 {
|
||||
// in the root directory
|
||||
if tp == typeBucket {
|
||||
mod.SetTitle(termboxUtil.AlignText("Create Root Bucket", inpW, termboxUtil.AlignCenter))
|
||||
screen.mode = modeInsertBucket | modeModToParent
|
||||
mod.Show()
|
||||
return true
|
||||
}
|
||||
} else {
|
||||
var insPath string
|
||||
_, p, e := screen.db.getGenericFromPath(screen.currentPath[:len(screen.currentPath)-1])
|
||||
if e == nil && p != nil {
|
||||
insPath = strings.Join(screen.currentPath[:len(screen.currentPath)-2], " → ") + " → "
|
||||
} else {
|
||||
insPath = strings.Join(screen.currentPath[:len(screen.currentPath)-1], " → ") + " → "
|
||||
}
|
||||
titlePrfx := ""
|
||||
if tp == typeBucket {
|
||||
titlePrfx = "New Bucket: "
|
||||
} else if tp == typePair {
|
||||
titlePrfx = "New Pair: "
|
||||
}
|
||||
titleText := titlePrfx + insPath
|
||||
if len(titleText) > inpW {
|
||||
truncW := len(titleText) - inpW
|
||||
titleText = titlePrfx + "..." + insPath[truncW+3:]
|
||||
}
|
||||
if tp == typeBucket {
|
||||
mod.SetTitle(termboxUtil.AlignText(titleText, inpW, termboxUtil.AlignCenter))
|
||||
screen.mode = modeInsertBucket | modeModToParent
|
||||
mod.Show()
|
||||
return true
|
||||
} else if tp == typePair {
|
||||
mod.SetTitle(termboxUtil.AlignText(titleText, inpW, termboxUtil.AlignCenter))
|
||||
mod.Show()
|
||||
screen.mode = modeInsertPair | modeModToParent
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) startInsertItem(tp BoltType) bool {
|
||||
w, h := termbox.Size()
|
||||
inpW, inpH := w-1, 7
|
||||
if w > 80 {
|
||||
inpW, inpH = (w / 2), 7
|
||||
}
|
||||
inpX, inpY := ((w / 2) - (inpW / 2)), ((h / 2) - inpH)
|
||||
mod := termboxUtil.CreateInputModal("", inpX, inpY, inpW, inpH, termbox.ColorWhite, termbox.ColorBlack)
|
||||
//mod.SetInputWrap(true)
|
||||
screen.inputModal = mod
|
||||
var insPath string
|
||||
_, p, e := screen.db.getGenericFromPath(screen.currentPath)
|
||||
if e == nil && p != nil {
|
||||
insPath = strings.Join(screen.currentPath[:len(screen.currentPath)-1], " → ") + " → "
|
||||
} else {
|
||||
insPath = strings.Join(screen.currentPath, " → ") + " → "
|
||||
}
|
||||
titlePrfx := ""
|
||||
if tp == typeBucket {
|
||||
titlePrfx = "New Bucket: "
|
||||
} else if tp == typePair {
|
||||
titlePrfx = "New Pair: "
|
||||
}
|
||||
titleText := titlePrfx + insPath
|
||||
if len(titleText) > inpW {
|
||||
truncW := len(titleText) - inpW
|
||||
titleText = titlePrfx + "..." + insPath[truncW+3:]
|
||||
}
|
||||
if tp == typeBucket {
|
||||
mod.SetTitle(termboxUtil.AlignText(titleText, inpW, termboxUtil.AlignCenter))
|
||||
screen.mode = modeInsertBucket
|
||||
mod.Show()
|
||||
return true
|
||||
} else if tp == typePair {
|
||||
mod.SetTitle(termboxUtil.AlignText(titleText, inpW, termboxUtil.AlignCenter))
|
||||
mod.Show()
|
||||
screen.mode = modeInsertPair
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) startExportValue() bool {
|
||||
_, p, e := screen.db.getGenericFromPath(screen.currentPath)
|
||||
if e == nil && p != nil {
|
||||
w, h := termbox.Size()
|
||||
inpW, inpH := (w / 2), 6
|
||||
inpX, inpY := ((w / 2) - (inpW / 2)), ((h / 2) - inpH)
|
||||
mod := termboxUtil.CreateInputModal("", inpX, inpY, inpW, inpH, termbox.ColorWhite, termbox.ColorBlack)
|
||||
mod.SetTitle(termboxUtil.AlignText(fmt.Sprintf("Export value of '%s' to:", p.key), inpW, termboxUtil.AlignCenter))
|
||||
mod.SetValue("")
|
||||
mod.Show()
|
||||
screen.inputModal = mod
|
||||
screen.mode = modeIOExportValue
|
||||
return true
|
||||
}
|
||||
screen.setMessage("Couldn't do string export on " + screen.currentPath[len(screen.currentPath)-1] + "(did you mean 'X'?)")
|
||||
return false
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) startExportJSON() bool {
|
||||
b, p, e := screen.db.getGenericFromPath(screen.currentPath)
|
||||
if e == nil {
|
||||
w, h := termbox.Size()
|
||||
inpW, inpH := (w / 2), 6
|
||||
inpX, inpY := ((w / 2) - (inpW / 2)), ((h / 2) - inpH)
|
||||
mod := termboxUtil.CreateInputModal("", inpX, inpY, inpW, inpH, termbox.ColorWhite, termbox.ColorBlack)
|
||||
if b != nil {
|
||||
mod.SetTitle(termboxUtil.AlignText(fmt.Sprintf("Export JSON of '%s' to:", b.name), inpW, termboxUtil.AlignCenter))
|
||||
mod.SetValue("")
|
||||
} else if p != nil {
|
||||
mod.SetTitle(termboxUtil.AlignText(fmt.Sprintf("Export JSON of '%s' to:", p.key), inpW, termboxUtil.AlignCenter))
|
||||
mod.SetValue("")
|
||||
}
|
||||
mod.Show()
|
||||
screen.inputModal = mod
|
||||
screen.mode = modeIOExportJSON
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) startImportValue() bool {
|
||||
_, p, e := screen.db.getGenericFromPath(screen.currentPath)
|
||||
if e == nil && p != nil {
|
||||
w, h := termbox.Size()
|
||||
inpW, inpH := (w / 2), 6
|
||||
inpX, inpY := ((w / 2) - (inpW / 2)), ((h / 2) - inpH)
|
||||
mod := termboxUtil.CreateInputModal("", inpX, inpY, inpW, inpH, termbox.ColorWhite, termbox.ColorBlack)
|
||||
mod.SetTitle(termboxUtil.AlignText(fmt.Sprintf("Import value of '%s' from:", p.key), inpW, termboxUtil.AlignCenter))
|
||||
mod.SetValue("")
|
||||
mod.Show()
|
||||
screen.inputModal = mod
|
||||
screen.mode = modeIOImportValue
|
||||
return true
|
||||
}
|
||||
screen.setMessage("Couldn't do import on " + screen.currentPath[len(screen.currentPath)-1] + ", must be a pair.")
|
||||
return false
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) setMessage(msg string) {
|
||||
screen.message = msg
|
||||
screen.messageTime = time.Now()
|
||||
screen.messageTimeout = time.Second * 2
|
||||
}
|
||||
|
||||
/* setMessageWithTimeout lets you specify the timeout for the message
|
||||
* setting it to -1 means it won't timeout
|
||||
*/
|
||||
func (screen *BrowserScreen) setMessageWithTimeout(msg string, timeout time.Duration) {
|
||||
screen.message = msg
|
||||
screen.messageTime = time.Now()
|
||||
screen.messageTimeout = timeout
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) clearMessage() {
|
||||
screen.message = ""
|
||||
screen.messageTimeout = -1
|
||||
}
|
||||
|
||||
func (screen *BrowserScreen) refreshDatabase() {
|
||||
shadowDB := screen.db
|
||||
screen.db = screen.db.refreshDatabase()
|
||||
screen.db.syncOpenBuckets(shadowDB)
|
||||
}
|
||||
|
||||
func comparePaths(p1, p2 []string) bool {
|
||||
return strings.Join(p1, " → ") == strings.Join(p2, " → ")
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// stringify ensures that we can print only valid characters.
|
||||
// It's wrong to assume that everything is a string, since BoltDB is typeless.
|
||||
func stringify(v []byte) string {
|
||||
if utf8.Valid(v) {
|
||||
ok := true
|
||||
for _, r := range string(v) {
|
||||
if r < 0x20 {
|
||||
ok = false
|
||||
break
|
||||
} else if r >= 0x7f && r <= 0x9f {
|
||||
ok = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if ok {
|
||||
return string(v)
|
||||
}
|
||||
}
|
||||
if len(v) == 8 {
|
||||
return fmt.Sprintf("%v", binary.BigEndian.Uint64(v))
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%x", v)
|
||||
}
|
||||
|
||||
func stringifyPath(path []string) []string {
|
||||
for k, v := range path {
|
||||
path[k] = stringify([]byte(v))
|
||||
}
|
||||
return path
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package main
|
||||
|
||||
import "github.com/nsf/termbox-go"
|
||||
|
||||
/*
|
||||
Style Defines the colors for the terminal display, basically
|
||||
*/
|
||||
type Style struct {
|
||||
defaultBg termbox.Attribute
|
||||
defaultFg termbox.Attribute
|
||||
titleFg termbox.Attribute
|
||||
titleBg termbox.Attribute
|
||||
cursorFg termbox.Attribute
|
||||
cursorBg termbox.Attribute
|
||||
}
|
||||
|
||||
func defaultStyle() Style {
|
||||
var style Style
|
||||
style.defaultBg = termbox.ColorBlack
|
||||
style.defaultFg = termbox.ColorWhite
|
||||
style.titleFg = termbox.ColorBlack
|
||||
style.titleBg = termbox.ColorGreen
|
||||
style.cursorFg = termbox.ColorBlack
|
||||
style.cursorBg = termbox.ColorGreen
|
||||
|
||||
return style
|
||||
}
|
||||
Reference in New Issue
Block a user