bluebrown / go-template-cli

render json, yaml & toml with go templates, from the command line
BSD Zero Clause License
30 stars 6 forks source link

If --name isn't specified and more than one template is parsed, a random template is selected as the default template #22

Closed mlabbe closed 3 months ago

mlabbe commented 3 months ago

in cli.go, the first template is extracted from a slice: https://github.com/bluebrown/go-template-cli/blob/main/cmd/tpl/cli.go#L263

Unfortunately, Go internally stores parsed templates as a map and only generates a slice at the last moment. Maps are not ordered. https://github.com/golang/go/blob/master/src/text/template/template.go?name=release#L149

Repeatedly running tpl results in non-deterministic template selection. There is no guarantee that it will be the first template that was parsed.

mlabbe commented 3 months ago

Here is a fix from my fork which may not work for you.

https://github.com/mlabbe/go-template-cli/commit/7e8e805ab7982e6cf9f01f8276861b0936dc8174

bluebrown commented 3 months ago

The entire function is about dealing with that problem and other ordering issues. The line you are highlighting is for when there is exactly 1 template left. Other things have priority. Its explained in the comment above. Perhaps you broke it in your fork. Its not a problem in this case. You are forced to use the name flag if it ambiguous, that was the design choice back then.

https://github.com/bluebrown/go-template-cli/blob/62cb3e205fca90239b0202cde26be70d76058a8a/cmd/tpl/cli.go#L266

This is also explained here https://github.com/bluebrown/go-template-cli?tab=readme-ov-file#templates