From aeb793f968ceb121a0315e0fa8e870cf96128b68 Mon Sep 17 00:00:00 2001 From: Chris Marchesi Date: Thu, 25 May 2017 09:45:31 -0700 Subject: [PATCH] helper/schema: Add Clear function to ResourceDiff This should complete the feature set of the prototype. This function removes a specific key from the existing diff, preventing conflicts. Further functionality might be needed to make this behave as expected, namely ensuring that we don't re-process the whole diff after the CustomizeDiffFunc runs. --- helper/schema/resource_diff.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/helper/schema/resource_diff.go b/helper/schema/resource_diff.go index 91658d3e5..30fd741ab 100644 --- a/helper/schema/resource_diff.go +++ b/helper/schema/resource_diff.go @@ -186,10 +186,30 @@ func newResourceDiff(schema map[string]*Schema, config *terraform.ResourceConfig // ClearAll wipes the current diff. This cannot be undone - use only if you // need to create a whole new diff from scatch, such as when you are leaning on // the provider completely to create the diff. +// +// Note that this does not wipe overrides. func (d *ResourceDiff) ClearAll() { d.diff = new(terraform.InstanceDiff) } +// Clear wipes the diff for a particular key. It is called by SetDiff to remove +// any possibility of conflicts, but can be called on its own to just remove a +// specific key from the diff completely. +// +// Note that this does not wipe an override. +func (d *ResourceDiff) Clear(key string) error { + // Check the schema to make sure that this key exists first. + if _, ok := d.schema[key]; !ok { + return fmt.Errorf("%s is not a valid key", key) + } + for k := range d.diff.Attributes { + if strings.HasPrefix(k, key) { + delete(d.diff.Attributes, k) + } + } + return nil +} + // diffChange helps to implement resourceDiffer and derives its change values // from ResourceDiff's own change data, in addition to existing diff, config, and state. func (d *ResourceDiff) diffChange(key string) (interface{}, interface{}, bool, bool) { @@ -238,6 +258,10 @@ func (d *ResourceDiff) SetDiff(key string, old, new interface{}, computed bool) return fmt.Errorf("SetNew, SetNewComputed, and SetDiff are allowed on computed attributes only - %s is not one", key) } + if err := d.Clear(key); err != nil { + return err + } + if err := d.oldWriter.WriteField(strings.Split(key, "."), old); err != nil { return fmt.Errorf("Cannot set old diff value for key %s: %s", key, err) }