bitcask-mirror/cmd/bitcask/put.go

66 lines
1.2 KiB
Go
Raw Permalink Normal View History

2019-03-09 12:41:59 +00:00
package main
import (
"bytes"
"io"
"io/ioutil"
"os"
2022-01-21 11:35:03 +00:00
log "github.com/rs/zerolog/log"
2019-03-09 12:41:59 +00:00
"github.com/spf13/cobra"
"github.com/spf13/viper"
2021-12-31 15:09:31 +00:00
"git.tcp.direct/Mirrors/bitcask-mirror"
2019-03-09 12:41:59 +00:00
)
var putCmd = &cobra.Command{
Use: "put <key> [<value>]",
Aliases: []string{"add", "set", "store"},
Short: "Adds a new Key/Value pair",
Long: `This adds a new key/value pair or modifies an existing one.
2019-03-09 12:41:59 +00:00
If the value is not specified as an argument it is read from standard input.`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
path := viper.GetString("path")
key := args[0]
var value io.Reader
if len(args) > 1 {
value = bytes.NewBufferString(args[1])
} else {
value = os.Stdin
}
os.Exit(put(path, key, value))
2019-03-09 12:41:59 +00:00
},
}
func init() {
RootCmd.AddCommand(putCmd)
2019-03-09 12:41:59 +00:00
}
func put(path, key string, value io.Reader) int {
2019-03-09 12:41:59 +00:00
db, err := bitcask.Open(path)
if err != nil {
2022-01-21 11:35:03 +00:00
log.Error().Err(err).Msg("error opening database")
2019-03-09 12:41:59 +00:00
return 1
}
2019-03-14 11:50:41 +00:00
defer db.Close()
2019-03-09 12:41:59 +00:00
data, err := ioutil.ReadAll(value)
if err != nil {
2022-01-21 11:35:03 +00:00
log.Error().Err(err).Msg("error writing key")
2019-03-09 12:41:59 +00:00
return 1
}
err = db.Put([]byte(key), data)
2019-03-09 12:41:59 +00:00
if err != nil {
2022-01-21 11:35:03 +00:00
log.Error().Err(err).Msg("error writing key")
2019-03-09 12:41:59 +00:00
return 1
}
return 0
}