github.com/2matz/terraform@v0.6.1-0.20150714181608-a03cbdb5d5bd/config/string_list.go (about)

     1  package config
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  )
     7  
     8  // StringList represents the "poor man's list" that terraform uses
     9  // internally
    10  type StringList string
    11  
    12  // This is the delimiter used to recognize and split StringLists
    13  //
    14  // It plays two semantic roles:
    15  //   * It introduces a list
    16  //   * It terminates each element
    17  //
    18  // Example representations:
    19  // []             => SLD
    20  // [""]           => SLDSLD
    21  // [" "]          => SLD SLD
    22  // ["foo"]        => SLDfooSLD
    23  // ["foo", "bar"] => SLDfooSLDbarSLD
    24  // ["", ""]       => SLDSLDSLD
    25  const stringListDelim = `B780FFEC-B661-4EB8-9236-A01737AD98B6`
    26  
    27  // Build a StringList from a slice
    28  func NewStringList(parts []string) StringList {
    29  	// We have to special case the empty list representation
    30  	if len(parts) == 0 {
    31  		return StringList(stringListDelim)
    32  	}
    33  	return StringList(fmt.Sprintf("%s%s%s",
    34  		stringListDelim,
    35  		strings.Join(parts, stringListDelim),
    36  		stringListDelim,
    37  	))
    38  }
    39  
    40  // Returns an element at the index, wrapping around the length of the string
    41  // when index > list length
    42  func (sl StringList) Element(index int) string {
    43  	if sl.Length() == 0 {
    44  		return ""
    45  	}
    46  	return sl.Slice()[index%sl.Length()]
    47  }
    48  
    49  // Returns the length of the StringList
    50  func (sl StringList) Length() int {
    51  	return len(sl.Slice())
    52  }
    53  
    54  // Returns a slice of strings as represented by this StringList
    55  func (sl StringList) Slice() []string {
    56  	parts := strings.Split(string(sl), stringListDelim)
    57  
    58  	switch len(parts) {
    59  	case 0, 1:
    60  		return []string{}
    61  	case 2:
    62  		return []string{""}
    63  	}
    64  
    65  	// strip empty elements generated by leading and trailing delimiters
    66  	return parts[1 : len(parts)-1]
    67  }
    68  
    69  func (sl StringList) String() string {
    70  	return string(sl)
    71  }
    72  
    73  // Determines if a given string represents a StringList
    74  func IsStringList(s string) bool {
    75  	return strings.Contains(s, stringListDelim)
    76  }