summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDave Henderson <dhenderson@gmail.com>2018-02-18 23:25:43 -0500
committerDave Henderson <dhenderson@gmail.com>2018-04-18 15:23:49 -0400
commit0ff06aa75c6a3062852f08c0ae73751530ede6c3 (patch)
tree01002e4c015ee950f3b63c6584ebb8462eaf9b87
parentcd60ef2d97a45135f3b4127ea0038db5a4ffe847 (diff)
Putting main pkg in cmd subdirectory
Signed-off-by: Dave Henderson <dhenderson@gmail.com>
-rw-r--r--Makefile3
-rw-r--r--cleanup.go2
-rw-r--r--cmd/gomplate/main.go (renamed from main.go)52
-rw-r--r--context.go8
-rw-r--r--context_test.go6
-rw-r--r--funcs.go2
-rw-r--r--gomplate.go48
-rw-r--r--gomplate_test.go26
-rw-r--r--template.go40
-rw-r--r--template_test.go20
10 files changed, 105 insertions, 102 deletions
diff --git a/Makefile b/Makefile
index 1bb3ab1c..2cf8c330 100644
--- a/Makefile
+++ b/Makefile
@@ -54,7 +54,8 @@ $(PREFIX)/bin/$(PKG_NAME)_%: $(shell find $(PREFIX) -type f -name '*.go')
GOOS=$(shell echo $* | cut -f1 -d-) GOARCH=$(shell echo $* | cut -f2 -d- | cut -f1 -d.) CGO_ENABLED=0 \
$(GO) build \
-ldflags "-w -s $(COMMIT_FLAG) $(VERSION_FLAG)" \
- -o $@
+ -o $@ \
+ ./cmd/gomplate
$(PREFIX)/bin/$(PKG_NAME)$(call extension,$(GOOS)): $(PREFIX)/bin/$(PKG_NAME)_$(GOOS)-$(GOARCH)$(call extension,$(GOOS))
cp $< $@
diff --git a/cleanup.go b/cleanup.go
index 9ea78af4..81af5661 100644
--- a/cleanup.go
+++ b/cleanup.go
@@ -1,4 +1,4 @@
-package main
+package gomplate
var cleanupHooks = make([]func(), 0)
diff --git a/main.go b/cmd/gomplate/main.go
index f5f34011..256bed1f 100644
--- a/main.go
+++ b/cmd/gomplate/main.go
@@ -5,36 +5,24 @@ import (
"fmt"
"os"
+ "github.com/hairyhenderson/gomplate"
"github.com/hairyhenderson/gomplate/env"
"github.com/hairyhenderson/gomplate/version"
"github.com/spf13/cobra"
)
-// GomplateOpts -
-type GomplateOpts struct {
- version bool
- dataSources []string
- dataSourceHeaders []string
- lDelim string
- rDelim string
-
- input string
- inputFiles []string
- inputDir string
- outputFiles []string
- outputDir string
- excludeGlob []string
-}
-
-var opts GomplateOpts
+var (
+ printVer bool
+ opts gomplate.Config
+)
func validateOpts(cmd *cobra.Command, args []string) error {
if cmd.Flag("in").Changed && cmd.Flag("file").Changed {
return errors.New("--in and --file may not be used together")
}
- if len(opts.inputFiles) != len(opts.outputFiles) {
- return fmt.Errorf("Must provide same number of --out (%d) as --file (%d) options", len(opts.outputFiles), len(opts.inputFiles))
+ if len(opts.InputFiles) != len(opts.OutputFiles) {
+ return fmt.Errorf("Must provide same number of --out (%d) as --file (%d) options", len(opts.OutputFiles), len(opts.InputFiles))
}
if cmd.Flag("input-dir").Changed && (cmd.Flag("in").Changed || cmd.Flag("file").Changed) {
@@ -63,11 +51,11 @@ func newGomplateCmd() *cobra.Command {
Short: "Process text files with Go templates",
PreRunE: validateOpts,
RunE: func(cmd *cobra.Command, args []string) error {
- if opts.version {
+ if printVer {
printVersion(cmd.Name())
return nil
}
- return runTemplate(&opts)
+ return gomplate.RunTemplates(&opts)
},
Args: cobra.NoArgs,
}
@@ -75,22 +63,22 @@ func newGomplateCmd() *cobra.Command {
}
func initFlags(command *cobra.Command) {
- command.Flags().BoolVarP(&opts.version, "version", "v", false, "print the version")
+ command.Flags().BoolVarP(&printVer, "version", "v", false, "print the version")
- command.Flags().StringArrayVarP(&opts.inputFiles, "file", "f", []string{"-"}, "Template `file` to process. Omit to use standard input, or use --in or --input-dir")
- command.Flags().StringVarP(&opts.input, "in", "i", "", "Template `string` to process (alternative to --file and --input-dir)")
- command.Flags().StringVar(&opts.inputDir, "input-dir", "", "`directory` which is examined recursively for templates (alternative to --file and --in)")
- command.Flags().StringArrayVar(&opts.excludeGlob, "exclude", []string{}, "glob of files to not parse")
- command.Flags().StringArrayVarP(&opts.outputFiles, "out", "o", []string{"-"}, "output `file` name. Omit to use standard output.")
- command.Flags().StringVar(&opts.outputDir, "output-dir", ".", "`directory` to store the processed templates. Only used for --input-dir")
+ command.Flags().StringArrayVarP(&opts.InputFiles, "file", "f", []string{"-"}, "Template `file` to process. Omit to use standard input, or use --in or --input-dir")
+ command.Flags().StringVarP(&opts.Input, "in", "i", "", "Template `string` to process (alternative to --file and --input-dir)")
+ command.Flags().StringVar(&opts.InputDir, "input-dir", "", "`directory` which is examined recursively for templates (alternative to --file and --in)")
+ command.Flags().StringArrayVar(&opts.ExcludeGlob, "exclude", []string{}, "glob of files to not parse")
+ command.Flags().StringArrayVarP(&opts.OutputFiles, "out", "o", []string{"-"}, "output `file` name. Omit to use standard output.")
+ command.Flags().StringVar(&opts.OutputDir, "output-dir", ".", "`directory` to store the processed templates. Only used for --input-dir")
- command.Flags().StringArrayVarP(&opts.dataSources, "datasource", "d", nil, "`datasource` in alias=URL form. Specify multiple times to add multiple sources.")
- command.Flags().StringArrayVarP(&opts.dataSourceHeaders, "datasource-header", "H", nil, "HTTP `header` field in 'alias=Name: value' form to be provided on HTTP-based data sources. Multiples can be set.")
+ command.Flags().StringArrayVarP(&opts.DataSources, "datasource", "d", nil, "`datasource` in alias=URL form. Specify multiple times to add multiple sources.")
+ command.Flags().StringArrayVarP(&opts.DataSourceHeaders, "datasource-header", "H", nil, "HTTP `header` field in 'alias=Name: value' form to be provided on HTTP-based data sources. Multiples can be set.")
ldDefault := env.Getenv("GOMPLATE_LEFT_DELIM", "{{")
rdDefault := env.Getenv("GOMPLATE_RIGHT_DELIM", "}}")
- command.Flags().StringVar(&opts.lDelim, "left-delim", ldDefault, "override the default left-`delimiter` [$GOMPLATE_LEFT_DELIM]")
- command.Flags().StringVar(&opts.rDelim, "right-delim", rdDefault, "override the default right-`delimiter` [$GOMPLATE_RIGHT_DELIM]")
+ command.Flags().StringVar(&opts.LDelim, "left-delim", ldDefault, "override the default left-`delimiter` [$GOMPLATE_LEFT_DELIM]")
+ command.Flags().StringVar(&opts.RDelim, "right-delim", rdDefault, "override the default right-`delimiter` [$GOMPLATE_RIGHT_DELIM]")
}
func main() {
diff --git a/context.go b/context.go
index 939883ea..6c100dfb 100644
--- a/context.go
+++ b/context.go
@@ -1,16 +1,16 @@
-package main
+package gomplate
import (
"os"
"strings"
)
-// Context for templates
-type Context struct {
+// context for templates
+type context struct {
}
// Env - Map environment variables for use in a template
-func (c *Context) Env() map[string]string {
+func (c *context) Env() map[string]string {
env := make(map[string]string)
for _, i := range os.Environ() {
sep := strings.Index(i, "=")
diff --git a/context_test.go b/context_test.go
index b4a60ff3..16492e9a 100644
--- a/context_test.go
+++ b/context_test.go
@@ -1,4 +1,4 @@
-package main
+package gomplate
import (
"os"
@@ -8,13 +8,13 @@ import (
)
func TestEnvMapifiesEnvironment(t *testing.T) {
- c := &Context{}
+ c := &context{}
env := c.Env()
assert.Equal(t, env["USER"], os.Getenv("USER"))
}
func TestEnvGetsUpdatedEnvironment(t *testing.T) {
- c := &Context{}
+ c := &context{}
assert.Empty(t, c.Env()["FOO"])
assert.NoError(t, os.Setenv("FOO", "foo"))
assert.Equal(t, c.Env()["FOO"], "foo")
diff --git a/funcs.go b/funcs.go
index 65a4b480..16a61f0c 100644
--- a/funcs.go
+++ b/funcs.go
@@ -1,4 +1,4 @@
-package main
+package gomplate
import (
"text/template"
diff --git a/gomplate.go b/gomplate.go
index 76b06260..debfed74 100644
--- a/gomplate.go
+++ b/gomplate.go
@@ -1,4 +1,4 @@
-package main
+package gomplate
import (
"io"
@@ -7,16 +7,33 @@ import (
"github.com/hairyhenderson/gomplate/data"
)
-// Gomplate -
-type Gomplate struct {
+// Config - values necessary for rendering templates with gomplate.
+// Mainly for use by the CLI
+type Config struct {
+ Input string
+ InputFiles []string
+ InputDir string
+ ExcludeGlob []string
+ OutputFiles []string
+ OutputDir string
+
+ DataSources []string
+ DataSourceHeaders []string
+
+ LDelim string
+ RDelim string
+}
+
+// gomplate -
+type gomplate struct {
funcMap template.FuncMap
leftDelim string
rightDelim string
}
-// RunTemplate -
-func (g *Gomplate) RunTemplate(t *tplate) error {
- context := &Context{}
+// runTemplate -
+func (g *gomplate) runTemplate(t *tplate) error {
+ context := &context{}
tmpl, err := t.toGoTemplate(g)
if err != nil {
return err
@@ -31,28 +48,33 @@ func (g *Gomplate) RunTemplate(t *tplate) error {
return err
}
-// NewGomplate -
-func NewGomplate(d *data.Data, leftDelim, rightDelim string) *Gomplate {
- return &Gomplate{
+// newGomplate -
+func newGomplate(d *data.Data, leftDelim, rightDelim string) *gomplate {
+ return &gomplate{
leftDelim: leftDelim,
rightDelim: rightDelim,
funcMap: initFuncs(d),
}
}
-func runTemplate(o *GomplateOpts) error {
+// RunTemplates - run all gomplate templates specified by the given configuration
+func RunTemplates(o *Config) error {
defer runCleanupHooks()
- d := data.NewData(o.dataSources, o.dataSourceHeaders)
+ d := data.NewData(o.DataSources, o.DataSourceHeaders)
addCleanupHook(d.Cleanup)
- g := NewGomplate(d, o.lDelim, o.rDelim)
+ g := newGomplate(d, o.LDelim, o.RDelim)
+
+ return g.runTemplates(o)
+}
+func (g *gomplate) runTemplates(o *Config) error {
tmpl, err := gatherTemplates(o)
if err != nil {
return err
}
for _, t := range tmpl {
- if err := g.RunTemplate(t); err != nil {
+ if err := g.runTemplate(t); err != nil {
return err
}
}
diff --git a/gomplate_test.go b/gomplate_test.go
index c091f1ea..233faa3b 100644
--- a/gomplate_test.go
+++ b/gomplate_test.go
@@ -1,4 +1,4 @@
-package main
+package gomplate
import (
"bytes"
@@ -15,14 +15,14 @@ import (
"github.com/stretchr/testify/assert"
)
-func testTemplate(g *Gomplate, tmpl string) string {
+func testTemplate(g *gomplate, tmpl string) string {
var out bytes.Buffer
- g.RunTemplate(&tplate{name: "testtemplate", contents: tmpl, target: &out})
+ g.runTemplate(&tplate{name: "testtemplate", contents: tmpl, target: &out})
return out.String()
}
func TestGetenvTemplates(t *testing.T) {
- g := &Gomplate{
+ g := &gomplate{
funcMap: template.FuncMap{
"getenv": env.Getenv,
"bool": conv.Bool,
@@ -34,7 +34,7 @@ func TestGetenvTemplates(t *testing.T) {
}
func TestBoolTemplates(t *testing.T) {
- g := &Gomplate{
+ g := &gomplate{
funcMap: template.FuncMap{
"bool": conv.Bool,
},
@@ -46,9 +46,9 @@ func TestBoolTemplates(t *testing.T) {
}
func TestEc2MetaTemplates(t *testing.T) {
- createGomplate := func(status int, body string) (*Gomplate, *httptest.Server) {
+ createGomplate := func(status int, body string) (*gomplate, *httptest.Server) {
server, ec2meta := aws.MockServer(status, body)
- return &Gomplate{funcMap: template.FuncMap{"ec2meta": ec2meta.Meta}}, server
+ return &gomplate{funcMap: template.FuncMap{"ec2meta": ec2meta.Meta}}, server
}
g, s := createGomplate(404, "")
@@ -66,7 +66,7 @@ func TestEc2MetaTemplates(t *testing.T) {
func TestEc2MetaTemplates_WithJSON(t *testing.T) {
server, ec2meta := aws.MockServer(200, `{"foo":"bar"}`)
defer server.Close()
- g := &Gomplate{
+ g := &gomplate{
funcMap: template.FuncMap{
"ec2meta": ec2meta.Meta,
"ec2dynamic": ec2meta.Dynamic,
@@ -79,7 +79,7 @@ func TestEc2MetaTemplates_WithJSON(t *testing.T) {
}
func TestJSONArrayTemplates(t *testing.T) {
- g := &Gomplate{
+ g := &gomplate{
funcMap: template.FuncMap{
"jsonArray": data.JSONArray,
},
@@ -90,7 +90,7 @@ func TestJSONArrayTemplates(t *testing.T) {
}
func TestYAMLTemplates(t *testing.T) {
- g := &Gomplate{
+ g := &gomplate{
funcMap: template.FuncMap{
"yaml": data.YAML,
"yamlArray": data.YAMLArray,
@@ -103,7 +103,7 @@ func TestYAMLTemplates(t *testing.T) {
}
func TestSliceTemplates(t *testing.T) {
- g := &Gomplate{
+ g := &gomplate{
funcMap: template.FuncMap{
"slice": conv.Slice,
},
@@ -114,7 +114,7 @@ func TestSliceTemplates(t *testing.T) {
}
func TestHasTemplate(t *testing.T) {
- g := &Gomplate{
+ g := &gomplate{
funcMap: template.FuncMap{
"yaml": data.YAML,
"has": conv.Has,
@@ -138,7 +138,7 @@ func TestHasTemplate(t *testing.T) {
}
func TestCustomDelim(t *testing.T) {
- g := &Gomplate{
+ g := &gomplate{
leftDelim: "[",
rightDelim: "]",
funcMap: template.FuncMap{},
diff --git a/template.go b/template.go
index 8df7946a..3b4b8193 100644
--- a/template.go
+++ b/template.go
@@ -1,4 +1,4 @@
-package main
+package gomplate
import (
"fmt"
@@ -16,14 +16,14 @@ var stdin io.ReadCloser = os.Stdin
var stdout io.WriteCloser = os.Stdout
var fs = afero.NewOsFs()
-// tplate - models a tplate file...
+// tplate - models a gomplate template file...
type tplate struct {
name string
target io.Writer
contents string
}
-func (t *tplate) toGoTemplate(g *Gomplate) (*template.Template, error) {
+func (t *tplate) toGoTemplate(g *gomplate) (*template.Template, error) {
tmpl := template.New(t.name)
tmpl.Option("missingkey=error")
tmpl.Funcs(g.funcMap)
@@ -39,48 +39,40 @@ func (t *tplate) loadContents() (err error) {
return err
}
-func (t *tplate) addTarget(outFile string) error {
+func (t *tplate) addTarget(outFile string) (err error) {
if t.target == nil {
- target, err := openOutFile(outFile)
- if err != nil {
- return err
- }
- addCleanupHook(func() {
- // nolint: errcheck
- target.Close()
- })
- t.target = target
+ t.target, err = openOutFile(outFile)
}
- return nil
+ return err
}
// gatherTemplates - gather and prepare input template(s) and output file(s) for rendering
-func gatherTemplates(o *GomplateOpts) (templates []*tplate, err error) {
+func gatherTemplates(o *Config) (templates []*tplate, err error) {
// the arg-provided input string gets a special name
- if o.input != "" {
+ if o.Input != "" {
templates = []*tplate{{
name: "<arg>",
- contents: o.input,
+ contents: o.Input,
}}
}
// input dirs presume output dirs are set too
- if o.inputDir != "" {
- o.inputFiles, o.outputFiles, err = walkDir(o.inputDir, o.outputDir, o.excludeGlob)
+ if o.InputDir != "" {
+ o.InputFiles, o.OutputFiles, err = walkDir(o.InputDir, o.OutputDir, o.ExcludeGlob)
if err != nil {
return nil, err
}
}
if len(templates) == 0 {
- templates = make([]*tplate, len(o.inputFiles))
+ templates = make([]*tplate, len(o.InputFiles))
for i := range templates {
- templates[i] = &tplate{name: o.inputFiles[i]}
+ templates[i] = &tplate{name: o.InputFiles[i]}
}
}
- if len(o.outputFiles) == 0 {
- o.outputFiles = []string{"-"}
+ if len(o.OutputFiles) == 0 {
+ o.OutputFiles = []string{"-"}
}
for i, t := range templates {
@@ -88,7 +80,7 @@ func gatherTemplates(o *GomplateOpts) (templates []*tplate, err error) {
return nil, err
}
- if err := t.addTarget(o.outputFiles[i]); err != nil {
+ if err := t.addTarget(o.OutputFiles[i]); err != nil {
return nil, err
}
}
diff --git a/template_test.go b/template_test.go
index 5599acb4..66863b50 100644
--- a/template_test.go
+++ b/template_test.go
@@ -1,6 +1,6 @@
// +build !windows
-package main
+package gomplate
import (
"bytes"
@@ -153,30 +153,30 @@ func TestGatherTemplates(t *testing.T) {
afero.WriteFile(fs, "in/2", []byte("bar"), 0644)
afero.WriteFile(fs, "in/3", []byte("baz"), 0644)
- templates, err := gatherTemplates(&GomplateOpts{})
+ templates, err := gatherTemplates(&Config{})
assert.NoError(t, err)
assert.Len(t, templates, 0)
- templates, err = gatherTemplates(&GomplateOpts{
- input: "foo",
+ templates, err = gatherTemplates(&Config{
+ Input: "foo",
})
assert.NoError(t, err)
assert.Len(t, templates, 1)
assert.Equal(t, "foo", templates[0].contents)
assert.Equal(t, stdout, templates[0].target)
- templates, err = gatherTemplates(&GomplateOpts{
- inputFiles: []string{"foo"},
- outputFiles: []string{"out"},
+ templates, err = gatherTemplates(&Config{
+ InputFiles: []string{"foo"},
+ OutputFiles: []string{"out"},
})
assert.NoError(t, err)
assert.Len(t, templates, 1)
assert.Equal(t, "bar", templates[0].contents)
assert.NotEqual(t, stdout, templates[0].target)
- templates, err = gatherTemplates(&GomplateOpts{
- inputDir: "in",
- outputDir: "out",
+ templates, err = gatherTemplates(&Config{
+ InputDir: "in",
+ OutputDir: "out",
})
assert.NoError(t, err)
assert.Len(t, templates, 3)