get_command.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package command
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/codegangsta/cli"
  7. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd"
  8. )
  9. // NewGetCommand returns the CLI command for "get".
  10. func NewGetCommand() cli.Command {
  11. return cli.Command{
  12. Name: "get",
  13. Usage: "retrieve the value of a key",
  14. Flags: []cli.Flag{
  15. cli.BoolFlag{Name: "sort", Usage: "returns result in sorted order"},
  16. cli.BoolFlag{Name: "consistent", Usage: "send request to the leader, thereby guranteeing that any earlier writes will be seen by the read"},
  17. },
  18. Action: func(c *cli.Context) {
  19. handleGet(c, getCommandFunc)
  20. },
  21. }
  22. }
  23. // handleGet handles a request that intends to do get-like operations.
  24. func handleGet(c *cli.Context, fn handlerFunc) {
  25. handlePrint(c, fn, printGet)
  26. }
  27. // printGet writes error message when getting the value of a directory.
  28. func printGet(resp *etcd.Response, format string) {
  29. if resp.Node.Dir {
  30. fmt.Fprintln(os.Stderr, fmt.Sprintf("%s: is a directory", resp.Node.Key))
  31. os.Exit(1)
  32. }
  33. printKey(resp, format)
  34. }
  35. // getCommandFunc executes the "get" command.
  36. func getCommandFunc(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. consistent := c.Bool("consistent")
  42. sorted := c.Bool("sort")
  43. // Setup consistency on the client.
  44. if consistent {
  45. client.SetConsistency(etcd.STRONG_CONSISTENCY)
  46. } else {
  47. client.SetConsistency(etcd.WEAK_CONSISTENCY)
  48. }
  49. // Retrieve the value from the server.
  50. return client.Get(key, sorted, false)
  51. }