@@ -30,6 +30,7 @@ type Command struct {
3030
3131// NewCommand creates a new command
3232// You can add option with variadic option argument
33+ // Default timeout is set to 30 minutes
3334//
3435// Example:
3536// c := cmd.NewCommand("echo hello", function (c *Command) {
@@ -45,7 +46,7 @@ type Command struct {
4546func NewCommand (cmd string , options ... func (* Command )) * Command {
4647 c := & Command {
4748 Command : cmd ,
48- Timeout : 1 * time .Minute ,
49+ Timeout : 30 * time .Minute ,
4950 executed : false ,
5051 Env : []string {},
5152 }
@@ -84,6 +85,11 @@ func WithTimeout(t time.Duration) func(c *Command) {
8485 }
8586}
8687
88+ // WithoutTimeout disables the timeout for the command
89+ func WithoutTimeout (c * Command ) {
90+ c .Timeout = 0
91+ }
92+
8793// AddEnv adds an environment variable to the command
8894// If a variable gets passed like ${VAR_NAME} the env variable will be read out by the current shell
8995func (c * Command ) AddEnv (key string , value string ) {
@@ -147,6 +153,12 @@ func (c *Command) Execute() error {
147153 cmd .Stderr = c .StderrWriter
148154 cmd .Dir = c .WorkingDir
149155
156+ // Create timer only if timeout was set > 0
157+ var timeoutChan = make (<- chan time.Time , 1 )
158+ if c .Timeout != 0 {
159+ timeoutChan = time .After (c .Timeout )
160+ }
161+
150162 err := cmd .Start ()
151163 if err != nil {
152164 return err
@@ -173,15 +185,14 @@ func (c *Command) Execute() error {
173185 break
174186 }
175187 c .exitCode = 0
176- case <- time . After ( c . Timeout ) :
188+ case <- timeoutChan :
177189 quit <- true
178190 if err := cmd .Process .Kill (); err != nil {
179191 return fmt .Errorf ("Timeout occurred and can not kill process with pid %v" , cmd .Process .Pid )
180192 }
181193 return fmt .Errorf ("Command timed out after %v" , c .Timeout )
182194 }
183195
184- //Remove leading and trailing whitespaces
185196 c .executed = true
186197
187198 return nil
0 commit comments