Skip to content
This repository was archived by the owner on Apr 12, 2019. It is now read-only.

Commit 135704d

Browse files
typelessbkcsoft
authored andcommitted
Use exec.CommandContext for timeout control
1 parent 1b3739c commit 135704d

File tree

1 file changed

+6
-21
lines changed

1 file changed

+6
-21
lines changed

command.go

Lines changed: 6 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ package git
66

77
import (
88
"bytes"
9+
"context"
910
"fmt"
1011
"io"
1112
"os/exec"
@@ -58,34 +59,18 @@ func (c *Command) RunInDirTimeoutPipeline(timeout time.Duration, dir string, std
5859
log("%s: %v", dir, c)
5960
}
6061

61-
cmd := exec.Command(c.name, c.args...)
62+
ctx, cancel := context.WithTimeout(context.Background(), timeout)
63+
defer cancel()
64+
65+
cmd := exec.CommandContext(ctx, c.name, c.args...)
6266
cmd.Dir = dir
6367
cmd.Stdout = stdout
6468
cmd.Stderr = stderr
6569
if err := cmd.Start(); err != nil {
6670
return err
6771
}
6872

69-
done := make(chan error)
70-
go func() {
71-
done <- cmd.Wait()
72-
}()
73-
74-
var err error
75-
select {
76-
case <-time.After(timeout):
77-
if cmd.Process != nil && cmd.ProcessState != nil && !cmd.ProcessState.Exited() {
78-
if err := cmd.Process.Kill(); err != nil {
79-
return fmt.Errorf("fail to kill process: %v", err)
80-
}
81-
}
82-
83-
<-done
84-
return ErrExecTimeout{timeout}
85-
case err = <-done:
86-
}
87-
88-
return err
73+
return cmd.Wait()
8974
}
9075

9176
// RunInDirTimeout executes the command in given directory with given timeout,

0 commit comments

Comments
 (0)