go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/flag/meta.go (about)

     1  // Copyright 2019 The LUCI 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 flag
    16  
    17  import (
    18  	"flag"
    19  	"fmt"
    20  	"sort"
    21  	"strings"
    22  
    23  	"google.golang.org/grpc/metadata"
    24  )
    25  
    26  // metadataFlag implements the flag.Getter returned by GRPCMetadata.
    27  type grpcMetadataFlag metadata.MD
    28  
    29  // GRPCMetadata returns a flag.Getter for parsing gRPC metadata from a
    30  // a set of colon-separated strings.
    31  // Example: -f a:1 -f a:2 -f b:3
    32  // Panics if md is nil.
    33  func GRPCMetadata(md metadata.MD) flag.Getter {
    34  	if md == nil {
    35  		panic("md is nil")
    36  	}
    37  	return grpcMetadataFlag(md)
    38  }
    39  
    40  // String implements the flag.Value interface.
    41  func (f grpcMetadataFlag) String() string {
    42  	pairs := make([]string, 0, len(f))
    43  	for k, vs := range f {
    44  		for _, v := range vs {
    45  			pairs = append(pairs, fmt.Sprintf("%s:%s", k, v))
    46  		}
    47  	}
    48  	sort.Strings(pairs)
    49  	return strings.Join(pairs, ", ")
    50  }
    51  
    52  // Set implements the flag.Value interface.
    53  func (f grpcMetadataFlag) Set(s string) error {
    54  	parts := strings.Split(s, ":")
    55  	if len(parts) == 1 {
    56  		return fmt.Errorf("no colon")
    57  	}
    58  	metadata.MD(f).Append(parts[0], parts[1])
    59  	return nil
    60  }
    61  
    62  // Get retrieves the flag value.
    63  func (f grpcMetadataFlag) Get() any {
    64  	return metadata.MD(f)
    65  }