Debian Codegraph @

internal/tool/tool.go

raw symbols SCIP
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 golang.org/x/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 Alloc string `flag:"profile.alloc" help:"write alloc profile to this file"`
47 Trace string `flag:"profile.trace" help:"write trace log to this file"`
48 Block string `flag:"profile.block" help:"write block profile to this file"`
49 }
50
51 // Application is the interface that must be satisfied by an object passed to Main.
52 type Application interface {
53 // Name returns the application's name. It is used in help and error messages.
54 Name() string
55 // Most of the help usage is automatically generated, this string should only
56 // describe the contents of non flag arguments.
57 Usage() string
58 // ShortHelp returns the one line overview of the command.
59 ShortHelp() string
60 // DetailedHelp should print a detailed help message. It will only ever be shown
61 // when the ShortHelp is also printed, so there is no need to duplicate
62 // anything from there.
63 // It is passed the flag set so it can print the default values of the flags.
64 // It should use the flag sets configured Output to write the help to.
65 DetailedHelp(*flag.FlagSet)
66 // Run is invoked after all flag processing, and inside the profiling and
67 // error handling harness.
68 Run(ctx context.Context, args ...string) error
69 }
70
71 type SubCommand interface {
72 Parent() string
73 }
74
75 // This is the type returned by CommandLineErrorf, which causes the outer main
76 // to trigger printing of the command line help.
77 type commandLineError string
78
79 func (e commandLineError) Error() string { return string(e) }
80
81 // CommandLineErrorf is like fmt.Errorf except that it returns a value that
82 // triggers printing of the command line help.
83 // In general you should use this when generating command line validation errors.
84 func CommandLineErrorf(message string, args ...any) error {
85 return commandLineError(fmt.Sprintf(message, args...))
86 }
87
88 // Main should be invoked directly by main function.
89 // It will only return if there was no error. If an error
90 // was encountered it is printed to standard error and the
91 // application exits with an exit code of 2.
92 func Main(ctx context.Context, app Application, args []string) {
93 s := flag.NewFlagSet(app.Name(), flag.ExitOnError)
94 if err := Run(ctx, s, app, args); err != nil {
95 fmt.Fprintf(s.Output(), "%s: %v\n", app.Name(), err)
96 if _, printHelp := err.(commandLineError); printHelp {
97 // TODO(adonovan): refine this. It causes
98 // any command-line error to result in the full
99 // usage message, which typically obscures
100 // the actual error.
101 s.Usage()
102 }
103 os.Exit(2)
104 }
105 }
106
107 // Run is the inner loop for Main; invoked by Main, recursively by
108 // Run, and by various tests. It runs the application and returns an
109 // error.
110 func Run(ctx context.Context, s *flag.FlagSet, app Application, args []string) (resultErr error) {
111 s.Usage = func() {
112 if app.ShortHelp() != "" {
113 fmt.Fprintf(s.Output(), "%s\n\nUsage:\n ", app.ShortHelp())
114 if sub, ok := app.(SubCommand); ok && sub.Parent() != "" {
115 fmt.Fprintf(s.Output(), "%s [flags] %s", sub.Parent(), app.Name())
116 } else {
117 fmt.Fprintf(s.Output(), "%s [flags]", app.Name())
118 }
119 if usage := app.Usage(); usage != "" {
120 fmt.Fprintf(s.Output(), " %s", usage)
121 }
122 fmt.Fprint(s.Output(), "\n")
123 }
124 app.DetailedHelp(s)
125 }
126 p := addFlags(s, reflect.StructField{}, reflect.ValueOf(app))
127 if err := s.Parse(args); err != nil {
128 return err
129 }
130
131 if p != nil && p.CPU != "" {
132 f, err := os.Create(p.CPU)
133 if err != nil {
134 return err
135 }
136 if err := pprof.StartCPUProfile(f); err != nil {
137 f.Close() // ignore error
138 return err
139 }
140 defer func() {
141 pprof.StopCPUProfile()
142 if closeErr := f.Close(); resultErr == nil {
143 resultErr = closeErr
144 }
145 }()
146 }
147
148 if p != nil && p.Trace != "" {
149 f, err := os.Create(p.Trace)
150 if err != nil {
151 return err
152 }
153 if err := trace.Start(f); err != nil {
154 f.Close() // ignore error
155 return err
156 }
157 defer func() {
158 trace.Stop()
159 if closeErr := f.Close(); resultErr == nil {
160 resultErr = closeErr
161 }
162 log.Printf("To view the trace, run:\n$ go tool trace view %s", p.Trace)
163 }()
164 }
165
166 if p != nil && p.Memory != "" {
167 f, err := os.Create(p.Memory)
168 if err != nil {
169 return err
170 }
171 defer func() {
172 runtime.GC() // get up-to-date statistics
173 if err := pprof.WriteHeapProfile(f); err != nil {
174 log.Printf("Writing memory profile: %v", err)
175 }
176 if err := f.Close(); err != nil {
177 log.Printf("Closing memory profile: %v", err)
178 }
179 }()
180 }
181
182 if p != nil && p.Alloc != "" {
183 f, err := os.Create(p.Alloc)
184 if err != nil {
185 return err
186 }
187 defer func() {
188 if err := pprof.Lookup("allocs").WriteTo(f, 0); err != nil {
189 log.Printf("Writing alloc profile: %v", err)
190 }
191 if err := f.Close(); err != nil {
192 log.Printf("Closing alloc profile: %v", err)
193 }
194 }()
195 }
196
197 if p != nil && p.Block != "" {
198 f, err := os.Create(p.Block)
199 if err != nil {
200 return err
201 }
202 runtime.SetBlockProfileRate(1) // record all blocking events
203 defer func() {
204 if err := pprof.Lookup("block").WriteTo(f, 0); err != nil {
205 log.Printf("Writing block profile: %v", err)
206 }
207 if err := f.Close(); err != nil {
208 log.Printf("Closing block profile: %v", err)
209 }
210 }()
211 }
212
213 return app.Run(ctx, s.Args()...)
214 }
215
216 // addFlags scans fields of structs recursively to find things with flag tags
217 // and add them to the flag set.
218 func addFlags(f *flag.FlagSet, field reflect.StructField, value reflect.Value) *Profile {
219 // is it a field we are allowed to reflect on?
220 if field.PkgPath != "" {
221 return nil
222 }
223 // now see if is actually a flag
224 flagNames, isFlag := field.Tag.Lookup("flag")
225 help := field.Tag.Get("help")
226 if isFlag {
227 nameList := strings.Split(flagNames, ",")
228 // add the main flag
229 addFlag(f, value, nameList[0], help)
230 if len(nameList) > 1 {
231 // and now add any aliases using the same flag value
232 fv := f.Lookup(nameList[0]).Value
233 for _, flagName := range nameList[1:] {
234 f.Var(fv, flagName, help)
235 }
236 }
237 return nil
238 }
239 // not a flag, but it might be a struct with flags in it
240 value = resolve(value.Elem())
241 if value.Kind() != reflect.Struct {
242 return nil
243 }
244
245 // TODO(adonovan): there's no need for this special treatment of Profile:
246 // The caller can use f.Lookup("profile.cpu") etc instead.
247 p, _ := value.Addr().Interface().(*Profile)
248 // go through all the fields of the struct
249 for i := 0; i < value.Type().NumField(); i++ {
250 child := value.Type().Field(i)
251 v := value.Field(i)
252 // make sure we have a pointer
253 if v.Kind() != reflect.Pointer {
254 v = v.Addr()
255 }
256 // check if that field is a flag or contains flags
257 if fp := addFlags(f, child, v); fp != nil {
258 p = fp
259 }
260 }
261 return p
262 }
263
264 func addFlag(f *flag.FlagSet, value reflect.Value, flagName string, help string) {
265 switch v := value.Interface().(type) {
266 case flag.Value:
267 f.Var(v, flagName, help)
268 case *bool:
269 f.BoolVar(v, flagName, *v, help)
270 case *time.Duration:
271 f.DurationVar(v, flagName, *v, help)
272 case *float64:
273 f.Float64Var(v, flagName, *v, help)
274 case *int64:
275 f.Int64Var(v, flagName, *v, help)
276 case *int:
277 f.IntVar(v, flagName, *v, help)
278 case *string:
279 f.StringVar(v, flagName, *v, help)
280 case *uint:
281 f.UintVar(v, flagName, *v, help)
282 case *uint64:
283 f.Uint64Var(v, flagName, *v, help)
284 default:
285 log.Fatalf("field %q of type %T is not assignable to flag.Value", flagName, v)
286 }
287 }
288
289 func resolve(v reflect.Value) reflect.Value {
290 for {
291 switch v.Kind() {
292 case reflect.Interface, reflect.Pointer:
293 v = v.Elem()
294 default:
295 return v
296 }
297 }
298 }