go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/server/portal/yesno.go (about)

     1  // Copyright 2016 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 portal
    16  
    17  import (
    18  	"errors"
    19  )
    20  
    21  // YesOrNo is a bool that serializes to 'yes' or 'no'.
    22  //
    23  // Useful in Fields that define boolean values.
    24  type YesOrNo bool
    25  
    26  // String returns "yes" or "no".
    27  func (yn YesOrNo) String() string {
    28  	if yn {
    29  		return "yes"
    30  	}
    31  	return "no"
    32  }
    33  
    34  // Set changes the value of YesOrNo.
    35  func (yn *YesOrNo) Set(v string) error {
    36  	switch v {
    37  	case "yes":
    38  		*yn = true
    39  	case "no":
    40  		*yn = false
    41  	default:
    42  		return errors.New("expecting 'yes' or 'no'")
    43  	}
    44  	return nil
    45  }
    46  
    47  // YesOrNoField modifies the field so that it corresponds to YesOrNo value.
    48  //
    49  // It sets 'Type', 'ChoiceVariants' and 'Validator' properties.
    50  func YesOrNoField(f Field) Field {
    51  	f.Type = FieldChoice
    52  	f.ChoiceVariants = []string{"yes", "no"}
    53  	f.Validator = func(v string) error {
    54  		var x YesOrNo
    55  		return x.Set(v)
    56  	}
    57  	return f
    58  }