ls_command.go 2.3 KB

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