From add7ae723764b07d25a46508852906a9227165c2 Mon Sep 17 00:00:00 2001 From: Mathieu Acthernoene Date: Thu, 15 Dec 2016 13:28:57 +0100 Subject: [PATCH] Extract ProtoHelpersFuncMap in its own file --- encoder.go | 31 ------------------------------- helpers.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 31 deletions(-) create mode 100644 helpers.go diff --git a/encoder.go b/encoder.go index 6cf6181..86e20e6 100644 --- a/encoder.go +++ b/encoder.go @@ -2,7 +2,6 @@ package main import ( "bytes" - "encoding/json" "log" "os" "path/filepath" @@ -10,39 +9,10 @@ import ( "text/template" "time" - "github.com/Masterminds/sprig" "github.com/golang/protobuf/protoc-gen-go/descriptor" "github.com/golang/protobuf/protoc-gen-go/plugin" ) -var ProtoHelpersFuncMap = template.FuncMap{ - "string": func(i interface { - String() string - }) string { - return i.String() - }, - "json": func(v interface{}) string { - a, _ := json.Marshal(v) - return string(a) - }, - "prettyjson": func(v interface{}) string { - a, _ := json.MarshalIndent(v, "", " ") - return string(a) - }, - "first": func(a []string) string { - return a[0] - }, - "last": func(a []string) string { - return a[len(a)-1] - }, -} - -func init() { - for k, v := range sprig.TxtFuncMap() { - ProtoHelpersFuncMap[k] = v - } -} - type GenericTemplateBasedEncoder struct { templateDir string service *descriptor.ServiceDescriptorProto @@ -146,7 +116,6 @@ func (e *GenericTemplateBasedEncoder) buildContent(templateFilename string) (str // initialize template engine fullPath := filepath.Join(e.templateDir, templateFilename) templateName := filepath.Base(fullPath) - tmpl, err := template.New(templateName).Funcs(ProtoHelpersFuncMap).ParseFiles(fullPath) if err != nil { return "", "", err diff --git a/helpers.go b/helpers.go new file mode 100644 index 0000000..39cf9ad --- /dev/null +++ b/helpers.go @@ -0,0 +1,36 @@ +package main + +import ( + "encoding/json" + "text/template" + + "github.com/Masterminds/sprig" +) + +var ProtoHelpersFuncMap = template.FuncMap{ + "string": func(i interface { + String() string + }) string { + return i.String() + }, + "json": func(v interface{}) string { + a, _ := json.Marshal(v) + return string(a) + }, + "prettyjson": func(v interface{}) string { + a, _ := json.MarshalIndent(v, "", " ") + return string(a) + }, + "first": func(a []string) string { + return a[0] + }, + "last": func(a []string) string { + return a[len(a)-1] + }, +} + +func init() { + for k, v := range sprig.TxtFuncMap() { + ProtoHelpersFuncMap[k] = v + } +}