github.com/pyroscope-io/pyroscope@v0.37.3-0.20230725203016-5f6947968bd0/cmd/pyroscope/command/root.go (about)

     1  package command
     2  
     3  import (
     4  	"fmt"
     5  	"runtime"
     6  
     7  	"github.com/sirupsen/logrus"
     8  	"github.com/spf13/cobra"
     9  
    10  	"github.com/pyroscope-io/pyroscope/pkg/cli"
    11  	"github.com/pyroscope-io/pyroscope/pkg/config"
    12  )
    13  
    14  func Execute() error {
    15  	var cfg config.Config
    16  	rootCmd := newRootCmd(&cfg)
    17  	rootCmd.SilenceErrors = true
    18  
    19  	subcommands := []*cobra.Command{
    20  		newAdhocCmd(&cfg.Adhoc),
    21  		newAdminCmd(&cfg.Admin),
    22  		newAgentCmd(&cfg.Agent),
    23  		newConnectCmd(&cfg.Connect),
    24  		newEBPFSpyCmd(&cfg.EBPF),
    25  		newConvertCmd(&cfg.Convert),
    26  		newDbManagerCmd(&config.CombinedDbManager{DbManager: &cfg.DbManager, Server: &cfg.Server}),
    27  		newExecCmd(&cfg.Exec),
    28  		newServerCmd(&cfg.Server),
    29  		newVersionCmd(),
    30  		newCiCmd(&cfg.CI),
    31  	}
    32  
    33  	for _, c := range subcommands {
    34  		if c == nil {
    35  			continue
    36  		}
    37  		addHelpSubcommand(c)
    38  		c.HasHelpSubCommands()
    39  		rootCmd.AddCommand(c)
    40  	}
    41  
    42  	logrus.SetReportCaller(true)
    43  	logrus.SetFormatter(&logrus.TextFormatter{
    44  		TimestampFormat: "2006-01-02T15:04:05.000000",
    45  		FullTimestamp:   true,
    46  		CallerPrettyfier: func(f *runtime.Frame) (string, string) {
    47  			filename := f.File
    48  			if len(filename) > 38 {
    49  				filename = filename[38:]
    50  			}
    51  			return "", fmt.Sprintf(" %s:%d", filename, f.Line)
    52  		},
    53  	})
    54  
    55  	return rootCmd.Execute()
    56  }
    57  
    58  func newRootCmd(cfg *config.Config) *cobra.Command {
    59  	vpr := newViper()
    60  	rootCmd := &cobra.Command{
    61  		Use: "pyroscope [flags] <subcommand>",
    62  		Run: func(cmd *cobra.Command, _ []string) {
    63  			if cfg.Version {
    64  				printVersion(cmd)
    65  			} else {
    66  				printHelpMessage(cmd, nil)
    67  			}
    68  		},
    69  	}
    70  
    71  	rootCmd.SetUsageFunc(printUsageMessage)
    72  	rootCmd.SetHelpFunc(printHelpMessage)
    73  	cli.PopulateFlagSet(cfg, rootCmd.Flags(), vpr)
    74  	return rootCmd
    75  }
    76  
    77  func printUsageMessage(cmd *cobra.Command) error {
    78  	printHelpMessage(cmd, nil)
    79  	return nil
    80  }
    81  
    82  func printHelpMessage(cmd *cobra.Command, _ []string) {
    83  	cmd.Println(gradientBanner())
    84  	cmd.Println(cli.DefaultUsageFunc(cmd.Flags(), cmd))
    85  }
    86  
    87  func addHelpSubcommand(cmd *cobra.Command) {
    88  	cmd.AddCommand(&cobra.Command{
    89  		Use: "help",
    90  		Run: func(_ *cobra.Command, _ []string) {
    91  			printHelpMessage(cmd, nil)
    92  		},
    93  	})
    94  }