ls_command.go 1.6 KB

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