Expand the template.toml file (#7)

Expand the template.toml file

Signed-off-by: jolheiser <john.olheiser@gmail.com>

Co-authored-by: jolheiser <john.olheiser@gmail.com>
Reviewed-on: https://gitea.com/jolheiser/tmpl/pulls/7
Co-Authored-By: John Olheiser <john.olheiser@gmail.com>
Co-Committed-By: John Olheiser <john.olheiser@gmail.com>
pull/8/head
John Olheiser 2020-11-23 13:02:16 +08:00
parent 6dc75436fc
commit 6ffc50dc06
3 changed files with 22 additions and 3 deletions

View File

@ -11,6 +11,10 @@ A "valid" tmpl template only requires two things
## template.toml ## template.toml
**NOTE:** The template.toml file will be expanded, though not with the full power of the template itself.
The template.toml file will only expand environment variables with syntax `$USER` or `${USER}`.
For full documentation on the syntax, see [os.ExpandEnv](https://golang.org/pkg/os/#ExpandEnv).
```toml ```toml
# Key-value pairs can be simple # Key-value pairs can be simple
# The user will receive a basic prompt asking them to fill out the variable # The user will receive a basic prompt asking them to fill out the variable
@ -25,7 +29,7 @@ prompt = "The name of the author of this project"
# help would be extra information (generally seen by giving '?' to a prompt) # help would be extra information (generally seen by giving '?' to a prompt)
help = "Who will be primarily writing this project" help = "Who will be primarily writing this project"
# default is the "value" part of the simple pair. This could be a suggested value # default is the "value" part of the simple pair. This could be a suggested value
default = "me" default = "$USER"
``` ```
## template directory ## template directory

View File

@ -2,6 +2,7 @@ package registry
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"sort" "sort"
@ -25,7 +26,15 @@ func prompt(dir string, defaults bool) (templatePrompts, error) {
return nil, err return nil, err
} }
tree, err := toml.LoadFile(templatePath) templateBytes, err := ioutil.ReadFile(templatePath)
if err != nil {
return nil, err
}
// Expand the template with environment variables
templateContents := os.ExpandEnv(string(templateBytes))
tree, err := toml.Load(templateContents)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -12,7 +12,7 @@ var (
tmplTemplate = `name = "john olheiser" tmplTemplate = `name = "john olheiser"
[year] [year]
default = 2020 default = ${TMPL_TEST}
[package] [package]
default = "pkg"` default = "pkg"`
@ -21,6 +21,12 @@ default = "pkg"`
) )
func testExecute(t *testing.T) { func testExecute(t *testing.T) {
// Set environment variable
if err := os.Setenv("TMPL_TEST", "2020"); err != nil {
t.Logf("could not set environment: %v", err)
t.FailNow()
}
// Get template // Get template
tmpl, err := reg.GetTemplate("test") tmpl, err := reg.GetTemplate("test")
if err != nil { if err != nil {