@@ -65,14 +65,25 @@ func NewCommand(cmd string, options ...func(*Command)) *Command {
6565//
6666// Example:
6767//
68- // c := cmd.NewCommand("echo hello", cmd.WithStandardStreams)
69- // c.Execute()
68+ // c := cmd.NewCommand("echo hello", cmd.WithStandardStreams)
69+ // c.Execute()
7070//
7171func WithStandardStreams (c * Command ) {
7272 c .StdoutWriter = os .Stdout
7373 c .StderrWriter = os .Stderr
7474}
7575
76+ // WithTimeout sets the timeout of the command
77+ //
78+ // Example:
79+ // cmd.NewCommand("sleep 10;", cmd.WithTimeout(500))
80+ //
81+ func WithTimeout (t time.Duration ) func (c * Command ) {
82+ return func (c * Command ) {
83+ c .Timeout = t
84+ }
85+ }
86+
7687// AddEnv adds an environment variable to the command
7788// If a variable gets passed like ${VAR_NAME} the env variable will be read out by the current shell
7889func (c * Command ) AddEnv (key string , value string ) {
@@ -97,27 +108,6 @@ func parseEnvVariableFromShell(val string) []string {
97108 return matches
98109}
99110
100- //SetTimeoutMS sets the timeout in milliseconds
101- func (c * Command ) SetTimeoutMS (ms int ) {
102- if ms == 0 {
103- c .Timeout = 1 * time .Minute
104- return
105- }
106- c .Timeout = time .Duration (ms ) * time .Millisecond
107- }
108-
109- // SetTimeout sets the timeout given a time unit
110- // Example: SetTimeout("100s") sets the timeout to 100 seconds
111- func (c * Command ) SetTimeout (timeout string ) error {
112- d , err := time .ParseDuration (timeout )
113- if err != nil {
114- return err
115- }
116-
117- c .Timeout = d
118- return nil
119- }
120-
121111//Stdout returns the output to stdout
122112func (c * Command ) Stdout () string {
123113 c .isExecuted ("Stdout" )
@@ -162,9 +152,18 @@ func (c *Command) Execute() error {
162152 return err
163153 }
164154
165- done := make (chan error )
155+ done := make (chan error , 1 )
156+ defer close (done )
157+ quit := make (chan bool , 1 )
158+ defer close (quit )
159+
166160 go func () {
167- done <- cmd .Wait ()
161+ select {
162+ case <- quit :
163+ return
164+ case done <- cmd .Wait ():
165+ return
166+ }
168167 }()
169168
170169 select {
@@ -175,6 +174,7 @@ func (c *Command) Execute() error {
175174 }
176175 c .exitCode = 0
177176 case <- time .After (c .Timeout ):
177+ quit <- true
178178 if err := cmd .Process .Kill (); err != nil {
179179 return fmt .Errorf ("Timeout occurred and can not kill process with pid %v" , cmd .Process .Pid )
180180 }
0 commit comments