ls_command.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. },
  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. handlePrint(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(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(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. sort := c.Bool("sort")
  42. // Retrieve the value from the server.
  43. return client.Get(key, sort, recursive)
  44. }
  45. // rPrint recursively prints out the nodes in the node structure.
  46. func rPrint(n *etcd.Node) {
  47. fmt.Println(n.Key)
  48. for _, node := range n.Nodes {
  49. rPrint(node)
  50. }
  51. }