无法打开应该在基本路径中的文件

I have a Go project (bazel-remote) that tries to read a yaml file passed in the command line, when built with bazel. This yaml file sits in the same location from where I run the bazel run command.

But it fails to run because os.Open fails with no such file or directory.

I printed the basePath using os.Getwd, because someone suggested that my basePath might be set wrong. But my basePath is set to a location in my /private/var/tmp/ where the bazel objects are created and stored:

/private/var/tmp/bazel/312feba8ddcde6737ae7dd7ef9bc2a5a/execroot/main/bazel-out/darwin-fastbuild/bin/darwin_amd64_static_pure_stripped/bazel-remote.runfiles/main'

How do I set my basePath correctly? Why is my basePath set to where it is?

Binaries started with bazel run are executed in an internal Bazel directory. They'll have access to "runfiles", which are files mentioned in the data attribute of the binary rule or its dependencies. For example, if you have a rule like the one below, you'll be able to read foo.txt, but not bar.txt or other files:

load("@io_bazel_rules_go//go:def.bzl", "go_binary")

go_binary(
    name = "hello",
    srcs = ["hello.go"],
    data = ["foo.txt"],
)

Note that the working directory of the binary corresponds to the repository root directory, not the directory where the binary is defined. You can debug with os.Getwd and filepath.Walk.

You mentioned you wanted to access a yaml file passed in on the command line though. Presumably, you want to be able to access any file the user passes in, not just files mentioned in the data attribute. For this case, take a look at the BUILD_WORKING_DIRECTORY environment variable (bazel run sets this). That gives the path to the directory where bazel run was invoked. Also, BUILD_WORKSPACE_DIRECTORY is the path to the workspace root directory.