github.com/powerman/golang-tools@v0.1.11-0.20220410185822-5ad214d8d803/internal/tool/tool.go (about)

     1  // Copyright 2018 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package tool is a harness for writing Go tools.
     6  package tool
     7  
     8  import (
     9  	"context"
    10  	"flag"
    11  	"fmt"
    12  	"log"
    13  	"os"
    14  	"reflect"
    15  	"runtime"
    16  	"runtime/pprof"
    17  	"runtime/trace"
    18  	"strings"
    19  	"time"
    20  )
    21  
    22  // This file is a harness for writing your main function.
    23  // The original version of the file is in github.com/powerman/golang-tools/internal/tool.
    24  //
    25  // It adds a method to the Application type
    26  //     Main(name, usage string, args []string)
    27  // which should normally be invoked from a true main as follows:
    28  //     func main() {
    29  //       (&Application{}).Main("myapp", "non-flag-command-line-arg-help", os.Args[1:])
    30  //     }
    31  // It recursively scans the application object for fields with a tag containing
    32  //     `flag:"flagnames" help:"short help text"``
    33  // uses all those fields to build command line flags. It will split flagnames on
    34  // commas and add a flag per name.
    35  // It expects the Application type to have a method
    36  //     Run(context.Context, args...string) error
    37  // which it invokes only after all command line flag processing has been finished.
    38  // If Run returns an error, the error will be printed to stderr and the
    39  // application will quit with a non zero exit status.
    40  
    41  // Profile can be embedded in your application struct to automatically
    42  // add command line arguments and handling for the common profiling methods.
    43  type Profile struct {
    44  	CPU    string `flag:"profile.cpu" help:"write CPU profile to this file"`
    45  	Memory string `flag:"profile.mem" help:"write memory profile to this file"`
    46  	Trace  string `flag:"profile.trace" help:"write trace log to this file"`
    47  }
    48  
    49  // Application is the interface that must be satisfied by an object passed to Main.
    50  type Application interface {
    51  	// Name returns the application's name. It is used in help and error messages.
    52  	Name() string
    53  	// Most of the help usage is automatically generated, this string should only
    54  	// describe the contents of non flag arguments.
    55  	Usage() string
    56  	// ShortHelp returns the one line overview of the command.
    57  	ShortHelp() string
    58  	// DetailedHelp should print a detailed help message. It will only ever be shown
    59  	// when the ShortHelp is also printed, so there is no need to duplicate
    60  	// anything from there.
    61  	// It is passed the flag set so it can print the default values of the flags.
    62  	// It should use the flag sets configured Output to write the help to.
    63  	DetailedHelp(*flag.FlagSet)
    64  	// Run is invoked after all flag processing, and inside the profiling and
    65  	// error handling harness.
    66  	Run(ctx context.Context, args ...string) error
    67  }
    68  
    69  type SubCommand interface {
    70  	Parent() string
    71  }
    72  
    73  // This is the type returned by CommandLineErrorf, which causes the outer main
    74  // to trigger printing of the command line help.
    75  type commandLineError string
    76  
    77  func (e commandLineError) Error() string { return string(e) }
    78  
    79  // CommandLineErrorf is like fmt.Errorf except that it returns a value that
    80  // triggers printing of the command line help.
    81  // In general you should use this when generating command line validation errors.
    82  func CommandLineErrorf(message string, args ...interface{}) error {
    83  	return commandLineError(fmt.Sprintf(message, args...))
    84  }
    85  
    86  // Main should be invoked directly by main function.
    87  // It will only return if there was no error.  If an error
    88  // was encountered it is printed to standard error and the
    89  // application exits with an exit code of 2.
    90  func Main(ctx context.Context, app Application, args []string) {
    91  	s := flag.NewFlagSet(app.Name(), flag.ExitOnError)
    92  	if err := Run(ctx, s, app, args); err != nil {
    93  		fmt.Fprintf(s.Output(), "%s: %v\n", app.Name(), err)
    94  		if _, printHelp := err.(commandLineError); printHelp {
    95  			s.Usage()
    96  		}
    97  		os.Exit(2)
    98  	}
    99  }
   100  
   101  // Run is the inner loop for Main; invoked by Main, recursively by
   102  // Run, and by various tests.  It runs the application and returns an
   103  // error.
   104  func Run(ctx context.Context, s *flag.FlagSet, app Application, args []string) error {
   105  	s.Usage = func() {
   106  		if app.ShortHelp() != "" {
   107  			fmt.Fprintf(s.Output(), "%s\n\nUsage:\n  ", app.ShortHelp())
   108  			if sub, ok := app.(SubCommand); ok && sub.Parent() != "" {
   109  				fmt.Fprintf(s.Output(), "%s [flags] %s", sub.Parent(), app.Name())
   110  			} else {
   111  				fmt.Fprintf(s.Output(), "%s [flags]", app.Name())
   112  			}
   113  			if usage := app.Usage(); usage != "" {
   114  				fmt.Fprintf(s.Output(), " %s", usage)
   115  			}
   116  			fmt.Fprint(s.Output(), "\n")
   117  		}
   118  		app.DetailedHelp(s)
   119  	}
   120  	p := addFlags(s, reflect.StructField{}, reflect.ValueOf(app))
   121  	if err := s.Parse(args); err != nil {
   122  		return err
   123  	}
   124  
   125  	if p != nil && p.CPU != "" {
   126  		f, err := os.Create(p.CPU)
   127  		if err != nil {
   128  			return err
   129  		}
   130  		if err := pprof.StartCPUProfile(f); err != nil {
   131  			return err
   132  		}
   133  		defer pprof.StopCPUProfile()
   134  	}
   135  
   136  	if p != nil && p.Trace != "" {
   137  		f, err := os.Create(p.Trace)
   138  		if err != nil {
   139  			return err
   140  		}
   141  		if err := trace.Start(f); err != nil {
   142  			return err
   143  		}
   144  		defer func() {
   145  			trace.Stop()
   146  			log.Printf("To view the trace, run:\n$ go tool trace view %s", p.Trace)
   147  		}()
   148  	}
   149  
   150  	if p != nil && p.Memory != "" {
   151  		f, err := os.Create(p.Memory)
   152  		if err != nil {
   153  			return err
   154  		}
   155  		defer func() {
   156  			runtime.GC() // get up-to-date statistics
   157  			if err := pprof.WriteHeapProfile(f); err != nil {
   158  				log.Printf("Writing memory profile: %v", err)
   159  			}
   160  			f.Close()
   161  		}()
   162  	}
   163  
   164  	return app.Run(ctx, s.Args()...)
   165  }
   166  
   167  // addFlags scans fields of structs recursively to find things with flag tags
   168  // and add them to the flag set.
   169  func addFlags(f *flag.FlagSet, field reflect.StructField, value reflect.Value) *Profile {
   170  	// is it a field we are allowed to reflect on?
   171  	if field.PkgPath != "" {
   172  		return nil
   173  	}
   174  	// now see if is actually a flag
   175  	flagNames, isFlag := field.Tag.Lookup("flag")
   176  	help := field.Tag.Get("help")
   177  	if isFlag {
   178  		nameList := strings.Split(flagNames, ",")
   179  		// add the main flag
   180  		addFlag(f, value, nameList[0], help)
   181  		if len(nameList) > 1 {
   182  			// and now add any aliases using the same flag value
   183  			fv := f.Lookup(nameList[0]).Value
   184  			for _, flagName := range nameList[1:] {
   185  				f.Var(fv, flagName, help)
   186  			}
   187  		}
   188  		return nil
   189  	}
   190  	// not a flag, but it might be a struct with flags in it
   191  	value = resolve(value.Elem())
   192  	if value.Kind() != reflect.Struct {
   193  		return nil
   194  	}
   195  	p, _ := value.Addr().Interface().(*Profile)
   196  	// go through all the fields of the struct
   197  	for i := 0; i < value.Type().NumField(); i++ {
   198  		child := value.Type().Field(i)
   199  		v := value.Field(i)
   200  		// make sure we have a pointer
   201  		if v.Kind() != reflect.Ptr {
   202  			v = v.Addr()
   203  		}
   204  		// check if that field is a flag or contains flags
   205  		if fp := addFlags(f, child, v); fp != nil {
   206  			p = fp
   207  		}
   208  	}
   209  	return p
   210  }
   211  
   212  func addFlag(f *flag.FlagSet, value reflect.Value, flagName string, help string) {
   213  	switch v := value.Interface().(type) {
   214  	case flag.Value:
   215  		f.Var(v, flagName, help)
   216  	case *bool:
   217  		f.BoolVar(v, flagName, *v, help)
   218  	case *time.Duration:
   219  		f.DurationVar(v, flagName, *v, help)
   220  	case *float64:
   221  		f.Float64Var(v, flagName, *v, help)
   222  	case *int64:
   223  		f.Int64Var(v, flagName, *v, help)
   224  	case *int:
   225  		f.IntVar(v, flagName, *v, help)
   226  	case *string:
   227  		f.StringVar(v, flagName, *v, help)
   228  	case *uint:
   229  		f.UintVar(v, flagName, *v, help)
   230  	case *uint64:
   231  		f.Uint64Var(v, flagName, *v, help)
   232  	default:
   233  		log.Fatalf("Cannot understand flag of type %T", v)
   234  	}
   235  }
   236  
   237  func resolve(v reflect.Value) reflect.Value {
   238  	for {
   239  		switch v.Kind() {
   240  		case reflect.Interface, reflect.Ptr:
   241  			v = v.Elem()
   242  		default:
   243  			return v
   244  		}
   245  	}
   246  }