Skip to content

Commit

Permalink
Add split utility func
Browse files Browse the repository at this point in the history
  • Loading branch information
Owen Smith committed Nov 29, 2016
1 parent ef6a803 commit ab65bb0
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
20 changes: 20 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package main

import "bytes"

import "errors"
import "io"
import "os"
import "text/template"
Expand All @@ -23,13 +25,31 @@ func ReadEnvVars(rawEnv []string) (environ map[string]string) {

func WriteTemplateToStream(tplSource string, environ map[string]string, outStream io.Writer) {
tpl := template.New("_root_")
tpl.Funcs(template.FuncMap{
"split": TplSplitStr,
})
_, err := tpl.Parse(tplSource)
if err != nil {
panic(err)
}
tpl.Execute(outStream, environ)
}

func TplSplitStr(args ...interface{}) ([]string, error) {
rawValue := args[0].(string)
sep := args[1].(string)
limit := -1
if len(args) > 2 {
parsedLimit, ok := args[2].(int)
if !ok {
err := errors.New("Limit parameter (3rd)is not integer")
return nil, err
}
limit = parsedLimit
}
return strings.SplitN(rawValue, sep, limit), nil
}

func main() {
WriteTemplateToStream(ReadTemplate(os.Stdin), ReadEnvVars(os.Environ()), os.Stdout)
}
23 changes: 21 additions & 2 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ func ExampleReadEnvVars() {
v := envMap[k]
fmt.Printf("key '%s' has value '%s'\n", k, v)
}
// Output: key 'a' has value 'A'
// Output:
// key 'a' has value 'A'
// key 'b' has value 'b=B'
// key 'empty' has value ''
// key 'spaces' has value ' '
Expand All @@ -26,6 +27,24 @@ func ExampleWriteTemplateToStream_basic() {
WriteTemplateToStream("Hello, {{ .TARGET_PLANET }}!\n", env, buf)
WriteTemplateToStream("{{ if not .BEGIN_INVASION}}We mean you no{{ else }}Prepare yourselves for{{ end }} harm.", env, buf)
fmt.Println(buf.String())
// Output: Hello, earth!
// Output:
// Hello, earth!
// We mean you no harm.
}

func ExampleWriteTemplateToStream_strSplit() {
buf := new(bytes.Buffer)
env := map[string]string{
"PARTS": "a,b,c",
}
// WriteTemplateToStream("{{ split .PARTS ',' }}", env, buf)
WriteTemplateToStream("{{ range $i, $v := split .PARTS \",\" }}List 1 item {{$i}} has value {{$v}}\n{{end}}", env, buf)
WriteTemplateToStream("{{ range $i, $v := split .PARTS \",\" 2 }}List 2 item {{$i}} has value {{$v}}\n{{end}}", env, buf)
fmt.Println(buf.String())
// Output:
// List 1 item 0 has value a
// List 1 item 1 has value b
// List 1 item 2 has value c
// List 2 item 0 has value a
// List 2 item 1 has value b,c
}

0 comments on commit ab65bb0

Please sign in to comment.