rm_command.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/codegangsta/cli"
  17. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd"
  18. )
  19. // NewRemoveCommand returns the CLI command for "rm".
  20. func NewRemoveCommand() cli.Command {
  21. return cli.Command{
  22. Name: "rm",
  23. Usage: "remove a key",
  24. Flags: []cli.Flag{
  25. cli.BoolFlag{Name: "dir", Usage: "removes the key if it is an empty directory or a key-value pair"},
  26. cli.BoolFlag{Name: "recursive", Usage: "removes the key and all child keys(if it is a directory)"},
  27. cli.StringFlag{Name: "with-value", Value: "", Usage: "previous value"},
  28. cli.IntFlag{Name: "with-index", Value: 0, Usage: "previous index"},
  29. },
  30. Action: func(c *cli.Context) {
  31. handleAll(c, removeCommandFunc)
  32. },
  33. }
  34. }
  35. // removeCommandFunc executes the "rm" command.
  36. func removeCommandFunc(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. recursive := c.Bool("recursive")
  42. dir := c.Bool("dir")
  43. // TODO: distinguish with flag is not set and empty flag
  44. // the cli pkg need to provide this feature
  45. prevValue := c.String("with-value")
  46. prevIndex := uint64(c.Int("with-index"))
  47. if prevValue != "" || prevIndex != 0 {
  48. return client.CompareAndDelete(key, prevValue, prevIndex)
  49. }
  50. if recursive || !dir {
  51. return client.Delete(key, recursive)
  52. }
  53. return client.DeleteDir(key)
  54. }