go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/logdog/client/butlerlib/streamproto/tag.go (about)

     1  // Copyright 2015 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 streamproto
    16  
    17  import (
    18  	"encoding/json"
    19  	"flag"
    20  	"sort"
    21  
    22  	"go.chromium.org/luci/common/flag/stringmapflag"
    23  	"go.chromium.org/luci/logdog/common/types"
    24  )
    25  
    26  // TagMap is a flags-compatible map used to store stream tags.
    27  type TagMap stringmapflag.Value
    28  
    29  var _ interface {
    30  	json.Marshaler
    31  	json.Unmarshaler
    32  	flag.Value
    33  } = (*TagMap)(nil)
    34  
    35  // String implements flag.Value.
    36  func (t *TagMap) String() string {
    37  	return (*stringmapflag.Value)(t).String()
    38  }
    39  
    40  // Set implements flag.Value
    41  func (t *TagMap) Set(key string) error {
    42  	return (*stringmapflag.Value)(t).Set(key)
    43  }
    44  
    45  // SortedKeys returns a sorted slice of the keys in a TagMap.
    46  func (t TagMap) SortedKeys() []string {
    47  	if len(t) == 0 {
    48  		return nil
    49  	}
    50  
    51  	keys := make([]string, 0, len(t))
    52  	for k := range t {
    53  		keys = append(keys, k)
    54  	}
    55  	sort.Strings(keys)
    56  	return keys
    57  }
    58  
    59  // MarshalJSON implements the json.Marshaler interface.
    60  func (t *TagMap) MarshalJSON() ([]byte, error) {
    61  	m := make(map[string]string, len(*t))
    62  	if len(*t) > 0 {
    63  		for k, v := range *t {
    64  			m[k] = v
    65  		}
    66  	}
    67  	return json.Marshal(m)
    68  }
    69  
    70  // UnmarshalJSON implements the json.Unmarshaler interface.
    71  func (t *TagMap) UnmarshalJSON(data []byte) error {
    72  	m := map[string]string{}
    73  	if err := json.Unmarshal(data, &m); err != nil {
    74  		return err
    75  	}
    76  
    77  	if len(m) == 0 {
    78  		*t = nil
    79  		return nil
    80  	}
    81  
    82  	tm := make(TagMap, len(m))
    83  	for k, v := range m {
    84  		if err := types.ValidateTag(k, v); err != nil {
    85  			return err
    86  		}
    87  		tm[k] = v
    88  	}
    89  
    90  	*t = tm
    91  	return nil
    92  }