jesseduffield / jesseduffield/lazydocker

Add `sprig` support for custom command templating

Open
#799 1 comment 0 reactions 0 assignees View on GitHub
enhancement
Dominant language
Go
Stars
52.8k
Forks
1.7k
PR merge metrics
No merged PRs in 30d

Description

The current state of custom command templating covers most use cases, but it does prove to be inadequate in some very specific scenarios, where additional functions would be nice to have in template expressions.

I came across this need when I tried adding this custom command for containers:

```yaml
customCommands:
containers:
- name: commit
shell: true
attach: false
command: 'docker commit {{ .Container.ID }} "{{ .Container.Name }}:{{ now | date "2006-01-02_15-04-05" }}"'
```

The `now` and `date` functions are provided by `sprig`, and the integration is fairly simple.

I would like if the templating logic included passing the template through `sprig` so we can have custom commands such as this.

The code change itself is very simple, since all templates are executed by the `utils.ApplyTemplate` function. We can use the `Template.Funcs` function to pass the funcmap provided by `sprig`:

```diff
func ApplyTemplate(str string, object interface{}) string {
var buf bytes.Buffer
- _ = template.Must(template.New("").Parse(str)).Execute(&buf, object)
+ _ = template.Must(template.New("").Funcs(sprig.FuncMap()).Parse(str)).Execute(&buf, object)
return buf.String()
}
```

Of course it might make sense to consider making this solution more extensible, in case of required future support for other templating engines/funcmaps, but for this basic use case, this works as expected.

A preview of this change can be found in my fork of this repository [here](https://github.com/eMarci/lazydocker), especially on [this](https://github.com/eMarci/lazydocker/commit/b5b8ad3200371bc85ca61442bc7f47c096cd7e5b) commit.

Manual testing confirms that this change is sufficient, its result can be seen in the custom command popup, where the templated command is showing up correctly. When using my previously provided example:

Image

---

I would be more than happy to work on this myself, if we can pin down the scope of the required changes (unless my fork is already sufficient in both quality and in the changes themselves). I would also happily accept any guidance/tips.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.