twpayne / chezmoi

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

Preconditions before generating template-based files #3084

Closed x80486 closed 1 year ago

x80486 commented 1 year ago

Description

I would like to be able to be able to run some checks in a way that's not invasive to fail (or not) the generated file based on a given template.

For instance, I have a config file for Git with a user section that's similar to this:

...

[user]
  email = "{{ .git.gitlab.email }}"
  name = "{{ .git.gitlab.name }}"
  signingKey = "{{ .chezmoi.homeDir }}/.ssh/gitlab-personal.pub"

So if I try to generate the file based on this template, it should fail because {{ .chezmoi.homeDir }}/.ssh/gitlab-personal.pub is not present (if that's the case).

Describe Solution(s) You Would Like

Describe Alternatives You Have Considered

N/A

halostatue commented 1 year ago

I think what would be missing here shouldn’t be too hard to add, and that’s an unconditional "halt" template function.

It might work as something like:

...

[user]
  email = "{{ .git.gitlab.email }}"
  name = "{{ .git.gitlab.name }}"
{{- if stat (joinPath .chezmoi.homeDir ".ssh/gitlab-personal.pub")) }}
  signingKey = "{{ .chezmoi.homeDir }}/.ssh/gitlab-personal.pub"
{{ else }}
  {{ halt "Missing ~/.ssh/gitlab-personal.pub" }}
{{ end }}

This is imperfect and may be dangerous for normal execution cases, but the idea could work.

twpayne commented 1 year ago

You can use the existing fail template function for this.

halostatue commented 1 year ago

Good to know and good to know that such a template function already exists.