fix multi template file rendering

This commit is contained in:
Diego Fernando Carrión 2023-10-13 15:04:13 +02:00
parent b0a3501b00
commit 8067b10b0b
Signed by: CRThaze
GPG Key ID: 0F647F8A6A3AF588

40
main.go
View File

@ -74,13 +74,19 @@ func (v *valSlice) Set(value string) error {
}
var flags struct {
valuesFiles valFileSlice
values valSlice
valuesFiles valFileSlice
values valSlice
outputDelimiter string
}
func init() {
flag.Var(&flags.values, "set", "")
flag.Var(&flags.valuesFiles, "f", "")
flag.StringVar(
&flags.outputDelimiter,
"d", "---",
"Output delimiter between template files rendered",
)
flag.Parse()
}
@ -129,9 +135,17 @@ func expandFiles(files []string) (expFiles []string) {
filepath.WalkDir(path, func(path string, d fs.DirEntry, err error) error {
if err != nil {
fmt.Fprintf(os.Stderr, "WARN: %+v", err)
return err
return nil
}
if d.IsDir() {
// Don't recurse hidden directories.
if d.Name() != "." && strings.HasPrefix(d.Name(), ".") {
return filepath.SkipDir
}
return nil
}
// Skip hidden files.
if strings.HasPrefix(d.Name(), ".") {
return nil
}
abs, err := filepath.Abs(path)
@ -183,6 +197,9 @@ func main() {
var err error
tpl := template.New("base").Funcs(sprig.FuncMap())
values := mergeValues()
// fmt.Fprintf(os.Stderr, "%+v\n", values)
if len(flag.Args()) == 0 {
// With no provided arguments read from STDIN if anything is immediately available through it.
// otherwise print the usage and exit.
@ -211,11 +228,18 @@ func main() {
tpl, err = tpl.Parse(string(data))
checkErr(err)
} else {
// Otherwise use the provided files/directories for templates to render.
// fmt.Fprintf(os.Stderr, "%+v\n", expandFiles(flag.Args()))
tpl, err = tpl.ParseFiles(expandFiles(flag.Args())...)
tplFiles := expandFiles(flag.Args())
// Otherwise use the provided tplFiles/directories for templates to render.
// fmt.Fprintf(os.Stderr, "%+v\n", tplFiles)
tpl, err = template.ParseFiles(tplFiles...)
checkErr(err)
for i, file := range tplFiles {
if i > 0 {
fmt.Println(flags.outputDelimiter)
}
checkErr(tpl.ExecuteTemplate(os.Stdout, filepath.Base(file), values))
}
return
}
// fmt.Fprintf(os.Stderr, "%+v\n", mergeValues())
tpl.Execute(os.Stdout, mergeValues())
checkErr(tpl.Execute(os.Stdout, values))
}