github.com/turtlemonvh/terraform@v0.6.9-0.20151204001754-8e40b6b855e8/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  // Takes a Stringlist and returns one without empty strings in it
    28  func (sl StringList) Compact() StringList {
    29  	parts := sl.Slice()
    30  
    31  	newlist := []string{}
    32  	// drop the empty strings
    33  	for i := range parts {
    34  		if parts[i] != "" {
    35  			newlist = append(newlist, parts[i])
    36  		}
    37  	}
    38  	return NewStringList(newlist)
    39  }
    40  
    41  // Build a StringList from a slice
    42  func NewStringList(parts []string) StringList {
    43  	// We have to special case the empty list representation
    44  	if len(parts) == 0 {
    45  		return StringList(stringListDelim)
    46  	}
    47  	return StringList(fmt.Sprintf("%s%s%s",
    48  		stringListDelim,
    49  		strings.Join(parts, stringListDelim),
    50  		stringListDelim,
    51  	))
    52  }
    53  
    54  // Returns an element at the index, wrapping around the length of the string
    55  // when index > list length
    56  func (sl StringList) Element(index int) string {
    57  	if sl.Length() == 0 {
    58  		return ""
    59  	}
    60  	return sl.Slice()[index%sl.Length()]
    61  }
    62  
    63  // Returns the length of the StringList
    64  func (sl StringList) Length() int {
    65  	return len(sl.Slice())
    66  }
    67  
    68  // Returns a slice of strings as represented by this StringList
    69  func (sl StringList) Slice() []string {
    70  	parts := strings.Split(string(sl), stringListDelim)
    71  
    72  	// split on an empty StringList will have a length of 2, since there is
    73  	// always at least one deliminator
    74  	if len(parts) <= 2 {
    75  		return []string{}
    76  	}
    77  
    78  	// strip empty elements generated by leading and trailing delimiters
    79  	return parts[1 : len(parts)-1]
    80  }
    81  
    82  func (sl StringList) String() string {
    83  	return string(sl)
    84  }
    85  
    86  // Determines if a given string represents a StringList
    87  func IsStringList(s string) bool {
    88  	return strings.Contains(s, stringListDelim)
    89  }