From 7043adbf2fa72b7432fa3786b792ffd95f310387 Mon Sep 17 00:00:00 2001 From: Christian Stewart Date: Mon, 11 Mar 2024 21:02:26 -0700 Subject: [PATCH] go/packages: correctly handle context canceled If the context is canceled for packages.Load, the following log message is written numerous times to stderr and returned as a load error per-package: internal error: error "context canceled" (*errors.errorString) without position Check if the context was canceled and return nil, ctx.Err() instead. Use ld.Context which is ld.Config.Context if non-nil and otherwise defaults to context.Background to avoid nil references on ld.Config.Context. Signed-off-by: Christian Stewart --- go/packages/packages.go | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/go/packages/packages.go b/go/packages/packages.go index 95e6540aa4d..c5a4d2c4764 100644 --- a/go/packages/packages.go +++ b/go/packages/packages.go @@ -759,6 +759,11 @@ func (ld *loader) refine(response *DriverResponse) ([]*Package, error) { }(lpkg) } wg.Wait() + + // Check if the context was canceled during loadRecursive and return early if so. + if err := ld.Context.Err(); err != nil { + return nil, err + } } result := make([]*Package, len(initial)) @@ -966,6 +971,11 @@ func (ld *loader) loadPackage(lpkg *loaderPackage) { } files, errs := ld.parseFiles(lpkg.CompiledGoFiles) + // parseFiles may return context canceled if ld.Context.Err() != nil + // check if the context was canceled during parseFiles and return early if so. + if err := ld.Context.Err(); err != nil { + return + } for _, err := range errs { appendError(err) } @@ -1132,9 +1142,8 @@ func (ld *loader) parseFiles(filenames []string) ([]*ast.File, []error) { parsed := make([]*ast.File, n) errors := make([]error, n) for i, file := range filenames { - if ld.Config.Context.Err() != nil { - parsed[i] = nil - errors[i] = ld.Config.Context.Err() + if err := ld.Context.Err(); err != nil { + parsed[i], errors[i] = nil, err continue } wg.Add(1)