twpayne / chezmoi

Manage your dotfiles across multiple diverse machines, securely.
https://www.chezmoi.io/
MIT License
13.27k stars 493 forks source link

Feature: Add math template functions (esp. multiplication for scaling) #887

Closed webarnes closed 4 years ago

webarnes commented 4 years ago

Go's text/template doesn't do math. However, you can define functions for use in templates. Chezmoi should define some functions for basic math.

Use Case

I suspect this is a common use case: sharing configuration between computers with different DPIs. You need to scale values by a usually fixed amount between computers. For example, my polybar is 25px on my standard DPI desktop monitor but 50px on my HiDPI laptop monitor. To achieve this I have an entry in my config.yaml like data: polybar: height: 50 (line breaks removed).

Instead, if Chezmoi defined a function like multiply, I could define a variable data: scale: 2 and use it across all my templates like height = {{ multiply 25 .scale }} or font = "mono {{ multiply 12 .scale }}" rather than having config variables for each value that requires scaling.

Example: https://play.golang.org/p/ro4K9-4HCgo (this is pretty basic; I don't know Go; I suspect it might require a few more lines to work with floats)

zb140 commented 4 years ago

chezmoi templates can use the Sprig template functions (full list here), which includes a lot of super useful stuff. There are several math functions including multiply (called mul).

For example:

$ echo "{{ mul 3 4 }}" | chezmoi execute-template
12

Unfortunately it does appear that they are limited to integers, though the docs do say that float support will be added "in the future".

twpayne commented 4 years ago

Thanks for the suggestion @webarnes, and thank you for the fast and accurate response @zb140 :)

@webarnes, do you need floating point support?

zb140 commented 4 years ago

Always happy to help when I can :-)

I did a little digging around in the Sprig repo and found this PR for floating point support, but unfortunately it hasn't seen much activity lately: https://github.com/Masterminds/sprig/pull/181

webarnes commented 4 years ago

Thank you. The Sprig functions cover my use case. I missed those. I can use integers everywhere (and scale by 2 instead of 0.5).

From my perspective, the issue is closed, but I'm sure that others might have a use for floats (11.5pt fonts perhaps).

twpayne commented 4 years ago

Let's add floating support when it's definitely needed. I'll close this for now.