rm_command.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package command
  2. import (
  3. "errors"
  4. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/codegangsta/cli"
  5. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd"
  6. )
  7. // NewRemoveCommand returns the CLI command for "rm".
  8. func NewRemoveCommand() cli.Command {
  9. return cli.Command{
  10. Name: "rm",
  11. Usage: "remove a key",
  12. Flags: []cli.Flag{
  13. cli.BoolFlag{Name: "dir", Usage: "removes the key if it is an empty directory or a key-value pair"},
  14. cli.BoolFlag{Name: "recursive", Usage: "removes the key and all child keys(if it is a directory)"},
  15. cli.StringFlag{Name: "with-value", Value: "", Usage: "previous value"},
  16. cli.IntFlag{Name: "with-index", Value: 0, Usage: "previous index"},
  17. },
  18. Action: func(c *cli.Context) {
  19. handleAll(c, removeCommandFunc)
  20. },
  21. }
  22. }
  23. // removeCommandFunc executes the "rm" command.
  24. func removeCommandFunc(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. recursive := c.Bool("recursive")
  30. dir := c.Bool("dir")
  31. // TODO: distinguish with flag is not set and empty flag
  32. // the cli pkg need to provide this feature
  33. prevValue := c.String("with-value")
  34. prevIndex := uint64(c.Int("with-index"))
  35. if prevValue != "" || prevIndex != 0 {
  36. return client.CompareAndDelete(key, prevValue, prevIndex)
  37. }
  38. if recursive || !dir {
  39. return client.Delete(key, recursive)
  40. }
  41. return client.DeleteDir(key)
  42. }