Skip to content

Commit

Permalink
feat: Add plugin support
Browse files Browse the repository at this point in the history
  • Loading branch information
twpayne committed Sep 14, 2023
1 parent 63cda81 commit 5918296
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 1 deletion.
8 changes: 8 additions & 0 deletions assets/chezmoi.io/docs/reference/plugins.md
@@ -0,0 +1,8 @@
# Plugins

chezmoi supports plugins, similar to git.

If you run `chezmoi command` where *command* is not a builtin chezmoi command
then chezmoi will look for a binary called `chezmoi-command` in your `$PATH`. If
such a binary is found then chezmoi will execute it. Otherwise, chezmoi will
report an unknown command error.
1 change: 1 addition & 0 deletions assets/chezmoi.io/mkdocs.yml
Expand Up @@ -305,6 +305,7 @@ nav:
- reference/templates/secret-functions/index.md
- secret: reference/templates/secret-functions/secret.md
- secretJSON: reference/templates/secret-functions/secretJSON.md
- Plugins: reference/plugins.md
- Release history: reference/release-history.md
- Developer:
- Developing locally: developer/developing-locally.md
Expand Down
14 changes: 13 additions & 1 deletion internal/cmd/cmd.go
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"os"
"os/exec"
"regexp"
"runtime/debug"
"strconv"
Expand Down Expand Up @@ -105,7 +106,18 @@ func (v VersionInfo) MarshalZerologObject(e *zerolog.Event) {

// Main runs chezmoi and returns an exit code.
func Main(versionInfo VersionInfo, args []string) int {
if err := runMain(versionInfo, args); err != nil {
err := runMain(versionInfo, args)
if err != nil && strings.Contains(err.Error(), "unknown command") &&
len(args) > 0 { // FIXME find a better way of detecting unknown commands
if name, err2 := exec.LookPath("chezmoi-" + args[0]); err2 == nil {
cmd := exec.Command(name, args[1:]...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
}
}
if err != nil {
var errExitCode chezmoi.ExitCodeError
if errors.As(err, &errExitCode) {
return int(errExitCode)
Expand Down
16 changes: 16 additions & 0 deletions internal/cmd/testdata/scripts/plugin.txtar
@@ -0,0 +1,16 @@
[unix] chmod 755 bin/chezmoi-plugin

# test that chezmoi returns unknown command errors for unknown commands
! exec chezmoi unknown
stderr 'unknown command'

# test that chezmoi executes plugins
exec chezmoi plugin
stdout hello

-- bin/chezmoi-plugin --
#!/bin/sh

echo hello
-- bin/chezmoi-plugin.cmd --
@echo hello

0 comments on commit 5918296

Please sign in to comment.