瀏覽代碼

Merge pull request #4450 from mitake/v3-put-stdin

etcdctlv3: support reading value from stdin
Anthony Romano 10 年之前
父節點
當前提交
4698e7e23b
共有 2 個文件被更改,包括 24 次插入6 次删除
  1. 13 0
      etcdctlv3/command/global.go
  2. 11 6
      etcdctlv3/command/put_command.go

+ 13 - 0
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
+}

+ 11 - 6
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] <key> <value>",
+		Use:   "put [options] <key> <value> (<value> 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 <key> -- <value>
 $ put -- <key> <value>
+
+If <value> isn't given, this command tries to read the value from standard input.
+For example,
+$ cat file | put <key>
+will store the content of the file to <key>.
 `,
 		Run: putCommandFunc,
 	}
@@ -49,8 +55,10 @@ $ put -- <key> <value>
 
 // 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)