set_command.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package command
  14. import (
  15. "errors"
  16. "os"
  17. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/codegangsta/cli"
  18. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd"
  19. )
  20. // NewSetCommand returns the CLI command for "set".
  21. func NewSetCommand() cli.Command {
  22. return cli.Command{
  23. Name: "set",
  24. Usage: "set the value of a key",
  25. Flags: []cli.Flag{
  26. cli.IntFlag{Name: "ttl", Value: 0, Usage: "key time-to-live"},
  27. cli.StringFlag{Name: "swap-with-value", Value: "", Usage: "previous value"},
  28. cli.IntFlag{Name: "swap-with-index", Value: 0, Usage: "previous index"},
  29. },
  30. Action: func(c *cli.Context) {
  31. handleKey(c, setCommandFunc)
  32. },
  33. }
  34. }
  35. // setCommandFunc executes the "set" command.
  36. func setCommandFunc(c *cli.Context, client *etcd.Client) (*etcd.Response, error) {
  37. if len(c.Args()) == 0 {
  38. return nil, errors.New("Key required")
  39. }
  40. key := c.Args()[0]
  41. value, err := argOrStdin(c.Args(), os.Stdin, 1)
  42. if err != nil {
  43. return nil, errors.New("Value required")
  44. }
  45. ttl := c.Int("ttl")
  46. prevValue := c.String("swap-with-value")
  47. prevIndex := c.Int("swap-with-index")
  48. if prevValue == "" && prevIndex == 0 {
  49. return client.Set(key, value, uint64(ttl))
  50. } else {
  51. return client.CompareAndSwap(key, value, uint64(ttl), prevValue, uint64(prevIndex))
  52. }
  53. }