From e5b82931ff6ba70a9e8b0e921b16182e229d8207 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Wed, 18 Jun 2014 20:34:39 -0700 Subject: [PATCH] terraform: read/write diff to binary format --- terraform/diff.go | 20 ++++++++++++++++++++ terraform/diff_test.go | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/terraform/diff.go b/terraform/diff.go index 4baf2ebbc..5d1b656e1 100644 --- a/terraform/diff.go +++ b/terraform/diff.go @@ -2,7 +2,9 @@ package terraform import ( "bytes" + "encoding/gob" "fmt" + "io" "sort" "strings" "sync" @@ -14,6 +16,24 @@ type Diff struct { once sync.Once } +// ReadDiff reads a diff structure out of a reader in the format that +// was written by WriteDiff. +func ReadDiff(src io.Reader) (*Diff, error) { + var result *Diff + + dec := gob.NewDecoder(src) + if err := dec.Decode(&result); err != nil { + return nil, err + } + + return result, nil +} + +// WriteDiff writes a diff somewhere in a binary format. +func WriteDiff(d *Diff, dst io.Writer) error { + return gob.NewEncoder(dst).Encode(d) +} + func (d *Diff) init() { d.once.Do(func() { if d.Resources == nil { diff --git a/terraform/diff_test.go b/terraform/diff_test.go index 0e4d951d7..5268ba32a 100644 --- a/terraform/diff_test.go +++ b/terraform/diff_test.go @@ -1,6 +1,8 @@ package terraform import ( + "bytes" + "reflect" "strings" "testing" ) @@ -61,6 +63,44 @@ func TestResourceDiff_RequiresNew_nil(t *testing.T) { } } +func TestReadWriteDiff(t *testing.T) { + diff := &Diff{ + Resources: map[string]*ResourceDiff{ + "nodeA": &ResourceDiff{ + Attributes: map[string]*ResourceAttrDiff{ + "foo": &ResourceAttrDiff{ + Old: "foo", + New: "bar", + }, + "bar": &ResourceAttrDiff{ + Old: "foo", + NewComputed: true, + }, + "longfoo": &ResourceAttrDiff{ + Old: "foo", + New: "bar", + RequiresNew: true, + }, + }, + }, + }, + } + + buf := new(bytes.Buffer) + if err := WriteDiff(diff, buf); err != nil { + t.Fatalf("err: %s", err) + } + + actual, err := ReadDiff(buf) + if err != nil { + t.Fatalf("err: %s", err) + } + + if !reflect.DeepEqual(actual, diff) { + t.Fatalf("bad: %#v", actual) + } +} + const diffStrBasic = ` CREATE: nodeA bar: "foo" => ""