Skip to content

Commit

Permalink
internal/pwru: Implement a proper help function
Browse files Browse the repository at this point in the history
With "./pwru --help" or "./pwru -h", pwru:

  1. displays the help message,
  2. prints "pflag: help requested",
  3. exits with error code 2.

Steps 2 and 3 are not expected, the interactive help should return 0
without displaying an error message. This is because of how
pflags.ParseAll() works. From its documentation [0]: "The return value
will be ErrHelp if -help was set but not defined."

Let's implement a dedicated function for displaying the help message
(reusing pflags.Usage() and what we had in pwru already), and call it
when users pass --help or -h to avoid this error and non-zero return
value.

[0] https://pkg.go.dev/github.com/spf13/pflag#FlagSet.ParseAll

Signed-off-by: Quentin Monnet <[email protected]>
  • Loading branch information
qmonnet authored and brb committed Dec 20, 2023
1 parent 9f5a386 commit 9b6449a
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ Usage: pwru [options] [pcap-filter]
--filter-netns string filter netns ("/proc/<pid>/ns/net", "inode:<inode>")
--filter-trace-tc trace TC bpf progs
--filter-track-skb trace a packet even if it does not match given filters (e.g., after NAT or tunnel decapsulation)
-h, --help display this message and exit
--kernel-btf string specify kernel BTF file
--kmods strings list of kernel modules names to attach to
--output-file string write traces to file
Expand Down
6 changes: 6 additions & 0 deletions internal/pwru/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const (

type Flags struct {
ShowVersion bool
ShowHelp bool

KernelBTF string

Expand Down Expand Up @@ -49,6 +50,7 @@ type Flags struct {
}

func (f *Flags) SetFlags() {
flag.BoolVarP(&f.ShowHelp, "help", "h", false, "display this message and exit")
flag.BoolVar(&f.ShowVersion, "version", false, "show pwru version and exit")
flag.StringVar(&f.KernelBTF, "kernel-btf", "", "specify kernel BTF file")
flag.StringSliceVar(&f.KMods, "kmods", nil, "list of kernel modules names to attach to")
Expand Down Expand Up @@ -82,6 +84,10 @@ func (f *Flags) SetFlags() {
}
}

func (f *Flags) PrintHelp() {
flag.Usage()
}

func (f *Flags) Parse() {
flag.Parse()
f.FilterPcap = strings.Join(flag.Args(), " ")
Expand Down
4 changes: 4 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ func main() {
flags.SetFlags()
flags.Parse()

if flags.ShowHelp {
flags.PrintHelp()
os.Exit(0)
}
if flags.ShowVersion {
fmt.Printf("pwru %s\n", pwru.Version)
os.Exit(0)
Expand Down

0 comments on commit 9b6449a

Please sign in to comment.