feat(cmd): added flag for displaying binary data in tty, and cleaned up some old code

This commit is contained in:
Lewis Wynne 2025-11-06 22:30:50 +00:00
parent 63ade13e7a
commit 990ff7ce40
4 changed files with 29 additions and 23 deletions

View file

@ -56,10 +56,16 @@ func get(cmd *cobra.Command, args []string) error {
return err
}
store.Print("%s", v)
binary, err := cmd.Flags().GetBool("include-binary")
if err != nil {
return err
}
store.Print("%s", binary, v)
return nil
}
func init() {
getCmd.Flags().BoolP("include-binary", "b", false, "include binary data in text output")
rootCmd.AddCommand(getCmd)
}

View file

@ -22,9 +22,6 @@ THE SOFTWARE.
package cmd
import (
"fmt"
"strconv"
"github.com/dgraph-io/badger/v4"
"github.com/spf13/cobra"
)
@ -39,31 +36,29 @@ var listCmd = &cobra.Command{
func list(cmd *cobra.Command, args []string) error {
store := &Store{}
var pf string
var err error
pf, err = strconv.Unquote(fmt.Sprintf(`"%%s%s%%s\n"`, "\t\t"))
if err != nil {
return err
}
if len(args) == 0 {
args = append(args, "@default")
targetDB := "@default"
if len(args) == 1 {
targetDB = args[0]
}
trans := TransactionArgs{
key: args[0],
key: targetDB,
readonly: true,
sync: true,
transact: func(tx *badger.Txn, k []byte) error {
binary, err := cmd.Flags().GetBool("include-binary")
if err != nil {
return err
}
opts := badger.DefaultIteratorOptions
opts.PrefetchSize = 10
it := tx.NewIterator(opts)
defer it.Close()
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
k := item.Key()
key := item.Key()
if err := item.Value(func(v []byte) error {
store.Print(pf, k, v)
store.Print("%s\t\t%s\n", binary, key, v)
return nil
}); err != nil {
return err
@ -77,5 +72,6 @@ func list(cmd *cobra.Command, args []string) error {
}
func init() {
listCmd.Flags().BoolP("include-binary", "b", false, "include binary data in text output")
rootCmd.AddCommand(listCmd)
}

View file

@ -65,4 +65,3 @@ func set(cmd *cobra.Command, args []string) error {
func init() {
rootCmd.AddCommand(setCmd)
}

View file

@ -23,7 +23,6 @@ package cmd
import (
"fmt"
"math"
"os"
"path/filepath"
"strings"
@ -75,19 +74,25 @@ func (s *Store) Transaction(args TransactionArgs) error {
}
tx := db.NewTransaction(!args.readonly)
defer tx.Discard()
if err := args.transact(tx, k); err != nil {
tx.Discard()
return err
}
if args.readonly {
return nil
}
return tx.Commit()
}
func (s *Store) Print(pf string, vs ...[]byte) {
func (s *Store) Print(pf string, includeBinary bool, vs ...[]byte) {
nb := "(omitted binary data)"
fvs := make([]any, 0)
tty := term.IsTerminal(int(os.Stdin.Fd()))
fvs := make([]any, 0, len(vs))
tty := term.IsTerminal(int(os.Stdout.Fd()))
for _, v := range vs {
if tty && !utf8.Valid(v) {
if tty && !includeBinary && !utf8.Valid(v) {
fvs = append(fvs, nb)
} else {
fvs = append(fvs, string(v))