github.com/grafana/synthetic-monitoring-agent@v0.64.2/internal/feature/feature.go (about)

     1  // The feature package provides types and methods for working with
     2  // feature flags.
     3  package feature
     4  
     5  import (
     6  	"errors"
     7  	"sort"
     8  	"strings"
     9  )
    10  
    11  // TODO: this doesn't seem like the right place for this
    12  const (
    13  	Traceroute            = "traceroute"
    14  	K6                    = "k6"
    15  	ExperimentalDnsProber = "experimental-dns-prober"
    16  	ProtocolSecrets       = "protocol-secrets"
    17  )
    18  
    19  // ErrInvalidCollection is returned when you try to set a flag in an
    20  // invalid collection.
    21  var ErrInvalidCollection = errors.New("invalid feature collection")
    22  
    23  // Collection represents a set of feature flags.
    24  type Collection map[string]struct{}
    25  
    26  // NewCollection returns a correctly initialized Collection.
    27  func NewCollection() Collection {
    28  	return make(Collection)
    29  }
    30  
    31  // Set adds the value specified by s to the collection.
    32  //
    33  // The input s can be a single feature flag or multiple feature flags
    34  // separated by commas.
    35  func (c Collection) Set(s string) error {
    36  	if c == nil {
    37  		return ErrInvalidCollection
    38  	}
    39  
    40  	for elem := range strings.SplitSeq(s, ",") {
    41  		feature := strings.TrimSpace(elem)
    42  		if feature == "" {
    43  			continue
    44  		}
    45  
    46  		c[feature] = struct{}{}
    47  	}
    48  
    49  	return nil
    50  }
    51  
    52  // String returns an string representation of the collection.
    53  //
    54  // The returned value can be passed to Set to recreate an identical
    55  // collection.
    56  func (c Collection) String() string {
    57  	if c == nil {
    58  		return ""
    59  	}
    60  
    61  	values := make([]string, 0, len(c))
    62  	for elem := range c {
    63  		values = append(values, elem)
    64  	}
    65  
    66  	sort.Strings(values)
    67  
    68  	return strings.Join(values, ",")
    69  }
    70  
    71  // IsSet returns true if the provided name is part of the collection,
    72  // false otherwise.
    73  func (c Collection) IsSet(name string) bool {
    74  	if c == nil {
    75  		return false
    76  	}
    77  
    78  	_, found := c[name]
    79  
    80  	return found
    81  }