From 075f5f68ad8ed07f45fd4fca88cd9935c38cdf1e Mon Sep 17 00:00:00 2001 From: Hitoshi Mitake Date: Mon, 8 Feb 2016 17:19:52 +0900 Subject: [PATCH] etcdctlv3: support reading value from stdin This commit lets etcdctlv3 support reading value from stdin like `etcdctl set`. It is convenient for storing complex, long value. --- etcdctlv3/command/global.go | 13 +++++++++++++ etcdctlv3/command/put_command.go | 17 +++++++++++------ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/etcdctlv3/command/global.go b/etcdctlv3/command/global.go index 16d35ab95..39c3dfaa1 100644 --- a/etcdctlv3/command/global.go +++ b/etcdctlv3/command/global.go @@ -16,6 +16,8 @@ package command import ( "errors" + "io" + "io/ioutil" "time" "github.com/coreos/etcd/Godeps/_workspace/src/github.com/spf13/cobra" @@ -73,3 +75,14 @@ func mustClient(cmd *cobra.Command) *clientv3.Client { } return client } + +func argOrStdin(args []string, stdin io.Reader, i int) ([]byte, error) { + if i < len(args) { + return []byte(args[i]), nil + } + bytes, err := ioutil.ReadAll(stdin) + if string(bytes) == "" || err != nil { + return nil, errors.New("no available argument and stdin") + } + return bytes, nil +} diff --git a/etcdctlv3/command/put_command.go b/etcdctlv3/command/put_command.go index 327ead24d..36d92a562 100644 --- a/etcdctlv3/command/put_command.go +++ b/etcdctlv3/command/put_command.go @@ -16,6 +16,7 @@ package command import ( "fmt" + "os" "strconv" "github.com/coreos/etcd/Godeps/_workspace/src/github.com/spf13/cobra" @@ -30,7 +31,7 @@ var ( // NewPutCommand returns the cobra command for "put". func NewPutCommand() *cobra.Command { cmd := &cobra.Command{ - Use: "put [options] ", + Use: "put [options] ( can also be given from stdin)", Short: "Put puts the given key into the store.", Long: ` Put puts the given key into the store. @@ -40,6 +41,11 @@ Insert '--' for workaround: $ put -- $ put -- + +If isn't given, this command tries to read the value from standard input. +For example, +$ cat file | put +will store the content of the file to . `, Run: putCommandFunc, } @@ -49,8 +55,10 @@ $ put -- // putCommandFunc executes the "put" command. func putCommandFunc(cmd *cobra.Command, args []string) { - if len(args) != 2 { - ExitWithError(ExitBadArgs, fmt.Errorf("put command needs 2 arguments.")) + key := []byte(args[0]) + value, err := argOrStdin(args, os.Stdin, 1) + if err != nil { + ExitWithError(ExitBadArgs, fmt.Errorf("put command needs 1 argument and input from stdin or 2 arguments.")) } id, err := strconv.ParseInt(leaseStr, 16, 64) @@ -58,9 +66,6 @@ func putCommandFunc(cmd *cobra.Command, args []string) { ExitWithError(ExitBadArgs, fmt.Errorf("bad lease ID arg (%v), expecting ID in Hex", err)) } - key := []byte(args[0]) - value := []byte(args[1]) - req := &pb.PutRequest{Key: key, Value: value, Lease: id} mustClient(cmd).KV.Put(context.Background(), req) fmt.Printf("%s %s\n", key, value)