Skip to content

Commit

Permalink
installer: Template: Make it gob-decodable
Browse files Browse the repository at this point in the history
  • Loading branch information
livingsilver94 committed Nov 2, 2023
1 parent 95541b0 commit fbb4ed8
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
28 changes: 28 additions & 0 deletions installer/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package installer
import (
"bufio"
"bytes"
"encoding/gob"
"io"
"strings"

Expand Down Expand Up @@ -58,6 +59,33 @@ func (t Template) ReplaceStringToString(s string) (string, error) {
)
}

func (t Template) GobEncode() ([]byte, error) {
buf := &bytes.Buffer{}
enc := gob.NewEncoder(buf)
err := enc.Encode(t.serviceName)
if err != nil {
return nil, err
}
err = enc.Encode(t.variables)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}

func (t *Template) GobDecode(data []byte) error {
dec := gob.NewDecoder(bytes.NewReader(data))
err := dec.Decode(&t.serviceName)
if err != nil {
return err
}
err = dec.Decode(&t.variables)
if err != nil {
return err
}
return nil
}

func (t Template) replaceTag(w io.Writer, varName string) (int, error) {
if val, err := t.variables.Get(t.serviceName, varName); err == nil {
// Matched a variable local to the service.
Expand Down
18 changes: 18 additions & 0 deletions installer/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package installer_test
import (
"bytes"
"errors"
"reflect"
"strings"
"testing"

Expand Down Expand Up @@ -96,6 +97,23 @@ func TestReplaceReader(t *testing.T) {
}
}

func TestGobCodec(t *testing.T) {
expected := installer.NewTemplate(serviceName, createVariables("var1", "value1"))

data, err := expected.GobEncode()
if err != nil {
t.Fatal(err)
}
var result installer.Template
err = result.GobDecode(data)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(result, expected) {
t.Fatalf("expected decoded template %#v. Got %#v", expected, result)
}
}

const serviceName = "service1"

func createVariables(keyVal ...string) repo.Variables {
Expand Down
6 changes: 6 additions & 0 deletions repo/variables.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,12 @@ func (vars *Variables) GobDecode(data []byte) error {
if err != nil {
return err
}
if len(vars.Common) == 0 {
// gob allocates an empty map even if we encoded a nil map.
// We want to replicate the behavior of NewVariables, so if
// gob allocated an empty map, we reset it to nil.
vars.Common = nil
}
err = dec.Decode(&vars.resolved)
if err != nil {
return err
Expand Down

0 comments on commit fbb4ed8

Please sign in to comment.