set_command.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package command
  2. import (
  3. "errors"
  4. "os"
  5. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/codegangsta/cli"
  6. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd"
  7. )
  8. // NewSetCommand returns the CLI command for "set".
  9. func NewSetCommand() cli.Command {
  10. return cli.Command{
  11. Name: "set",
  12. Usage: "set the value of a key",
  13. Flags: []cli.Flag{
  14. cli.IntFlag{Name: "ttl", Value: 0, Usage: "key time-to-live"},
  15. cli.StringFlag{Name: "swap-with-value", Value: "", Usage: "previous value"},
  16. cli.IntFlag{Name: "swap-with-index", Value: 0, Usage: "previous index"},
  17. },
  18. Action: func(c *cli.Context) {
  19. handleKey(c, setCommandFunc)
  20. },
  21. }
  22. }
  23. // setCommandFunc executes the "set" command.
  24. func setCommandFunc(c *cli.Context, client *etcd.Client) (*etcd.Response, error) {
  25. if len(c.Args()) == 0 {
  26. return nil, errors.New("Key required")
  27. }
  28. key := c.Args()[0]
  29. value, err := argOrStdin(c.Args(), os.Stdin, 1)
  30. if err != nil {
  31. return nil, errors.New("Value required")
  32. }
  33. ttl := c.Int("ttl")
  34. prevValue := c.String("swap-with-value")
  35. prevIndex := c.Int("swap-with-index")
  36. if prevValue == "" && prevIndex == 0 {
  37. return client.Set(key, value, uint64(ttl))
  38. } else {
  39. return client.CompareAndSwap(key, value, uint64(ttl), prevValue, uint64(prevIndex))
  40. }
  41. }