Skip to content

Commit

Permalink
go/packages: correctly handle context canceled
Browse files Browse the repository at this point in the history
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 <christian@aperture.us>
  • Loading branch information
paralin committed Mar 13, 2024
1 parent ca94c96 commit 7043adb
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions go/packages/packages.go
Expand Up @@ -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))
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 7043adb

Please sign in to comment.