mirror of
https://github.com/garethgeorge/backrest.git
synced 2025-12-14 09:35:41 +00:00
41 lines
981 B
Go
41 lines
981 B
Go
package hook
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"os/exec"
|
|
"strings"
|
|
|
|
v1 "github.com/garethgeorge/backrest/gen/go/v1"
|
|
)
|
|
|
|
func (h *Hook) doCommand(cmd *v1.Hook_ActionCommand, vars HookVars, output io.Writer) error {
|
|
command, err := h.renderTemplate(cmd.ActionCommand.Command, vars)
|
|
if err != nil {
|
|
return fmt.Errorf("template rendering: %w", err)
|
|
}
|
|
|
|
// Parse out the shell to use if a #! prefix is present
|
|
shell := "sh"
|
|
if len(command) > 2 && command[0:2] == "#!" {
|
|
nextLine := strings.Index(command, "\n")
|
|
if nextLine == -1 {
|
|
nextLine = len(command)
|
|
}
|
|
shell = strings.Trim(command[2:nextLine], " ")
|
|
command = command[nextLine+1:]
|
|
}
|
|
|
|
output.Write([]byte(fmt.Sprintf("------- script -------\n#! %v\n%v\n", shell, command)))
|
|
output.Write([]byte("------- output -------\n"))
|
|
|
|
// Run the command in the specified shell
|
|
execCmd := exec.Command(shell)
|
|
execCmd.Stdin = strings.NewReader(command)
|
|
|
|
execCmd.Stderr = output
|
|
execCmd.Stdout = output
|
|
|
|
return execCmd.Run()
|
|
}
|