gopls returns the error "gopls: no packages returned: packages.Load error" for github.com/Shopify/sarama - go

I've checked out the main branch of github.com/Shopify/sarama (at commit 947343309601b4eb3c2fa3e7d15d701b503dd491 ) but I notice that in VS Code I can't "Go to definition" as usual. If I hover over the package name sarama in functional_consumer_group_test.go, I get the linter warning
No packages found for open file /Users/kurtpeek/go/src/github.com/Shopify/sarama/functional_consumer_group_test.go: <nil>.
If this file contains build tags, try adding "-tags=<build tag>" to your gopls "buildFlags" configuration (see (https://github.com/golang/tools/blob/master/gopls/doc/settings.md#buildflags-string).
Otherwise, see the troubleshooting guidelines for help investigating (https://github.com/golang/tools/blob/master/gopls/doc/troubleshooting.md).go list
(See screenshot below).
From the command line, if I try to gopls that file, I get a similar error:
> gopls check functional_consumer_group_test.go
gopls: no packages returned: packages.Load error
I suspect this has something to do with the build constraints (https://pkg.go.dev/cmd/go#hdr-Build_constraints) in that file, from https://github.com/Shopify/sarama/blob/947343309601b4eb3c2fa3e7d15d701b503dd491/functional_consumer_group_test.go#L1-L2,
//go:build functional
// +build functional
It's not clear to me, however, how to modify my VS Code settings.json to pass these build constraints. Does anyone know how to get this functional test to build?

Following https://www.ryanchapin.com/configuring-vscode-to-use-build-tags-in-golang-to-separate-integration-and-unit-test-code/, I had to create a .vscode/settings.json file in the repository's root directory and add the following contents:
{
"go.buildFlags": [
"-tags=functional"
],
"go.testTags": "functional",
}
Now VS Code works like normal in that file:

Have you tried go clean -cache?
And this link may help:
https://github.com/golang/go/issues/42353

This worked for me!
by adding it in .vscode/settings.json
{
"gopls.env": {
"GOFLAGS": "-tags=test"
}
}

Related

Debugging go in vscode doesn't stop at breakpoints, says "Could not find file ..." when debugger starts

Ubuntu. vscode 1.62.1. go1.17.3. vscode go extension v0.29.0. delve v1.7.1.
I'm new to vscode and Go. I have many years of experience debugging Java apps in Eclipse.
I've constructed a small multi-module Go app. I can set a breakpoint in main and other functions in other modules. Inside main.go, I select "Start Debugging".
It starts the application, and I can tell it's working from the console, and that the REST endpoint responds with my dummy response.
However, it will NOT stop at breakpoints. As soon as I start the session, the red breakpoint markers suddenly become hollow, and hovering on one of them shows a message "Could not find file ...", which prints the full path to the source file in question.
When I start it, it shows the following in the console:
Starting: /home/.../go/bin/dlv-dap dap --check-go-version=false --listen=127.0.0.1:43347 --log-dest=3 from /home/.../...
DAP server listening at: 127.0.0.1:43347
I haven't modified the launch.json (I hope someday a friendlier interface to editing launch configurations is provided).
What else could I be doing wrong?
Update:
This is a screenshot showing main.go just before I press F5 (Start Debugging):
Notice that I have a breakpoint on the print statement, on the first line of main.
This is what I see after I press F5:
Notice that it printed "At start of main" in the console. It didn't stop at the breakpoint. Also notice message in tooltip when hovering over the breakpoint.
Update:
This is a view of my directory structure:
First, just make sure you have initiated your project with go mod init voltagems: that would explain the import "voltagems/xxx", but also helps delve to find your main.go file at debug time.
You should have go.mod and go.sum files beside main.go.
Second, check your go env output, making sure GOPATH and GOROOT are set to default paths.
The OP David M. Karr adds in the comments:
I did run "go mod init" when I first created the project, but I realized that I didn't like the root module name, so I changed it to "voltagems"
I believe you can edit directly go.mod first line, and make sure it says:
module voltagems
Then go mod verify + go mod tidy
Finally, go build .. Restart your VSCode (or the command Reload Window), and see if the issue persists.
The OP David M. Karr points out to a root cause:
There are symbolic links in my project path.
There is a "substitutePath" configuration in VSCode-Go that is used to map to absolute paths.
You can see this parameter mentioned in Debugging with Legacy Debug Adapter
substitutePath
Path mappings to apply to get from a path in the editor to a path in the compiled program (default: []).
That comes from issue 622 "debug: breakpoints don't work when working with symlink".
And commit 93f32bb
src/debugAdapter: add substitutePath config for debugging
This change adds a new configuration option to both launch and
attach requests.
substituePath takes an array that maps from string to string that is used to translate paths passed to the debugger and then
back to the client.
This allows users to translate their symlinked directories to the
files that were actually used to build the binary.
In addition this can also be used for remote debugging, and when the location of the files has moved since the program was built.
Example: you need a from and to key:
"substitutePath": [
{
"from": "/symlink/path/dir/on/local/machine",
"to": "/absolute/path/dir/on/local/machine",
},

Unable to use Delve to debug Go - Access is denied

Attempting to use Delve to debug Go, I get the following error:
could not launch process: fork/exec C:\code\go_stuff\debugtest\__debug_bin: Access is denied.
could not remove C:\code\go_stuff\debugtest\__debug_bin: remove C:\code\go_stuff\debugtest\__debug_bin: Access is denied.
This is on a very simple Go project I created using go mod init and I wrote the main.go using Vim, so no VSCode or anything else is involved.
I tried to run dlv debug from the terminal and I get the above output.
I also get the above output when I try and debug using Delve in VSCode as well.
I have tried this on another PC and it works perfectly so it may well be something environmental but I cannot fathom what is causing this.
None of the projects I am trying to debug are in git or indeed any other source control.
Before I incur any downvotes due to lack of code, here is my entire project:
package main
import "fmt"
func main() {
fmt.Println("So we begin")
fmt.Println("Here we end")
}
It seems to be have been an issue caused by anti-virus deleting the executable when I tried to run it or even debug it.
I moved to developing Go in WSL2 using VSCode and I can debug the code without issue, so this would appear to be environmental and not an issue with either Delve or Go.
Actually I've met similar problem. I modify the "settings.json" file of VScode as following:
{
    "workbench.colorTheme": "Default Dark+",
    "workbench.editorAssociations": {
        "*.ipynb": "jupyter.notebook.ipynb"
    },
    "gopls": {
        "experimentalWorkspaceModule": true
    },
    "go.alternateTools": {
    
    },
    "go.delveConfig": {    
        "dlvLoadConfig": {
            "followPointers": true,
            "maxVariableRecurse": 1,
            "maxStringLen": 64,
            "maxArrayValues": 64,
            "maxStructFields": -1
        },
        "apiVersion": 2,
        "showGlobalVariables": false,
        "debugAdapter": "legacy",
        "substitutePath": []
    }
}
Then try to debug or either run without debug. It works and the "__debug_bin.exe" will not generate anymore. However I don't know the reason, it seems some problem of dlv configuration. Does anyone know the root cause? Hope this help you!

missing go.sum entry for module providing package <package_name>

Using the buffalo framework,
after bootstraping it via buffalo new <project_name>
I am trying to run buffalo dev
Expecting to see:
project running on port 3000
But I am getting those error messages instead
actions/app.go:4:2: missing go.sum entry for module providing package github.com/gobuffalo/buffalo (imported by sc_api/actions); to add:go get sc_api/actions
actions/app.go:13:2: missing go.sum entry for module providing package github.com/gobuffalo/mw-csrf (imported by sc_api/actions); to add: go get sc_api/actions
actions/app.go has been generated by buffalo, but in case you are wondering the error does match the import statement in this file.
// app.go
package actions
import (
"github.com/gobuffalo/buffalo" // 1rst line
"github.com/gobuffalo/envy"
forcessl "github.com/gobuffalo/mw-forcessl"
paramlogger "github.com/gobuffalo/mw-paramlogger"
"github.com/unrolled/secure"
"sc_api/models"
"github.com/gobuffalo/buffalo-pop/v2/pop/popmw"
csrf "github.com/gobuffalo/mw-csrf" // 2nd line
i18n "github.com/gobuffalo/mw-i18n"
"github.com/gobuffalo/packr/v2"
)
What does it mean ? How do I fix it ?
It seems the issue has nothing to do with Buffalo and more with my lack of understanding of Go in general.
running go mod tidy solved the issue
This command goes through the go.mod file to resolve dependencies:
delete the packages that are not needed
download those needed
update the go.sum
I am still unsure which of those actions did the trick... but the project runs now.
ps: I'll let the in-depth explanation/correction to the Go wizard out here.
i got the same issue when building a docker image. i tried go mod tidy and
also go get -t . as suggested here https://github.com/golang/go/issues/44129. both didnt worked for me though but updating my docker builder to version 1.18 worked.
I use go mod tidy -e solved the problem. The -e flag (added in Go 1.16) causes go mod tidy to attempt to proceed despite errors encountered while loading packages.The more about mod tidy: https://go.dev/ref/mod#go-mod-tidy

go-swagger restapi/configure_todo_list.go - api.TodoGetHandler undefined error

I am a newbie in go and go-swagger. I am following steps in Simple Server tutorial in goswagger.io.
I am using Ubuntu 18.04, swagger v0.25.0 and go 1.15.6.
Following the same steps, there are a few differences of the files generated. For instance, goswagger.io's has find_todos_okbody.go and get_okbody.go in models but mine does not. Why is that so?
Link to screenshot of my generated files vs
Link to screenshot of generated files by swagger.io
Starting the server as written in the tutorial go install ./cmd/todo-list-server/ gives me the following error. Can anyone please help with this?
# my_folder/swagger-todo-list/restapi
restapi/configure_todo_list.go:41:8: api.TodosGetHandler undefined (type *operations.TodoListAPI has no field or method TodosGetHandler)
restapi/configure_todo_list.go:42:6: api.TodosGetHandler undefined (type *operations.TodoListAPI has no field or method TodosGetHandler)
The first step in goswagger.io todo-list is swagger init spec .... Which directory should I run this command in? I ran it in a newly created folder in my home directory. However, from the page, it shows the path to be ~/go/src/github.com/go-swagger/go-swagger/examples/tutorials/todo-list. I am not sure whether I should use go get ..., git clone ... or create those folders. Can someone advise me?
Thanks.
This is likely the documentation lagging behind the version of the code that you are running. As long as it compiles, the specific files the tool generates isn't so crucial.
This is a compilation error. When you do go install foo it will try to build the foo package as an executable and then move that to your GOPATH/bin directory. It seems that the generated code in restapi/configure_todo_list.go isn't correct for the operations code generated.
All you need to run this tutorial yourself is an empty directory and the swagger tool (not its source code). You run the commands from the root of this empty project. In order not to run into GOPATH problems I would initialise a module with go mod init todo-list-example before doing anything else.
Note that while the todo-list example code exists inside the go-swagger source, it's there just for documenting example usage and output.
What I would advice for #2 is to make sure you're using a properly released version of go-swagger, rather than installing from the latest commit (which happens when you just do a go get), as I have found that to be occasionally unstable.
Next, re-generate the entire server, but make sure you also regenerate restapi/configure_todo_list.go by passing --regenerate-configureapi to your swagger generate call. This file isn't always refreshed because you're meant to modify it to configure your app, and if you changed versions of the tool it may be different and incompatible.
If after that you still get the compilation error, it may be worth submitting a bug report at https://github.com/go-swagger/go-swagger/issues.
Thanks #EzequielMuns. The errors in #2 went away after I ran go get - u -f ./... as stated in
...
For this generation to compile you need to have some packages in your GOPATH:
* github.com/go-openapi/runtime
* github.com/jessevdk/go-flags
You can get these now with: go get -u -f ./...
I think it's an error of swagger code generation. You can do as folloing to fix this:
delete file configure_todo_list.go;
regenerate code.
# swagger generate server -A todo-list -f ./swagger.yml
Then, you can run command go install ./cmd/todo-list-server/, it will succeed.

How is VSCode finding this Go linting Problem and how do I ignore it?

I'm setting up linting with golangci-lint in my Go project. I have a file generated by go-bindata that VSCode is listing the following under the Problems tab:
assets/assets.go: redundant type from array, slice, or map composite literal (simplifycompositelit)
I can't seem to get rid of it. It's not a compiler error and I'll be re-running go-bindata from time to time so I don't want to make a habit of modifying generated code.
Right now, with the configuration below, I can't make VSCode stop reporting this error. If I run golangci-lint run ./... in the root of the workspace I get no output. I can provide my linting config if needed but VSCode seems to be running something else. How do I figure out what's reporting this error and how do I make it stop reporting anything for the file assets/assets.go in this one workspace?
Here's Go-related vscode settings:
{
"go.formatTool": "gofmt",
"go.lintTool": "golangci-lint",
"go.liveErrors": {
"enabled": true,
"delay": 500
},
"go.lintOnSave": "workspace",
"editor.codeActionsOnSave": {
"source.organizeImports": true
},
"go.useLanguageServer": true,
"go.languageServerExperimentalFeatures": {
"diagnostics": true,
"documentLink": true
},
}
Here's the line in question even with a nolint comment to show it's not behaving as expected. If it were golangci-lint outputting this, the nolint would prevent the warning from showing. I reloaded the window and closed/reopened vscode to be sure the change was noticed.
After reproducing locally, it seems this message comes from gopls, as disabling gopls silences the message. There are a couple of related complaints/issues on the Go issue tracker:
hide gofmt -s diagnostics (and others?) in generated files
should not issue lint-style warnings on generated code
Neither offers an actual solution.
However, this issue on the vscode-go repo, provides a work-around. In your VSCode config, add the gopls.analyses.simplifycompositelit key, with a value of false:
"gopls": {
"analyses": {
"simplifycompositelit": false
},
}
Of course, this disables it for all projects, not just generated files, but if you're also using golangci-lint, it can be configured to catch the same types of errors, and can be configured on a more granular basis, so that you won't miss the same class of errors in non-generated code.

Resources