ls_command.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package command
  15. import (
  16. "fmt"
  17. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/codegangsta/cli"
  18. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  19. "github.com/coreos/etcd/client"
  20. )
  21. func NewLsCommand() cli.Command {
  22. return cli.Command{
  23. Name: "ls",
  24. Usage: "retrieve a directory",
  25. Flags: []cli.Flag{
  26. cli.BoolFlag{Name: "sort", Usage: "returns result in sorted order"},
  27. cli.BoolFlag{Name: "recursive", Usage: "returns all key names recursively for the given path"},
  28. cli.BoolFlag{Name: "p", Usage: "append slash (/) to directories"},
  29. },
  30. Action: func(c *cli.Context) {
  31. lsCommandFunc(c, mustNewKeyAPI(c))
  32. },
  33. }
  34. }
  35. // lsCommandFunc executes the "ls" command.
  36. func lsCommandFunc(c *cli.Context, ki client.KeysAPI) {
  37. key := "/"
  38. if len(c.Args()) != 0 {
  39. key = c.Args()[0]
  40. }
  41. sort := c.Bool("sort")
  42. recursive := c.Bool("recursive")
  43. // TODO: handle transport timeout
  44. resp, err := ki.Get(context.TODO(), key, &client.GetOptions{Sort: sort, Recursive: recursive})
  45. if err != nil {
  46. handleError(ExitServerError, err)
  47. }
  48. printLs(c, resp)
  49. }
  50. // printLs writes a response out in a manner similar to the `ls` command in unix.
  51. // Non-empty directories list their contents and files list their name.
  52. func printLs(c *cli.Context, resp *client.Response) {
  53. if !resp.Node.Dir {
  54. fmt.Println(resp.Node.Key)
  55. }
  56. for _, node := range resp.Node.Nodes {
  57. rPrint(c, node)
  58. }
  59. }
  60. // rPrint recursively prints out the nodes in the node structure.
  61. func rPrint(c *cli.Context, n *client.Node) {
  62. if n.Dir && c.Bool("p") {
  63. fmt.Println(fmt.Sprintf("%v/", n.Key))
  64. } else {
  65. fmt.Println(n.Key)
  66. }
  67. for _, node := range n.Nodes {
  68. rPrint(c, node)
  69. }
  70. }