format.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. "encoding/json"
  17. "fmt"
  18. "os"
  19. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd"
  20. )
  21. // printKey writes the etcd response to STDOUT in the given format.
  22. func printKey(resp *etcd.Response, format string) {
  23. // printKey is only for keys, error on directories
  24. if resp.Node.Dir == true {
  25. fmt.Fprintln(os.Stderr, fmt.Sprintf("Cannot print key [%s: Is a directory]", resp.Node.Key))
  26. os.Exit(1)
  27. }
  28. printKeyOnly(resp, format)
  29. }
  30. // printAll prints the etcd response in the given format in its best efforts.
  31. func printAll(resp *etcd.Response, format string) {
  32. if resp.Node.Dir == true {
  33. return
  34. }
  35. printKeyOnly(resp, format)
  36. }
  37. // printKeyOnly only supports to print key correctly.
  38. func printKeyOnly(resp *etcd.Response, format string) {
  39. // Format the result.
  40. switch format {
  41. case "simple":
  42. fmt.Println(resp.Node.Value)
  43. case "extended":
  44. // Extended prints in a rfc2822 style format
  45. fmt.Println("Key:", resp.Node.Key)
  46. fmt.Println("Created-Index:", resp.Node.CreatedIndex)
  47. fmt.Println("Modified-Index:", resp.Node.ModifiedIndex)
  48. if resp.PrevNode != nil {
  49. fmt.Println("PrevNode.Value:", resp.PrevNode.Value)
  50. }
  51. fmt.Println("TTL:", resp.Node.TTL)
  52. fmt.Println("Etcd-Index:", resp.EtcdIndex)
  53. fmt.Println("Raft-Index:", resp.RaftIndex)
  54. fmt.Println("Raft-Term:", resp.RaftTerm)
  55. fmt.Println("")
  56. fmt.Println(resp.Node.Value)
  57. case "json":
  58. b, err := json.Marshal(resp)
  59. if err != nil {
  60. panic(err)
  61. }
  62. fmt.Println(string(b))
  63. default:
  64. fmt.Fprintln(os.Stderr, "Unsupported output format:", format)
  65. }
  66. }