ls_command.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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: "sort", Usage: "returns result in sorted order"},
  13. cli.BoolFlag{Name: "recursive", Usage: "returns all values for key and child keys"},
  14. cli.BoolFlag{Name: "p", Usage: "append slash (/) to directories"},
  15. },
  16. Action: func(c *cli.Context) {
  17. handleLs(c, lsCommandFunc)
  18. },
  19. }
  20. }
  21. // handleLs handles a request that intends to do ls-like operations.
  22. func handleLs(c *cli.Context, fn handlerFunc) {
  23. handleContextualPrint(c, fn, printLs)
  24. }
  25. // printLs writes a response out in a manner similar to the `ls` command in unix.
  26. // Non-empty directories list their contents and files list their name.
  27. func printLs(c *cli.Context, resp *etcd.Response, format string) {
  28. if !resp.Node.Dir {
  29. fmt.Println(resp.Node.Key)
  30. }
  31. for _, node := range resp.Node.Nodes {
  32. rPrint(c, node)
  33. }
  34. }
  35. // lsCommandFunc executes the "ls" command.
  36. func lsCommandFunc(c *cli.Context, client *etcd.Client) (*etcd.Response, error) {
  37. key := "/"
  38. if len(c.Args()) != 0 {
  39. key = c.Args()[0]
  40. }
  41. recursive := c.Bool("recursive")
  42. sort := c.Bool("sort")
  43. // Retrieve the value from the server.
  44. return client.Get(key, sort, recursive)
  45. }
  46. // rPrint recursively prints out the nodes in the node structure.
  47. func rPrint(c *cli.Context, n *etcd.Node) {
  48. if n.Dir && c.Bool("p") {
  49. fmt.Println(fmt.Sprintf("%v/", n.Key))
  50. } else {
  51. fmt.Println(n.Key)
  52. }
  53. for _, node := range n.Nodes {
  54. rPrint(c, node)
  55. }
  56. }