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

     1  // Copyright 2018 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  	"strings"
    20  
    21  	"go.chromium.org/luci/common/errors"
    22  )
    23  
    24  // commaListFlag implements the flag.Getter returned by CommaList.
    25  type commaListFlag []string
    26  
    27  // CommaList returns a flag.Getter for parsing a comma
    28  // separated flag argument into a string slice.
    29  func CommaList(s *[]string) flag.Getter {
    30  	return (*commaListFlag)(s)
    31  }
    32  
    33  // String implements the flag.Value interface.
    34  func (f commaListFlag) String() string {
    35  	return strings.Join(f, ",")
    36  }
    37  
    38  // Set implements the flag.Value interface.
    39  func (f *commaListFlag) Set(s string) error {
    40  	if f == nil {
    41  		return errors.Reason("commaListFlag pointer is nil").Err()
    42  	}
    43  	*f = splitCommaList(s)
    44  	return nil
    45  }
    46  
    47  // Get retrieves the flag value.
    48  func (f commaListFlag) Get() any {
    49  	return []string(f)
    50  }
    51  
    52  // splitCommaList splits a comma separated string into a slice of
    53  // strings.  If the string is empty, return an empty slice.
    54  func splitCommaList(s string) []string {
    55  	if s == "" {
    56  		return nil
    57  	}
    58  	return strings.Split(s, ",")
    59  }