Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I setup vscode for Go project built with bazel?

I am trying to browse code for gVisor with VScode.

However, unlike other Go projects, gVisor is built with bazel, and the source code is not located under $GOROOT or $GOPATH. Maybe this prevents gVisor packages from being searched by VSCode go extension. Go-to-definition is not working in most cases, except for cases where the definition can be found under the same directory.

How can I setup VSCode with bazel Go projects? Especially gVisor. Thanks!

like image 526
shpark Avatar asked Mar 29 '19 05:03

shpark


2 Answers

The linked gVisor rule now proxies a more canonical implementation

This setup worked for me:

  1. In your workspace's root BUILD file you can add the following build rule
# in BUILD.bazel
load("@io_bazel_rules_go//go:def.bzl", "go_path")

go_path(
    name = "gopath",
    mode = "link",
    deps = [
        "//my/binary/here",
        "//any/other/binaries/you/want/linked",
    ],
)

(if you don't yet have a gazelle import for the bazelbuild/go_rules, you would need to import it for bazel)

# in WORKSPACE
http_archive(
    name = "io_bazel_rules_go",
    sha256 = "8e968b5fcea1d2d64071872b12737bbb5514524ee5f0a4f54f5920266c261acb",
    urls = [
        "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.28.0/rules_go-v0.28.0.zip",
        "https://github.com/bazelbuild/rules_go/releases/download/v0.28.0/rules_go-v0.28.0.zip",
    ],
)
  1. Build this command to create a symlinked folder in your blaze-out at bazel-bin/gopath that contains links to each of your dependencies. You'll have to do this any time you add a new dependency. You will see a line for each symlink created.
bazel build :gopath
  1. (assuming you're using VSCode with the Golang extension) Set your workspace settings for the go extension to point to this gopath. Note you'll need to have it be a worspace trusted extension in order for this to work.
// In .vscode/settings.json
{
    "go.gopath": "/YOUR ABSOLUTE PATH TO YOUR WORKSPACE//bazel-bin/gopath"
}
  1. Restart VSCode

  2. Enjoy!

NOTE: if you have a go.mod file in your root dir, this will not work.

like image 79
Grady Ward Avatar answered Nov 03 '22 21:11

Grady Ward


gVisor recently added a gopath BUILD rule that creates a canonical GOPATH tree from the source.

You may be able to use that the edit more effectively from VScode.

like image 41
prattmic Avatar answered Nov 03 '22 21:11

prattmic