From ae869e4de72f99818d6fe52d725a0da6741046f0 Mon Sep 17 00:00:00 2001 From: jolheiser Date: Tue, 24 Nov 2020 00:05:47 -0600 Subject: [PATCH] Add true bools and better defaults, fix map/funcmap differences Signed-off-by: jolheiser --- registry/prompt.go | 21 +++++++++++++++++++-- registry/template_test.go | 13 +++++++++---- 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/registry/prompt.go b/registry/prompt.go index dfa47ce..62317c2 100644 --- a/registry/prompt.go +++ b/registry/prompt.go @@ -84,6 +84,18 @@ func prompt(dir string, defaults bool) (templatePrompts, error) { Options: t, Help: prompt.Help, } + case bool: + p = &survey.Confirm{ + Message: prompt.Message, + Default: t, + Help: prompt.Help, + } + case string: + p = &survey.Input{ + Message: prompt.Message, + Default: t, + Help: prompt.Help, + } default: p = &survey.Input{ Message: prompt.Message, @@ -103,6 +115,7 @@ func prompt(dir string, defaults bool) (templatePrompts, error) { type templatePrompts []templatePrompt +// ToMap converts a slice to templatePrompt into a suitable template context func (t templatePrompts) ToMap() map[string]interface{} { m := make(map[string]interface{}) for _, p := range t { @@ -115,25 +128,29 @@ func (t templatePrompts) ToMap() map[string]interface{} { return m } +// ToFuncMap converts a slice of templatePrompt into a suitable template.FuncMap func (t templatePrompts) ToFuncMap() template.FuncMap { m := make(map[string]interface{}) for k, v := range t.ToMap() { vv := v // Enclosure - m[k] = func() string { - return fmt.Sprintf("%v", vv) + m[k] = func() interface{} { + return vv } } return m } +// Len is for sort.Sort func (t templatePrompts) Len() int { return len(t) } +// Less is for sort.Sort func (t templatePrompts) Less(i, j int) bool { return t[i].Key > t[j].Key } +// Swap is for sort.Sort func (t templatePrompts) Swap(i, j int) { t[i], t[j] = t[j], t[i] } diff --git a/registry/template_test.go b/registry/template_test.go index 11f2d0f..019d3b1 100644 --- a/registry/template_test.go +++ b/registry/template_test.go @@ -8,14 +8,19 @@ import ( ) var ( - tmplContents = `{{title name}} {{.year}}` - tmplTemplate = `name = "john olheiser" + tmplContents = `{{title name}} {{if .bool}}{{.year}}{{end}}` + tmplTemplate = ` +name = "john olheiser" [year] -default = ${TMPL_TEST} +default = ${TMPL_TEST} # 2020 [package] -default = "pkg"` +default = "pkg" + +[bool] +default = true +` tmplGold = "John Olheiser 2020" tmplNewGold = "DO NOT OVERWRITE!" )