github.com/richardbowden/terraform@v0.6.12-0.20160901200758-30ea22c25211/helper/schema/field_reader_map.go (about)

     1  package schema
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  )
     7  
     8  // MapFieldReader reads fields out of an untyped map[string]string to
     9  // the best of its ability.
    10  type MapFieldReader struct {
    11  	Map    MapReader
    12  	Schema map[string]*Schema
    13  }
    14  
    15  func (r *MapFieldReader) ReadField(address []string) (FieldReadResult, error) {
    16  	k := strings.Join(address, ".")
    17  	schemaList := addrToSchema(address, r.Schema)
    18  	if len(schemaList) == 0 {
    19  		return FieldReadResult{}, nil
    20  	}
    21  
    22  	schema := schemaList[len(schemaList)-1]
    23  	switch schema.Type {
    24  	case TypeBool, TypeInt, TypeFloat, TypeString:
    25  		return r.readPrimitive(address, schema)
    26  	case TypeList:
    27  		return readListField(r, address, schema)
    28  	case TypeMap:
    29  		return r.readMap(k)
    30  	case TypeSet:
    31  		return r.readSet(address, schema)
    32  	case typeObject:
    33  		return readObjectField(r, address, schema.Elem.(map[string]*Schema))
    34  	default:
    35  		panic(fmt.Sprintf("Unknown type: %s", schema.Type))
    36  	}
    37  }
    38  
    39  func (r *MapFieldReader) readMap(k string) (FieldReadResult, error) {
    40  	result := make(map[string]interface{})
    41  	resultSet := false
    42  
    43  	// If the name of the map field is directly in the map with an
    44  	// empty string, it means that the map is being deleted, so mark
    45  	// that is is set.
    46  	if v, ok := r.Map.Access(k); ok && v == "" {
    47  		resultSet = true
    48  	}
    49  
    50  	prefix := k + "."
    51  	r.Map.Range(func(k, v string) bool {
    52  		if strings.HasPrefix(k, prefix) {
    53  			resultSet = true
    54  
    55  			key := k[len(prefix):]
    56  			if key != "%" && key != "#" {
    57  				result[key] = v
    58  			}
    59  		}
    60  
    61  		return true
    62  	})
    63  
    64  	var resultVal interface{}
    65  	if resultSet {
    66  		resultVal = result
    67  	}
    68  
    69  	return FieldReadResult{
    70  		Value:  resultVal,
    71  		Exists: resultSet,
    72  	}, nil
    73  }
    74  
    75  func (r *MapFieldReader) readPrimitive(
    76  	address []string, schema *Schema) (FieldReadResult, error) {
    77  	k := strings.Join(address, ".")
    78  	result, ok := r.Map.Access(k)
    79  	if !ok {
    80  		return FieldReadResult{}, nil
    81  	}
    82  
    83  	returnVal, err := stringToPrimitive(result, false, schema)
    84  	if err != nil {
    85  		return FieldReadResult{}, err
    86  	}
    87  
    88  	return FieldReadResult{
    89  		Value:  returnVal,
    90  		Exists: true,
    91  	}, nil
    92  }
    93  
    94  func (r *MapFieldReader) readSet(
    95  	address []string, schema *Schema) (FieldReadResult, error) {
    96  	// Get the number of elements in the list
    97  	countRaw, err := r.readPrimitive(
    98  		append(address, "#"), &Schema{Type: TypeInt})
    99  	if err != nil {
   100  		return FieldReadResult{}, err
   101  	}
   102  	if !countRaw.Exists {
   103  		// No count, means we have no list
   104  		countRaw.Value = 0
   105  	}
   106  
   107  	// Create the set that will be our result
   108  	set := schema.ZeroValue().(*Set)
   109  
   110  	// If we have an empty list, then return an empty list
   111  	if countRaw.Computed || countRaw.Value.(int) == 0 {
   112  		return FieldReadResult{
   113  			Value:    set,
   114  			Exists:   countRaw.Exists,
   115  			Computed: countRaw.Computed,
   116  		}, nil
   117  	}
   118  
   119  	// Go through the map and find all the set items
   120  	prefix := strings.Join(address, ".") + "."
   121  	countExpected := countRaw.Value.(int)
   122  	countActual := make(map[string]struct{})
   123  	completed := r.Map.Range(func(k, _ string) bool {
   124  		if !strings.HasPrefix(k, prefix) {
   125  			return true
   126  		}
   127  		if strings.HasPrefix(k, prefix+"#") {
   128  			// Ignore the count field
   129  			return true
   130  		}
   131  
   132  		// Split the key, since it might be a sub-object like "idx.field"
   133  		parts := strings.Split(k[len(prefix):], ".")
   134  		idx := parts[0]
   135  
   136  		var raw FieldReadResult
   137  		raw, err = r.ReadField(append(address, idx))
   138  		if err != nil {
   139  			return false
   140  		}
   141  		if !raw.Exists {
   142  			// This shouldn't happen because we just verified it does exist
   143  			panic("missing field in set: " + k + "." + idx)
   144  		}
   145  
   146  		set.Add(raw.Value)
   147  
   148  		// Due to the way multimap readers work, if we've seen the number
   149  		// of fields we expect, then exit so that we don't read later values.
   150  		// For example: the "set" map might have "ports.#", "ports.0", and
   151  		// "ports.1", but the "state" map might have those plus "ports.2".
   152  		// We don't want "ports.2"
   153  		countActual[idx] = struct{}{}
   154  		if len(countActual) >= countExpected {
   155  			return false
   156  		}
   157  
   158  		return true
   159  	})
   160  	if !completed && err != nil {
   161  		return FieldReadResult{}, err
   162  	}
   163  
   164  	return FieldReadResult{
   165  		Value:  set,
   166  		Exists: true,
   167  	}, nil
   168  }
   169  
   170  // MapReader is an interface that is given to MapFieldReader for accessing
   171  // a "map". This can be used to have alternate implementations. For a basic
   172  // map[string]string, use BasicMapReader.
   173  type MapReader interface {
   174  	Access(string) (string, bool)
   175  	Range(func(string, string) bool) bool
   176  }
   177  
   178  // BasicMapReader implements MapReader for a single map.
   179  type BasicMapReader map[string]string
   180  
   181  func (r BasicMapReader) Access(k string) (string, bool) {
   182  	v, ok := r[k]
   183  	return v, ok
   184  }
   185  
   186  func (r BasicMapReader) Range(f func(string, string) bool) bool {
   187  	for k, v := range r {
   188  		if cont := f(k, v); !cont {
   189  			return false
   190  		}
   191  	}
   192  
   193  	return true
   194  }
   195  
   196  // MultiMapReader reads over multiple maps, preferring keys that are
   197  // founder earlier (lower number index) vs. later (higher number index)
   198  type MultiMapReader []map[string]string
   199  
   200  func (r MultiMapReader) Access(k string) (string, bool) {
   201  	for _, m := range r {
   202  		if v, ok := m[k]; ok {
   203  			return v, ok
   204  		}
   205  	}
   206  
   207  	return "", false
   208  }
   209  
   210  func (r MultiMapReader) Range(f func(string, string) bool) bool {
   211  	done := make(map[string]struct{})
   212  	for _, m := range r {
   213  		for k, v := range m {
   214  			if _, ok := done[k]; ok {
   215  				continue
   216  			}
   217  
   218  			if cont := f(k, v); !cont {
   219  				return false
   220  			}
   221  
   222  			done[k] = struct{}{}
   223  		}
   224  	}
   225  
   226  	return true
   227  }