-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #8 from rebuy-de/context-support
add context support
- Loading branch information
Showing
2 changed files
with
94 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
package executil | ||
|
||
import ( | ||
"context" | ||
"os/exec" | ||
"strings" | ||
"syscall" | ||
|
||
"github.com/pkg/errors" | ||
"github.com/sirupsen/logrus" | ||
) | ||
|
||
// Run starts the specified command and waits for it to complete. | ||
// | ||
// The difference to Run from exec.CommandContext is that it sends an interrupt | ||
// instead of a kill, which gives the process time for a graceful shutdown. | ||
func Run(ctx context.Context, cmd *exec.Cmd) error { | ||
commandline := strings.Join(cmd.Args, " ") | ||
logrus.WithFields(logrus.Fields{ | ||
"Args": cmd.Args, | ||
"Dir": cmd.Dir, | ||
}).Debugf("running command `%s`", commandline) | ||
|
||
err := cmd.Start() | ||
if err != nil { | ||
return errors.WithStack(err) | ||
} | ||
|
||
done := make(chan struct{}, 1) | ||
defer close(done) | ||
|
||
go func() { | ||
select { | ||
case <-ctx.Done(): | ||
logrus.Debugf("sending interrupt signal to `%s`", commandline) | ||
cmd.Process.Signal(syscall.SIGINT) | ||
case <-done: | ||
// This mean wait() already exited and we can stop to wait for the | ||
// cancelation. | ||
} | ||
}() | ||
|
||
return errors.Wrapf(cmd.Wait(), "failed to run `%s`", commandline) | ||
} |