github.com/vtorhonen/terraform@v0.9.0-beta2.0.20170307220345-5d894e4ffda7/builtin/providers/ns1/string_enum.go (about)

     1  package ns1
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  )
     7  
     8  type StringEnum struct {
     9  	ValueMap  map[string]int
    10  	Expecting string
    11  }
    12  
    13  func NewStringEnum(values []string) *StringEnum {
    14  	valueMap := make(map[string]int)
    15  	quoted := make([]string, len(values), len(values))
    16  	for i, value := range values {
    17  		_, present := valueMap[value]
    18  		if present {
    19  			panic(fmt.Sprintf("duplicate value %q", value))
    20  		}
    21  		valueMap[value] = i
    22  
    23  		quoted[i] = fmt.Sprintf("%q", value)
    24  	}
    25  
    26  	return &StringEnum{
    27  		ValueMap:  valueMap,
    28  		Expecting: strings.Join(quoted, ", "),
    29  	}
    30  }
    31  
    32  func (se *StringEnum) Check(v string) (int, error) {
    33  	i, present := se.ValueMap[v]
    34  	if present {
    35  		return i, nil
    36  	} else {
    37  		return -1, fmt.Errorf("expecting one of %s; got %q", se.Expecting, v)
    38  	}
    39  }
    40  
    41  func (se *StringEnum) ValidateFunc(v interface{}, k string) (ws []string, es []error) {
    42  	_, err := se.Check(v.(string))
    43  	if err != nil {
    44  		return nil, []error{err}
    45  	}
    46  	return nil, nil
    47  }