printer_protobuf.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright 2016 The etcd Authors
  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. "os"
  18. v3 "go.etcd.io/etcd/clientv3"
  19. pb "go.etcd.io/etcd/etcdserver/etcdserverpb"
  20. mvccpb "go.etcd.io/etcd/mvcc/mvccpb"
  21. )
  22. type pbPrinter struct{ printer }
  23. type pbMarshal interface {
  24. Marshal() ([]byte, error)
  25. }
  26. func newPBPrinter() printer {
  27. return &pbPrinter{
  28. &printerRPC{newPrinterUnsupported("protobuf"), printPB},
  29. }
  30. }
  31. func (p *pbPrinter) Watch(r v3.WatchResponse) {
  32. evs := make([]*mvccpb.Event, len(r.Events))
  33. for i, ev := range r.Events {
  34. evs[i] = (*mvccpb.Event)(ev)
  35. }
  36. wr := pb.WatchResponse{
  37. Header: &r.Header,
  38. Events: evs,
  39. CompactRevision: r.CompactRevision,
  40. Canceled: r.Canceled,
  41. Created: r.Created,
  42. }
  43. printPB(&wr)
  44. }
  45. func printPB(v interface{}) {
  46. m, ok := v.(pbMarshal)
  47. if !ok {
  48. ExitWithError(ExitBadFeature, fmt.Errorf("marshal unsupported for type %T (%v)", v, v))
  49. }
  50. b, err := m.Marshal()
  51. if err != nil {
  52. fmt.Fprintf(os.Stderr, "%v\n", err)
  53. return
  54. }
  55. fmt.Print(string(b))
  56. }