cmd/viewcore: reset the flag values before executing subcommands

after executing a subcommand with --help flag one time,
the subcommand will always show the help usage even it doesn't
have the help flag,
since the help flag is always true after it's set to true once.

as the following case, the `top` flag won't work after executing `histo --help` once.
```
(viewcore) histo --help
print histogram of heap memory use by Go type.
If N is specified, it will reports only the top N buckets
based on the total bytes.

Usage:
   histogram [flags]

Aliases:
  histogram, histo

Flags:
  -h, --help      help for histogram
      --top int   reports only top N entries if N>0
(viewcore) histo --top 10
print histogram of heap memory use by Go type.
If N is specified, it will reports only the top N buckets
based on the total bytes.

Usage:
   histogram [flags]

Aliases:
  histogram, histo

Flags:
  -h, --help      help for histogram
      --top int   reports only top N entries if N>0
```

The original `ResetFlags` just delete the flags of the `root` command.
https://pkg.go.dev/github.com/spf13/cobra#Command.ResetFlags
https://github.com/spf13/cobra/issues/1488

Change-Id: Ib0c663846fe64512d29636c0d70afa1ba924828a
GitHub-Last-Rev: 328b3b6ec9313a5df8991751bfef11d4c119e84d
GitHub-Pull-Request: golang/debug#8
Reviewed-on: https://go-review.googlesource.com/c/debug/+/372374
Trust: Heschi Kreinick <heschi@google.com>
Reviewed-by: Hyang-Ah Hana Kim <hyangah@gmail.com>
Trust: Hyang-Ah Hana Kim <hyangah@gmail.com>
diff --git a/cmd/viewcore/main.go b/cmd/viewcore/main.go
index ce3c469..26e2785 100644
--- a/cmd/viewcore/main.go
+++ b/cmd/viewcore/main.go
@@ -27,6 +27,7 @@
 
 	"github.com/chzyer/readline"
 	"github.com/spf13/cobra"
+	"github.com/spf13/pflag"
 	"golang.org/x/debug/internal/core"
 	"golang.org/x/debug/internal/gocore"
 )
@@ -253,6 +254,17 @@
 	err     error
 }{}
 
+func ResetSubCommandFlagValues(root *cobra.Command) {
+	for _, c := range root.Commands() {
+		c.Flags().VisitAll(func(f *pflag.Flag) {
+			if f.Changed {
+				f.Value.Set(f.DefValue)
+				f.Changed = false
+			}
+		})
+	}
+}
+
 // readCore reads corefile and returns core and gocore process states.
 func readCore() (*core.Process, *gocore.Process, error) {
 	cc := coreCache
@@ -345,7 +357,7 @@
 		}
 
 		err = capturePanic(func() {
-			root.ResetFlags()
+			ResetSubCommandFlagValues(root)
 			root.SetArgs(strings.Fields(l))
 			root.Execute()
 		})
diff --git a/go.mod b/go.mod
index 73cf21a..ff62e49 100644
--- a/go.mod
+++ b/go.mod
@@ -5,6 +5,7 @@
 require (
 	github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e
 	github.com/spf13/cobra v0.0.3
+	github.com/spf13/pflag v1.0.3
 	golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359
 )
 
@@ -12,5 +13,4 @@
 	github.com/chzyer/logex v1.1.10 // indirect
 	github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1 // indirect
 	github.com/inconshreveable/mousetrap v1.0.0 // indirect
-	github.com/spf13/pflag v1.0.3 // indirect
 )