Switch from kingpin to cobra

This enables easier use of sub-commands for flexibility
This commit is contained in:
2018-07-08 02:57:33 +01:00
parent 6883984950
commit 85cf2ac225
109 changed files with 9858 additions and 15045 deletions

19
cmd/helpers.go Normal file
View File

@@ -0,0 +1,19 @@
package cmd
import (
"fmt"
"os"
"github.com/spf13/cobra"
)
func usage_er(cmd *cobra.Command, msg interface{}) {
cmd.Usage()
fmt.Println("")
er(msg)
}
func er(msg interface{}) {
fmt.Println("ERROR:", msg)
os.Exit(1)
}

66
cmd/leak.go Normal file
View File

@@ -0,0 +1,66 @@
package cmd
import (
"fmt"
"github.com/jimeh/rbheapleak/leak"
"github.com/spf13/cobra"
)
var leakOpts = struct {
Format string
Verbose bool
}{}
// leakCmd represents the leak command
var leakCmd = &cobra.Command{
Use: "leak [flags] <dump-A> <dump-B> <dump-C>",
Short: "Find objects which are likely leaked memory.",
Long: `Find objects which are likely leaked memory.
Compares the objects in three different dumps (A, B, C), to identify which
objects are present in both B and C, and not present in A.`,
// Args: cobra.ExactArgs(3),
Run: func(cmd *cobra.Command, args []string) {
if len(args) != 3 {
usage_er(cmd, fmt.Sprintf("requires 3 args, received %d", len(args)))
}
finder := leak.NewFinder(args[0], args[1], args[2])
finder.Verbose = leakOpts.Verbose
err := finder.Process()
if err != nil {
er(err)
}
switch leakOpts.Format {
case "hex":
finder.PrintLeakedAddresses()
case "full":
finder.PrintLeakedObjects()
default:
usage_er(
cmd,
fmt.Sprintf("\"%s\" is not a valid format", leakOpts.Format),
)
}
},
}
func init() {
rootCmd.AddCommand(leakCmd)
leakCmd.PersistentFlags().StringVarP(
&leakOpts.Format,
"format", "f", "hex",
"Output format: \"hex\" / \"full\"",
)
leakCmd.PersistentFlags().BoolVarP(
&leakOpts.Verbose,
"verbose", "v", false,
"print verbose information",
)
}

62
cmd/root.go Normal file
View File

@@ -0,0 +1,62 @@
package cmd
import (
"bytes"
"fmt"
"os"
"runtime"
"strings"
"github.com/spf13/cobra"
)
// BuildInfo represents info collected as build-time.
type BuildInfo struct {
Version string
Commit string
Date string
}
var rootCmd = &cobra.Command{
Use: "rbheapleak",
Short: "rbheapleak analyzes ObjectSpace dumps from Ruby processes.",
SilenceUsage: true,
SilenceErrors: true,
}
func versionString(info *BuildInfo) string {
var buffer bytes.Buffer
var meta []string
buffer.WriteString(info.Version)
if info.Commit != "unknown" {
meta = append(meta, info.Commit)
}
meta = append(meta, runtime.Version())
if info.Date != "unknown" {
meta = append(meta, info.Date)
}
if len(meta) > 0 {
buffer.WriteString(fmt.Sprintf(" (%s)", strings.Join(meta, ", ")))
}
return buffer.String()
}
func Execute(info *BuildInfo) {
rootCmd.Version = versionString(info)
rootCmd.SetVersionTemplate("{{.Use}} {{.Version}}\n")
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func init() {
rootCmd.Flags().BoolP("version", "v", false, "Show version.")
}