go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/buildbucket/cli/experiments.go (about)

     1  // Copyright 2021 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 cli
    16  
    17  import (
    18  	"flag"
    19  	"sort"
    20  	"strings"
    21  
    22  	"go.chromium.org/luci/common/errors"
    23  )
    24  
    25  type experimentsFlag struct {
    26  	experiments map[string]bool
    27  }
    28  
    29  func (f *experimentsFlag) Register(fs *flag.FlagSet, help string) {
    30  	f.experiments = map[string]bool{}
    31  	fs.Var(f, "ex", help)
    32  }
    33  
    34  func (f *experimentsFlag) Set(exp string) error {
    35  	if len(exp) < 2 {
    36  		return errors.Reason("expected [+-]experiment_name, got %q", exp).Err()
    37  	}
    38  	switch plusMinus, expname := exp[0], exp[1:]; plusMinus {
    39  	case '+':
    40  		f.experiments[expname] = true
    41  	case '-':
    42  		f.experiments[expname] = false
    43  	default:
    44  		return errors.Reason("expected [+-]experiment_name, got %q", exp).Err()
    45  	}
    46  	return nil
    47  }
    48  
    49  func (f *experimentsFlag) String() string {
    50  	return strings.Join(f.experimentsFlat(), ", ")
    51  }
    52  
    53  func (f *experimentsFlag) experimentsFlat() []string {
    54  	bits := make([]string, 0, len(f.experiments))
    55  	for exp, enabled := range f.experiments {
    56  		if enabled {
    57  			bits = append(bits, "+"+exp)
    58  		} else {
    59  			bits = append(bits, "-"+exp)
    60  		}
    61  	}
    62  	sort.Strings(bits)
    63  	return bits
    64  }