ls_command.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. "errors"
  17. "fmt"
  18. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/codegangsta/cli"
  19. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  20. "github.com/coreos/etcd/client"
  21. )
  22. func NewLsCommand() cli.Command {
  23. return cli.Command{
  24. Name: "ls",
  25. Usage: "retrieve a directory",
  26. Flags: []cli.Flag{
  27. cli.BoolFlag{Name: "sort", Usage: "returns result in sorted order"},
  28. cli.BoolFlag{Name: "recursive", Usage: "returns all key names recursively for the given path"},
  29. cli.BoolFlag{Name: "p", Usage: "append slash (/) to directories"},
  30. },
  31. Action: func(c *cli.Context) {
  32. lsCommandFunc(c, mustNewKeyAPI(c))
  33. },
  34. }
  35. }
  36. // lsCommandFunc executes the "ls" command.
  37. func lsCommandFunc(c *cli.Context, ki client.KeysAPI) {
  38. if len(c.Args()) == 0 {
  39. handleError(ExitBadArgs, errors.New("key required"))
  40. }
  41. key := c.Args()[0]
  42. sort := c.Bool("sort")
  43. recursive := c.Bool("recursive")
  44. // TODO: handle transport timeout
  45. resp, err := ki.Get(context.TODO(), key, &client.GetOptions{Sort: sort, Recursive: recursive})
  46. if err != nil {
  47. handleError(ExitServerError, err)
  48. }
  49. printLs(c, resp)
  50. }
  51. // printLs writes a response out in a manner similar to the `ls` command in unix.
  52. // Non-empty directories list their contents and files list their name.
  53. func printLs(c *cli.Context, resp *client.Response) {
  54. if !resp.Node.Dir {
  55. fmt.Println(resp.Node.Key)
  56. }
  57. for _, node := range resp.Node.Nodes {
  58. rPrint(c, node)
  59. }
  60. }
  61. // rPrint recursively prints out the nodes in the node structure.
  62. func rPrint(c *cli.Context, n *client.Node) {
  63. if n.Dir && c.Bool("p") {
  64. fmt.Println(fmt.Sprintf("%v/", n.Key))
  65. } else {
  66. fmt.Println(n.Key)
  67. }
  68. for _, node := range n.Nodes {
  69. rPrint(c, node)
  70. }
  71. }