put_command.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package command
  15. import (
  16. "fmt"
  17. "strconv"
  18. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/spf13/cobra"
  19. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  20. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  21. )
  22. var (
  23. leaseStr string
  24. )
  25. // NewPutCommand returns the cobra command for "put".
  26. func NewPutCommand() *cobra.Command {
  27. cmd := &cobra.Command{
  28. Use: "put [options] <key> <value>",
  29. Short: "Put puts the given key into the store.",
  30. Long: `
  31. Put puts the given key into the store.
  32. When <value> begins with '-', <value> is interpreted as a flag.
  33. Insert '--' for workaround:
  34. $ put <key> -- <value>
  35. $ put -- <key> <value>
  36. `,
  37. Run: putCommandFunc,
  38. }
  39. cmd.Flags().StringVar(&leaseStr, "lease", "0", "lease ID attached to the put key")
  40. return cmd
  41. }
  42. // putCommandFunc executes the "put" command.
  43. func putCommandFunc(cmd *cobra.Command, args []string) {
  44. if len(args) != 2 {
  45. ExitWithError(ExitBadArgs, fmt.Errorf("put command needs 2 arguments."))
  46. }
  47. id, err := strconv.ParseInt(leaseStr, 16, 64)
  48. if err != nil {
  49. ExitWithError(ExitBadArgs, fmt.Errorf("bad lease ID arg (%v), expecting ID in Hex", err))
  50. }
  51. key := []byte(args[0])
  52. value := []byte(args[1])
  53. req := &pb.PutRequest{Key: key, Value: value, Lease: id}
  54. mustClient(cmd).KV.Put(context.Background(), req)
  55. fmt.Printf("%s %s\n", key, value)
  56. }