ls_command.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package command
  2. import (
  3. "fmt"
  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. func NewLsCommand() cli.Command {
  8. return cli.Command{
  9. Name: "ls",
  10. Usage: "retrieve a directory",
  11. Flags: []cli.Flag{
  12. cli.BoolFlag{Name: "recursive", Usage: "returns all values for key and child keys"},
  13. },
  14. Action: func(c *cli.Context) {
  15. handleLs(c, lsCommandFunc)
  16. },
  17. }
  18. }
  19. // handleLs handles a request that intends to do ls-like operations.
  20. func handleLs(c *cli.Context, fn handlerFunc) {
  21. handlePrint(c, fn, printLs)
  22. }
  23. // printLs writes a response out in a manner similar to the `ls` command in unix.
  24. // Non-empty directories list their contents and files list their name.
  25. func printLs(resp *etcd.Response, format string) {
  26. if !resp.Node.Dir {
  27. fmt.Println(resp.Node.Key)
  28. }
  29. for _, node := range resp.Node.Nodes {
  30. rPrint(node)
  31. }
  32. }
  33. // lsCommandFunc executes the "ls" command.
  34. func lsCommandFunc(c *cli.Context, client *etcd.Client) (*etcd.Response, error) {
  35. key := "/"
  36. if len(c.Args()) != 0 {
  37. key = c.Args()[0]
  38. }
  39. recursive := c.Bool("recursive")
  40. // Retrieve the value from the server.
  41. return client.Get(key, false, recursive)
  42. }
  43. // rPrint recursively prints out the nodes in the node structure.
  44. func rPrint(n *etcd.Node) {
  45. fmt.Println(n.Key)
  46. for _, node := range n.Nodes {
  47. rPrint(node)
  48. }
  49. }