implemented OnKillRun

This commit is contained in:
decanus 2023-02-16 16:44:14 +01:00
parent a516d4132c
commit 9b6f7e82fd
No known key found for this signature in database
GPG key ID: 3730AAF5D6589867

View file

@ -23,9 +23,11 @@ import (
"fmt" "fmt"
"io" "io"
"os" "os"
"os/signal"
"path/filepath" "path/filepath"
"sort" "sort"
"strings" "strings"
"syscall"
flag "github.com/spf13/pflag" flag "github.com/spf13/pflag"
) )
@ -136,6 +138,8 @@ type Command struct {
PersistentPostRun func(cmd *Command, args []string) PersistentPostRun func(cmd *Command, args []string)
// PersistentPostRunE: PersistentPostRun but returns an error. // PersistentPostRunE: PersistentPostRun but returns an error.
PersistentPostRunE func(cmd *Command, args []string) error PersistentPostRunE func(cmd *Command, args []string) error
// OnKillRun: run if a commands execution is exited
OnKillRun func(cmd *Command, args []string)
// groups for subcommands // groups for subcommands
commandgroups []*Group commandgroups []*Group
@ -906,6 +910,23 @@ func (c *Command) execute(a []string) (err error) {
argWoFlags = a argWoFlags = a
} }
if c.OnKillRun != nil {
sigchan := make(chan os.Signal)
signal.Notify(
sigchan,
syscall.SIGINT,
syscall.SIGKILL,
syscall.SIGTERM,
syscall.SIGQUIT,
)
go func() {
_ = <-sigchan
c.OnKillRun(c, argWoFlags)
}()
}
if err := c.ValidateArgs(argWoFlags); err != nil { if err := c.ValidateArgs(argWoFlags); err != nil {
return err return err
} }