Browse Source

Flags support to define templates

master
Amelia A 2 months ago
parent
commit
e6ae610d2d
Signed by: amy GPG Key ID: 98E879BC3B6E1BF8
2 changed files with 26 additions and 9 deletions
  1. +23
    -8
      main.go
  2. +3
    -1
      main_test.go

+ 23
- 8
main.go View File

@ -2,6 +2,7 @@ package main
import (
"errors"
"flag"
"fmt"
"io"
"os"
@ -11,8 +12,7 @@ import (
const (
templateGlob = "*.tmpl"
exitFail = 1
usage = `Quick Usage: fvv <template definition name>
usageFooter = `
Fusozay Var Var is a CLI application for quickly rendering out text templates.
I often write outfit and character descriptions that reuses a lot of elements.
This allows me to DRY up my descriptions and still quickly get results.
@ -20,11 +20,10 @@ This allows me to DRY up my descriptions and still quickly get results.
Template requirements:
- All of the templates must be valid golang templates.
- They must not require any variables to be passed in.
- All templates must have the '.tmpl' extension. All other files ignored.
- The template you want to render must be "named"
https://golang.org/pkg/text/template/#hdr-Nested_template_definitions
Version 1.0.0
Version 1.2.0
`
)
@ -36,16 +35,32 @@ func main() {
}
func run(args []string, fileGlob string, stdout io.Writer) error {
if len(args) < 2 {
return errors.New(usage)
flags := flag.NewFlagSet(args[0], flag.ContinueOnError)
flags.Usage = func() {
fmt.Fprintf(flags.Output(), "Quick Usage: %s <template definition name>\n", args[0])
flags.PrintDefaults()
fmt.Fprint(flags.Output(), usageFooter)
}
var (
glob = flags.String("t", fileGlob, "glob to use to find templates")
)
if err := flags.Parse(args[1:]); err != nil {
return err
}
tmpl, err := template.ParseGlob(fileGlob)
if flags.NArg() != 1 {
flags.Usage()
return errors.New("template definition missing")
}
nonFlagArg := flags.Args()[0]
tmpl, err := template.ParseGlob(*glob)
if err != nil {
return fmt.Errorf("checking for templates: %v", err)
}
err = tmpl.ExecuteTemplate(stdout, args[1], "no data needed")
err = tmpl.ExecuteTemplate(stdout, nonFlagArg, "no data needed")
if err != nil {
return fmt.Errorf("executing template %s: %v", args[1], err)
}


+ 3
- 1
main_test.go View File

@ -5,7 +5,7 @@ import (
"testing"
)
func Test_run(t *testing.T) {
func TestRun(t *testing.T) {
type args struct {
args []string
fileGlob string
@ -20,6 +20,8 @@ func Test_run(t *testing.T) {
{"missing template", args{[]string{"fvv", "t3"}, "*.tmpl"}, "", true},
{"definition does not exist", args{[]string{"fvv", "t20"}, "test_files/*.tmpl"}, "", true},
{"happy path", args{[]string{"fvv", "T3"}, "test_files/*.tmpl"}, "ONE\nStandard stuff\nTWO", false},
{"flag template", args{[]string{"fvv", "-t", "test_files/*.tmpl", "T3"}, "*.tmpl"}, "ONE\nStandard stuff\nTWO", false},
{"bad flag", args{[]string{"fvv", "-z", "test_files/*.tmpl"}, ""}, "", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {


Loading…
Cancel
Save