baur icon indicating copy to clipboard operation
baur copied to clipboard

Add a --timeout parameter

Open fho opened this issue 5 years ago • 0 comments

Add a --timeout parameter that causes the executed command to exit with an error when it's exceeded.

Requires: https://github.com/simplesurance/baur/issues/158

Diff to add a timeout parameter for all commands:

diff --git a/internal/command/root.go b/internal/command/root.go
index 787e9e8..6f382eb 100644
--- a/internal/command/root.go
+++ b/internal/command/root.go
@@ -6,6 +6,7 @@ import (
        "os"
        "path/filepath"
        "runtime/pprof"
+       "time"
 
        "github.com/fatih/color"
        "github.com/spf13/cobra"
@@ -25,6 +26,7 @@ var rootCmd = &cobra.Command{
 var verboseFlag bool
 var cpuProfilingFlag bool
 var noColorFlag bool
+var timeoutFlag time.Duration
 
 var defCPUProfFile = filepath.Join(os.TempDir(), "baur-cpu.prof")
 
@@ -53,6 +55,11 @@ func initSb(_ *cobra.Command, _ []string) {
                        log.Fatalln(err)
                }
        }
+
+       if timeoutFlag != 0 {
+               // nolint:govet // loosing the cancelFn is fine here, need to run it
+               ctx, _ = context.WithTimeout(ctx, timeoutFlag)
+       }
 }
 
 // Execute parses commandline flags and execute their actions
@@ -66,6 +73,8 @@ func Execute() {
        rootCmd.PersistentFlags().BoolVar(&cpuProfilingFlag, "cpu-prof", false,
                fmt.Sprintf("enable cpu profiling, result is written to %q", defCPUProfFile))
        rootCmd.PersistentFlags().BoolVar(&noColorFlag, "no-color", false, "disable color output")
+       rootCmd.PersistentFlags().DurationVar(&timeoutFlag, "timeout", 0,
+               "Time limit for the command, when it is exceeded baur exits with an error")
 
        if err := rootCmd.Execute(); err != nil {
                log.Fatalln(err)

fho avatar Jun 25 '20 16:06 fho