magefile / mage

a Make/rake-like dev tool using Go
https://magefile.org
Apache License 2.0
4.01k stars 250 forks source link

Feature: zsh completions and formatting target lists with gotemplates #488

Open kraashen opened 7 months ago

kraashen commented 7 months ago

Short description

This pull request implements following functionalities:

Detailed description

This pull request implements following new features:

Support listing mage targets in a given go-template format

Context: Autocompletion scripts can be wrapped around mage -l (list). This syntax has whitespaces and extra strings in the output, which need to be taken into account in parsing.

Idea: Implement a format handler similar to go list -format command that accepts go template language string. Calling then mage -l -format <template> will describe each target name-synopsis pair how they should be listed.

Implementation: mage -l -format "<template-string>" command with which custom formatted output can be created. This can be then easily'ish be parsed with shell scripts to provide completion scripts for targets. E.g. provided zsh shell script uses piped CSV as output and parses that with awk.

❯ mage -l -format "{{ .Name }}|{{ .Synopsis }}"
build|binaries for executables under ./cmd
buildForArmMac|Build for arm64 MacOS
buildForLinux|Build for x64 Linux
buildForMac|Build for amd64 MacOS
...

Generate completion scripts

Context: Many golang tools nowadays support creation and sourcing autocompletion scripts. To keep the implementation simple, mage could print the completion scripts which user can then decide how to either source or deploy to their environment.

Idea: Implement an extendable completion interface around which different shell formats can be extended.

Implementation: completions/completion.go package has been implemented with an interface which (at the moment) reads a zsh shell function script for autocompletion and prints this to the user. By default in zsh completion script, hashfast feature is disabled, but README guides users how to enable it, so hitting tab and getting results after initial compilation is much faster. Script also supports namespaces and all targets are sorted alphabetically.

# zsh completions script
mage -completion zsh

# Add following line to `.zshrc` for faster autocomplete after initial compilation:
echo "zstyle ':completions:*:mage:*' hash-fast true" >> ~/.zshrc

Demo

With dash+tab

image

With tab only

image

Enhancement ideas

Fixes #289