Skip to content

Commit

Permalink
Add the rename command
Browse files Browse the repository at this point in the history
  • Loading branch information
SimFG committed Mar 10, 2023
1 parent ac55f64 commit b8ada99
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 0 deletions.
2 changes: 2 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
build:
go build -o bin/etcdctl+ main.go
Binary file modified bin/etcdctl+
Binary file not shown.
60 changes: 60 additions & 0 deletions cmd/rename_cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package cmd

import (
"errors"
"fmt"

"github.com/SimFG/etcd-analysis/core"
"github.com/spf13/cobra"
)

var (
renameSourceKey = ""
renameTargetKey = ""
renameIsBak = false
)

func NewRenameCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "rename",
Short: "rename the key from all etcd data",
Run: renameFunc,
}

cmd.Flags().StringVar(&renameSourceKey, "source-key", "", "The key of rename data")
cmd.Flags().StringVar(&renameTargetKey, "target-key", "", "The target key of rename data")
cmd.Flags().BoolVar(&renameIsBak, "bak", true, "whether or not back the origin key-value")
return cmd
}

func renameFunc(cmd *cobra.Command, args []string) {
if renameSourceKey == "" {
core.Exit(errors.New("should set the source-key param"))
}
if renameTargetKey == "" {
core.Exit(errors.New("should set the target-key param"))
}
client := core.InitClient()
resp, err := core.EtcdGet(client, renameSourceKey)
if err != nil {
core.Exit(err)
}
if len(resp.Kvs) == 0 {
core.Exit(errors.New("not found the key"))
}
if renameIsBak {
err = core.EtcdPut(client, "etcd-bak/"+renameSourceKey, string(resp.Kvs[0].Value))
if err != nil {
core.Exit(err)
}
}
err = core.EtcdPut(client, renameTargetKey, string(resp.Kvs[0].Value))
if err != nil {
core.Exit(err)
}
err = core.EtcdDelete(client, renameSourceKey)
if err != nil {
core.Exit(err)
}
fmt.Println("success rename the key, the bak data:" + "etcd-bak/" + renameSourceKey)
}
1 change: 1 addition & 0 deletions cmd/root_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,6 @@ func init() {
rootCmd.AddCommand(NewClearCmd())
rootCmd.AddCommand(NewFindCmd())
rootCmd.AddCommand(NewDecodeCmd())
rootCmd.AddCommand(NewRenameCmd())
rootCmd.AddCommand(cobracompletefig.CreateCompletionSpecCommand())
}

0 comments on commit b8ada99

Please sign in to comment.