github.com/vanstinator/golangci-lint@v0.0.0-20240223191551-cc572f00d9d1/pkg/commands/run.go (about) 1 package commands 2 3 import ( 4 "context" 5 "errors" 6 "fmt" 7 "io" 8 "log" 9 "os" 10 "runtime" 11 "strings" 12 "time" 13 14 "github.com/fatih/color" 15 "github.com/spf13/cobra" 16 "github.com/spf13/pflag" 17 18 "github.com/vanstinator/golangci-lint/pkg/config" 19 "github.com/vanstinator/golangci-lint/pkg/exitcodes" 20 "github.com/vanstinator/golangci-lint/pkg/lint" 21 "github.com/vanstinator/golangci-lint/pkg/lint/lintersdb" 22 "github.com/vanstinator/golangci-lint/pkg/logutils" 23 "github.com/vanstinator/golangci-lint/pkg/packages" 24 "github.com/vanstinator/golangci-lint/pkg/printers" 25 "github.com/vanstinator/golangci-lint/pkg/result" 26 ) 27 28 const defaultFileMode = 0644 29 30 const ( 31 // envFailOnWarnings value: "1" 32 envFailOnWarnings = "FAIL_ON_WARNINGS" 33 // envMemLogEvery value: "1" 34 envMemLogEvery = "GL_MEM_LOG_EVERY" 35 ) 36 37 func getDefaultIssueExcludeHelp() string { 38 parts := []string{color.GreenString("Use or not use default excludes:")} 39 for _, ep := range config.DefaultExcludePatterns { 40 parts = append(parts, 41 fmt.Sprintf(" # %s %s: %s", ep.ID, ep.Linter, ep.Why), 42 fmt.Sprintf(" - %s", color.YellowString(ep.Pattern)), 43 "", 44 ) 45 } 46 return strings.Join(parts, "\n") 47 } 48 49 func getDefaultDirectoryExcludeHelp() string { 50 parts := []string{color.GreenString("Use or not use default excluded directories:")} 51 for _, dir := range packages.StdExcludeDirRegexps { 52 parts = append(parts, fmt.Sprintf(" - %s", color.YellowString(dir))) 53 } 54 parts = append(parts, "") 55 return strings.Join(parts, "\n") 56 } 57 58 func wh(text string) string { 59 return color.GreenString(text) 60 } 61 62 const defaultTimeout = time.Minute 63 64 //nolint:funlen,gomnd 65 func initFlagSet(fs *pflag.FlagSet, cfg *config.Config, m *lintersdb.Manager, isFinalInit bool) { 66 hideFlag := func(name string) { 67 if err := fs.MarkHidden(name); err != nil { 68 panic(err) 69 } 70 71 // we run initFlagSet multiple times, but we wouldn't like to see deprecation message multiple times 72 if isFinalInit { 73 const deprecateMessage = "flag will be removed soon, please, use .golangci.yml config" 74 if err := fs.MarkDeprecated(name, deprecateMessage); err != nil { 75 panic(err) 76 } 77 } 78 } 79 80 // Output config 81 oc := &cfg.Output 82 fs.StringVar(&oc.Format, "out-format", 83 config.OutFormatColoredLineNumber, 84 wh(fmt.Sprintf("Format of output: %s", strings.Join(config.OutFormats, "|")))) 85 fs.BoolVar(&oc.PrintIssuedLine, "print-issued-lines", true, wh("Print lines of code with issue")) 86 fs.BoolVar(&oc.PrintLinterName, "print-linter-name", true, wh("Print linter name in issue line")) 87 fs.BoolVar(&oc.UniqByLine, "uniq-by-line", true, wh("Make issues output unique by line")) 88 fs.BoolVar(&oc.SortResults, "sort-results", false, wh("Sort linter results")) 89 fs.BoolVar(&oc.PrintWelcomeMessage, "print-welcome", false, wh("Print welcome message")) 90 fs.StringVar(&oc.PathPrefix, "path-prefix", "", wh("Path prefix to add to output")) 91 hideFlag("print-welcome") // no longer used 92 93 fs.BoolVar(&cfg.InternalCmdTest, "internal-cmd-test", false, wh("Option is used only for testing golangci-lint command, don't use it")) 94 if err := fs.MarkHidden("internal-cmd-test"); err != nil { 95 panic(err) 96 } 97 98 // Run config 99 rc := &cfg.Run 100 fs.StringVar(&rc.ModulesDownloadMode, "modules-download-mode", "", 101 wh("Modules download mode. If not empty, passed as -mod=<mode> to go tools")) 102 fs.IntVar(&rc.ExitCodeIfIssuesFound, "issues-exit-code", 103 exitcodes.IssuesFound, wh("Exit code when issues were found")) 104 fs.StringVar(&rc.Go, "go", "", wh("Targeted Go version")) 105 fs.StringSliceVar(&rc.BuildTags, "build-tags", nil, wh("Build tags")) 106 107 fs.DurationVar(&rc.Timeout, "deadline", defaultTimeout, wh("Deadline for total work")) 108 if err := fs.MarkHidden("deadline"); err != nil { 109 panic(err) 110 } 111 fs.DurationVar(&rc.Timeout, "timeout", defaultTimeout, wh("Timeout for total work")) 112 113 fs.BoolVar(&rc.AnalyzeTests, "tests", true, wh("Analyze tests (*_test.go)")) 114 fs.BoolVar(&rc.PrintResourcesUsage, "print-resources-usage", false, 115 wh("Print avg and max memory usage of golangci-lint and total time")) 116 fs.StringVarP(&rc.Config, "config", "c", "", wh("Read config from file path `PATH`")) 117 fs.BoolVar(&rc.NoConfig, "no-config", false, wh("Don't read config")) 118 fs.StringSliceVar(&rc.SkipDirs, "skip-dirs", nil, wh("Regexps of directories to skip")) 119 fs.BoolVar(&rc.UseDefaultSkipDirs, "skip-dirs-use-default", true, getDefaultDirectoryExcludeHelp()) 120 fs.StringSliceVar(&rc.SkipFiles, "skip-files", nil, wh("Regexps of files to skip")) 121 122 const allowParallelDesc = "Allow multiple parallel golangci-lint instances running. " + 123 "If false (default) - golangci-lint acquires file lock on start." 124 fs.BoolVar(&rc.AllowParallelRunners, "allow-parallel-runners", false, wh(allowParallelDesc)) 125 const allowSerialDesc = "Allow multiple golangci-lint instances running, but serialize them around a lock. " + 126 "If false (default) - golangci-lint exits with an error if it fails to acquire file lock on start." 127 fs.BoolVar(&rc.AllowSerialRunners, "allow-serial-runners", false, wh(allowSerialDesc)) 128 129 // Linters settings config 130 lsc := &cfg.LintersSettings 131 132 // Hide all linters settings flags: they were initially visible, 133 // but when number of linters started to grow it became obvious that 134 // we can't fill 90% of flags by linters settings: common flags became hard to find. 135 // New linters settings should be done only through config file. 136 fs.BoolVar(&lsc.Errcheck.CheckTypeAssertions, "errcheck.check-type-assertions", 137 false, "Errcheck: check for ignored type assertion results") 138 hideFlag("errcheck.check-type-assertions") 139 fs.BoolVar(&lsc.Errcheck.CheckAssignToBlank, "errcheck.check-blank", false, 140 "Errcheck: check for errors assigned to blank identifier: _ = errFunc()") 141 hideFlag("errcheck.check-blank") 142 fs.StringVar(&lsc.Errcheck.Exclude, "errcheck.exclude", "", 143 "Path to a file containing a list of functions to exclude from checking") 144 hideFlag("errcheck.exclude") 145 fs.StringVar(&lsc.Errcheck.Ignore, "errcheck.ignore", "fmt:.*", 146 `Comma-separated list of pairs of the form pkg:regex. The regex is used to ignore names within pkg`) 147 hideFlag("errcheck.ignore") 148 149 fs.BoolVar(&lsc.Govet.CheckShadowing, "govet.check-shadowing", false, 150 "Govet: check for shadowed variables") 151 hideFlag("govet.check-shadowing") 152 153 fs.Float64Var(&lsc.Golint.MinConfidence, "golint.min-confidence", 0.8, 154 "Golint: minimum confidence of a problem to print it") 155 hideFlag("golint.min-confidence") 156 157 fs.BoolVar(&lsc.Gofmt.Simplify, "gofmt.simplify", true, "Gofmt: simplify code") 158 hideFlag("gofmt.simplify") 159 160 fs.IntVar(&lsc.Gocyclo.MinComplexity, "gocyclo.min-complexity", 161 30, "Minimal complexity of function to report it") 162 hideFlag("gocyclo.min-complexity") 163 164 fs.BoolVar(&lsc.Maligned.SuggestNewOrder, "maligned.suggest-new", false, 165 "Maligned: print suggested more optimal struct fields ordering") 166 hideFlag("maligned.suggest-new") 167 168 fs.IntVar(&lsc.Dupl.Threshold, "dupl.threshold", 169 150, "Dupl: Minimal threshold to detect copy-paste") 170 hideFlag("dupl.threshold") 171 172 fs.BoolVar(&lsc.Goconst.MatchWithConstants, "goconst.match-constant", 173 true, "Goconst: look for existing constants matching the values") 174 hideFlag("goconst.match-constant") 175 fs.IntVar(&lsc.Goconst.MinStringLen, "goconst.min-len", 176 3, "Goconst: minimum constant string length") 177 hideFlag("goconst.min-len") 178 fs.IntVar(&lsc.Goconst.MinOccurrencesCount, "goconst.min-occurrences", 179 3, "Goconst: minimum occurrences of constant string count to trigger issue") 180 hideFlag("goconst.min-occurrences") 181 fs.BoolVar(&lsc.Goconst.ParseNumbers, "goconst.numbers", 182 false, "Goconst: search also for duplicated numbers") 183 hideFlag("goconst.numbers") 184 fs.IntVar(&lsc.Goconst.NumberMin, "goconst.min", 185 3, "minimum value, only works with goconst.numbers") 186 hideFlag("goconst.min") 187 fs.IntVar(&lsc.Goconst.NumberMax, "goconst.max", 188 3, "maximum value, only works with goconst.numbers") 189 hideFlag("goconst.max") 190 fs.BoolVar(&lsc.Goconst.IgnoreCalls, "goconst.ignore-calls", 191 true, "Goconst: ignore when constant is not used as function argument") 192 hideFlag("goconst.ignore-calls") 193 194 fs.IntVar(&lsc.Lll.TabWidth, "lll.tab-width", 1, 195 "Lll: tab width in spaces") 196 hideFlag("lll.tab-width") 197 198 // Linters config 199 lc := &cfg.Linters 200 fs.StringSliceVarP(&lc.Enable, "enable", "E", nil, wh("Enable specific linter")) 201 fs.StringSliceVarP(&lc.Disable, "disable", "D", nil, wh("Disable specific linter")) 202 fs.BoolVar(&lc.EnableAll, "enable-all", false, wh("Enable all linters")) 203 204 fs.BoolVar(&lc.DisableAll, "disable-all", false, wh("Disable all linters")) 205 fs.StringSliceVarP(&lc.Presets, "presets", "p", nil, 206 wh(fmt.Sprintf("Enable presets (%s) of linters. Run 'golangci-lint help linters' to see "+ 207 "them. This option implies option --disable-all", strings.Join(m.AllPresets(), "|")))) 208 fs.BoolVar(&lc.Fast, "fast", false, wh("Run only fast linters from enabled linters set (first run won't be fast)")) 209 210 // Issues config 211 ic := &cfg.Issues 212 fs.StringSliceVarP(&ic.ExcludePatterns, "exclude", "e", nil, wh("Exclude issue by regexp")) 213 fs.BoolVar(&ic.UseDefaultExcludes, "exclude-use-default", true, getDefaultIssueExcludeHelp()) 214 fs.BoolVar(&ic.ExcludeCaseSensitive, "exclude-case-sensitive", false, wh("If set to true exclude "+ 215 "and exclude rules regular expressions are case sensitive")) 216 217 fs.IntVar(&ic.MaxIssuesPerLinter, "max-issues-per-linter", 50, 218 wh("Maximum issues count per one linter. Set to 0 to disable")) 219 fs.IntVar(&ic.MaxSameIssues, "max-same-issues", 3, 220 wh("Maximum count of issues with the same text. Set to 0 to disable")) 221 222 fs.BoolVarP(&ic.Diff, "new", "n", false, 223 wh("Show only new issues: if there are unstaged changes or untracked files, only those changes "+ 224 "are analyzed, else only changes in HEAD~ are analyzed.\nIt's a super-useful option for integration "+ 225 "of golangci-lint into existing large codebase.\nIt's not practical to fix all existing issues at "+ 226 "the moment of integration: much better to not allow issues in new code.\nFor CI setups, prefer "+ 227 "--new-from-rev=HEAD~, as --new can skip linting the current patch if any scripts generate "+ 228 "unstaged files before golangci-lint runs.")) 229 fs.StringVar(&ic.DiffFromRevision, "new-from-rev", "", 230 wh("Show only new issues created after git revision `REV`")) 231 fs.StringVar(&ic.DiffPatchFilePath, "new-from-patch", "", 232 wh("Show only new issues created in git patch with file path `PATH`")) 233 fs.BoolVar(&ic.WholeFiles, "whole-files", false, 234 wh("Show issues in any part of update files (requires new-from-rev or new-from-patch)")) 235 fs.BoolVar(&ic.NeedFix, "fix", false, wh("Fix found issues (if it's supported by the linter)")) 236 } 237 238 func (e *Executor) initRunConfiguration(cmd *cobra.Command) { 239 fs := cmd.Flags() 240 fs.SortFlags = false // sort them as they are defined here 241 initFlagSet(fs, e.cfg, e.DBManager, true) 242 } 243 244 func (e *Executor) getConfigForCommandLine() (*config.Config, error) { 245 // We use another pflag.FlagSet here to not set `changed` flag 246 // on cmd.Flags() options. Otherwise, string slice options will be duplicated. 247 fs := pflag.NewFlagSet("config flag set", pflag.ContinueOnError) 248 249 var cfg config.Config 250 // Don't do `fs.AddFlagSet(cmd.Flags())` because it shares flags representations: 251 // `changed` variable inside string slice vars will be shared. 252 // Use another config variable here, not e.cfg, to not 253 // affect main parsing by this parsing of only config option. 254 initFlagSet(fs, &cfg, e.DBManager, false) 255 initVersionFlagSet(fs, &cfg) 256 257 // Parse max options, even force version option: don't want 258 // to get access to Executor here: it's error-prone to use 259 // cfg vs e.cfg. 260 initRootFlagSet(fs, &cfg, true) 261 262 fs.Usage = func() {} // otherwise, help text will be printed twice 263 if err := fs.Parse(os.Args); err != nil { 264 if errors.Is(err, pflag.ErrHelp) { 265 return nil, err 266 } 267 268 return nil, fmt.Errorf("can't parse args: %w", err) 269 } 270 271 return &cfg, nil 272 } 273 274 func (e *Executor) initRun() { 275 e.runCmd = &cobra.Command{ 276 Use: "run", 277 Short: "Run the linters", 278 Run: e.executeRun, 279 PreRunE: func(_ *cobra.Command, _ []string) error { 280 if ok := e.acquireFileLock(); !ok { 281 return errors.New("parallel golangci-lint is running") 282 } 283 return nil 284 }, 285 PostRun: func(_ *cobra.Command, _ []string) { 286 e.releaseFileLock() 287 }, 288 } 289 e.rootCmd.AddCommand(e.runCmd) 290 291 e.runCmd.SetOut(logutils.StdOut) // use custom output to properly color it in Windows terminals 292 e.runCmd.SetErr(logutils.StdErr) 293 294 e.initRunConfiguration(e.runCmd) 295 } 296 297 func fixSlicesFlags(fs *pflag.FlagSet) { 298 // It's a dirty hack to set flag.Changed to true for every string slice flag. 299 // It's necessary to merge config and command-line slices: otherwise command-line 300 // flags will always overwrite ones from the config. 301 fs.VisitAll(func(f *pflag.Flag) { 302 if f.Value.Type() != "stringSlice" { 303 return 304 } 305 306 s, err := fs.GetStringSlice(f.Name) 307 if err != nil { 308 return 309 } 310 311 if s == nil { // assume that every string slice flag has nil as the default 312 return 313 } 314 315 var safe []string 316 for _, v := range s { 317 // add quotes to escape comma because spf13/pflag use a CSV parser: 318 // https://github.com/spf13/pflag/blob/85dd5c8bc61cfa382fecd072378089d4e856579d/string_slice.go#L43 319 safe = append(safe, `"`+v+`"`) 320 } 321 322 // calling Set sets Changed to true: next Set calls will append, not overwrite 323 _ = f.Value.Set(strings.Join(safe, ",")) 324 }) 325 } 326 327 // runAnalysis executes the linters that have been enabled in the configuration. 328 func (e *Executor) runAnalysis(ctx context.Context, args []string) ([]result.Issue, error) { 329 e.cfg.Run.Args = args 330 331 lintersToRun, err := e.EnabledLintersSet.GetOptimizedLinters() 332 if err != nil { 333 return nil, err 334 } 335 336 enabledLintersMap, err := e.EnabledLintersSet.GetEnabledLintersMap() 337 if err != nil { 338 return nil, err 339 } 340 341 for _, lc := range e.DBManager.GetAllSupportedLinterConfigs() { 342 isEnabled := enabledLintersMap[lc.Name()] != nil 343 e.reportData.AddLinter(lc.Name(), isEnabled, lc.EnabledByDefault) 344 } 345 346 lintCtx, err := e.contextLoader.Load(ctx, lintersToRun) 347 if err != nil { 348 return nil, fmt.Errorf("context loading failed: %w", err) 349 } 350 lintCtx.Log = e.log.Child(logutils.DebugKeyLintersContext) 351 352 runner, err := lint.NewRunner(e.cfg, e.log.Child(logutils.DebugKeyRunner), 353 e.goenv, e.EnabledLintersSet, e.lineCache, e.fileCache, e.DBManager, lintCtx.Packages) 354 if err != nil { 355 return nil, err 356 } 357 358 return runner.Run(ctx, lintersToRun, lintCtx) 359 } 360 361 func (e *Executor) setOutputToDevNull() (savedStdout, savedStderr *os.File) { 362 savedStdout, savedStderr = os.Stdout, os.Stderr 363 devNull, err := os.Open(os.DevNull) 364 if err != nil { 365 e.log.Warnf("Can't open null device %q: %s", os.DevNull, err) 366 return 367 } 368 369 os.Stdout, os.Stderr = devNull, devNull 370 return 371 } 372 373 func (e *Executor) setExitCodeIfIssuesFound(issues []result.Issue) { 374 if len(issues) != 0 { 375 e.exitCode = e.cfg.Run.ExitCodeIfIssuesFound 376 } 377 } 378 379 func (e *Executor) runAndPrint(ctx context.Context, args []string) error { 380 if err := e.goenv.Discover(ctx); err != nil { 381 e.log.Warnf("Failed to discover go env: %s", err) 382 } 383 384 if !logutils.HaveDebugTag(logutils.DebugKeyLintersOutput) { 385 // Don't allow linters and loader to print anything 386 log.SetOutput(io.Discard) 387 savedStdout, savedStderr := e.setOutputToDevNull() 388 defer func() { 389 os.Stdout, os.Stderr = savedStdout, savedStderr 390 }() 391 } 392 393 issues, err := e.runAnalysis(ctx, args) 394 if err != nil { 395 return err // XXX: don't loose type 396 } 397 398 formats := strings.Split(e.cfg.Output.Format, ",") 399 for _, format := range formats { 400 out := strings.SplitN(format, ":", 2) 401 if len(out) < 2 { 402 out = append(out, "") 403 } 404 405 err := e.printReports(issues, out[1], out[0]) 406 if err != nil { 407 return err 408 } 409 } 410 411 e.setExitCodeIfIssuesFound(issues) 412 413 e.fileCache.PrintStats(e.log) 414 415 return nil 416 } 417 418 func (e *Executor) printReports(issues []result.Issue, path, format string) error { 419 w, shouldClose, err := e.createWriter(path) 420 if err != nil { 421 return fmt.Errorf("can't create output for %s: %w", path, err) 422 } 423 424 p, err := e.createPrinter(format, w) 425 if err != nil { 426 if file, ok := w.(io.Closer); shouldClose && ok { 427 _ = file.Close() 428 } 429 return err 430 } 431 432 if err = p.Print(issues); err != nil { 433 if file, ok := w.(io.Closer); shouldClose && ok { 434 _ = file.Close() 435 } 436 return fmt.Errorf("can't print %d issues: %w", len(issues), err) 437 } 438 439 if file, ok := w.(io.Closer); shouldClose && ok { 440 _ = file.Close() 441 } 442 443 return nil 444 } 445 446 func (e *Executor) createWriter(path string) (io.Writer, bool, error) { 447 if path == "" || path == "stdout" { 448 return logutils.StdOut, false, nil 449 } 450 if path == "stderr" { 451 return logutils.StdErr, false, nil 452 } 453 f, err := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, defaultFileMode) 454 if err != nil { 455 return nil, false, err 456 } 457 return f, true, nil 458 } 459 460 func (e *Executor) createPrinter(format string, w io.Writer) (printers.Printer, error) { 461 var p printers.Printer 462 switch format { 463 case config.OutFormatJSON: 464 p = printers.NewJSON(&e.reportData, w) 465 case config.OutFormatColoredLineNumber, config.OutFormatLineNumber: 466 p = printers.NewText(e.cfg.Output.PrintIssuedLine, 467 format == config.OutFormatColoredLineNumber, e.cfg.Output.PrintLinterName, 468 e.log.Child(logutils.DebugKeyTextPrinter), w) 469 case config.OutFormatTab, config.OutFormatColoredTab: 470 p = printers.NewTab(e.cfg.Output.PrintLinterName, 471 format == config.OutFormatColoredTab, 472 e.log.Child(logutils.DebugKeyTabPrinter), w) 473 case config.OutFormatCheckstyle: 474 p = printers.NewCheckstyle(w) 475 case config.OutFormatCodeClimate: 476 p = printers.NewCodeClimate(w) 477 case config.OutFormatHTML: 478 p = printers.NewHTML(w) 479 case config.OutFormatJunitXML: 480 p = printers.NewJunitXML(w) 481 case config.OutFormatGithubActions: 482 p = printers.NewGithub(w) 483 case config.OutFormatTeamCity: 484 p = printers.NewTeamCity(w) 485 default: 486 return nil, fmt.Errorf("unknown output format %s", format) 487 } 488 489 return p, nil 490 } 491 492 // executeRun executes the 'run' CLI command, which runs the linters. 493 func (e *Executor) executeRun(_ *cobra.Command, args []string) { 494 needTrackResources := e.cfg.Run.IsVerbose || e.cfg.Run.PrintResourcesUsage 495 trackResourcesEndCh := make(chan struct{}) 496 defer func() { // XXX: this defer must be before ctx.cancel defer 497 if needTrackResources { // wait until resource tracking finished to print properly 498 <-trackResourcesEndCh 499 } 500 }() 501 502 e.setTimeoutToDeadlineIfOnlyDeadlineIsSet() 503 ctx, cancel := context.WithTimeout(context.Background(), e.cfg.Run.Timeout) 504 defer cancel() 505 506 if needTrackResources { 507 go watchResources(ctx, trackResourcesEndCh, e.log, e.debugf) 508 } 509 510 if err := e.runAndPrint(ctx, args); err != nil { 511 e.log.Errorf("Running error: %s", err) 512 if e.exitCode == exitcodes.Success { 513 var exitErr *exitcodes.ExitError 514 if errors.As(err, &exitErr) { 515 e.exitCode = exitErr.Code 516 } else { 517 e.exitCode = exitcodes.Failure 518 } 519 } 520 } 521 522 e.setupExitCode(ctx) 523 } 524 525 // to be removed when deadline is finally decommissioned 526 func (e *Executor) setTimeoutToDeadlineIfOnlyDeadlineIsSet() { 527 deadlineValue := e.cfg.Run.Deadline 528 if deadlineValue != 0 && e.cfg.Run.Timeout == defaultTimeout { 529 e.cfg.Run.Timeout = deadlineValue 530 } 531 } 532 533 func (e *Executor) setupExitCode(ctx context.Context) { 534 if ctx.Err() != nil { 535 e.exitCode = exitcodes.Timeout 536 e.log.Errorf("Timeout exceeded: try increasing it by passing --timeout option") 537 return 538 } 539 540 if e.exitCode != exitcodes.Success { 541 return 542 } 543 544 needFailOnWarnings := os.Getenv(lintersdb.EnvTestRun) == "1" || os.Getenv(envFailOnWarnings) == "1" 545 if needFailOnWarnings && len(e.reportData.Warnings) != 0 { 546 e.exitCode = exitcodes.WarningInTest 547 return 548 } 549 550 if e.reportData.Error != "" { 551 // it's a case e.g. when typecheck linter couldn't parse and error and just logged it 552 e.exitCode = exitcodes.ErrorWasLogged 553 return 554 } 555 } 556 557 func watchResources(ctx context.Context, done chan struct{}, logger logutils.Log, debugf logutils.DebugFunc) { 558 startedAt := time.Now() 559 debugf("Started tracking time") 560 561 var maxRSSMB, totalRSSMB float64 562 var iterationsCount int 563 564 const intervalMS = 100 565 ticker := time.NewTicker(intervalMS * time.Millisecond) 566 defer ticker.Stop() 567 568 logEveryRecord := os.Getenv(envMemLogEvery) == "1" 569 const MB = 1024 * 1024 570 571 track := func() { 572 var m runtime.MemStats 573 runtime.ReadMemStats(&m) 574 575 if logEveryRecord { 576 debugf("Stopping memory tracing iteration, printing ...") 577 printMemStats(&m, logger) 578 } 579 580 rssMB := float64(m.Sys) / MB 581 if rssMB > maxRSSMB { 582 maxRSSMB = rssMB 583 } 584 totalRSSMB += rssMB 585 iterationsCount++ 586 } 587 588 for { 589 track() 590 591 stop := false 592 select { 593 case <-ctx.Done(): 594 stop = true 595 debugf("Stopped resources tracking") 596 case <-ticker.C: 597 } 598 599 if stop { 600 break 601 } 602 } 603 track() 604 605 avgRSSMB := totalRSSMB / float64(iterationsCount) 606 607 logger.Infof("Memory: %d samples, avg is %.1fMB, max is %.1fMB", 608 iterationsCount, avgRSSMB, maxRSSMB) 609 logger.Infof("Execution took %s", time.Since(startedAt)) 610 close(done) 611 }