From ac7253a1736413f0a618f28559ce5034c71e61f6 Mon Sep 17 00:00:00 2001 From: Mahe Tardy Date: Mon, 24 Jul 2023 10:36:39 +0000 Subject: [PATCH] Fix process command crash when provided with no args Use cobra.MinimumNArgs to require at least one argument and handle errors in processing the arguments. Improve the use help string. --- internal/cmd/process.go | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/internal/cmd/process.go b/internal/cmd/process.go index bb5d49b..a323a60 100644 --- a/internal/cmd/process.go +++ b/internal/cmd/process.go @@ -19,31 +19,38 @@ import ( // ProcessCommand displays information about a Go process. func ProcessCommand() *cobra.Command { return &cobra.Command{ - Use: "process", + Use: "process [period]", Aliases: []string{"pid", "proc"}, Short: "Prints information about a Go process.", + Args: cobra.MinimumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - ProcessInfo(args) - return nil + return ProcessInfo(args) }, } } // ProcessInfo takes arguments starting with pid|:addr and grabs all kinds of // useful Go process information. -func ProcessInfo(args []string) { +func ProcessInfo(args []string) error { pid, err := strconv.Atoi(args[0]) + if err != nil { + return fmt.Errorf("error parsing the first argument: %w", err) + } var period time.Duration if len(args) >= 2 { period, err = time.ParseDuration(args[1]) if err != nil { - secs, _ := strconv.Atoi(args[1]) + secs, err := strconv.Atoi(args[1]) + if err != nil { + return fmt.Errorf("error parsing the second argument: %w", err) + } period = time.Duration(secs) * time.Second } } processInfo(pid, period) + return nil } func processInfo(pid int, period time.Duration) {