go.etcd.io/etcd@v3.3.27+incompatible/etcdctl/ctlv3/command/printer_protobuf.go (about)

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