twpayne / chezmoi

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

Include external files from a template file? #2691

Closed Mixaz017 closed 1 year ago

Mixaz017 commented 1 year ago

What exactly are you trying to do?

I'm trying to include contents of a file from a remote repository, to use from a template file.

What have you tried so far?

I have read Include dotfiles from elsewhere, but from what I understand, .chezmoiexternal is for using external files as-is, and isn't for my use case. I also thought of using output template function to read output of programs like curl, but that isn't ideal since templates are executed often.

Where else have you checked for solutions?

bradenhilton commented 1 year ago

If the contents of the file do not change, a run_once_before_ script which gets the contents with curl and outputs it to a file which you then include is probably the best option.

If the contents of the file change, it may be better to use .chezmoiexternal to acquire it and keep it up to date, but there is no way to guarantee that the file will exist when the template is executed with this method.

Untested, but the following approach might be a good starting point:

{{ if not (stat "file/to/include") }}
{{   output "curl" "command" "here" }}
{{ else }}
{{   include "file/to/include" }}
{{ end }}

This way, the output is only run if the file to include does not exist. Once the external is downloaded, it should exist moving forward.

You could instead consider adding the file as a git submodule if applicable, then using it in include.

Mixaz017 commented 1 year ago

Thank you for a quick response @bradenhilton ! I should have stated that the remote content might change, so I want the remote file to be up to date like .chezmoiexternal.

there is no way to guarantee that the file will exist when the template is executed

I realized about this problem, so I think using git submodules is the best solution for my case so the content is guaranteed to exist.

Thank you for a helpful reply!