blob: f1d9f08b1e809eb5f547560b9265f751f9d95306 [file] [log] [blame]
Serge Bazanskicbd02be2021-09-24 13:39:12 +02001package toolbase
2
3import (
4 "fmt"
5 "os"
6 "path"
7)
8
9// isWorkspace returns whether a given string is a valid path pointing to a
10// Bazel workspace directory.
11func isWorkspace(dir string) bool {
12 w := path.Join(dir, "WORKSPACE")
13 if _, err := os.Stat(w); err == nil {
14 return true
15 }
16 return false
17}
18
19// WorkspaceDirectory returns the workspace directory from which a given
20// command line tool is running. This handles the following cases:
21//
Tim Windelschmidt99e15112025-02-05 17:38:16 +010022// 1. The command line tool was invoked via `bazel run`.
23// 2. The command line tool was started directly in a workspace directory (but
24// not a subdirectory).
Serge Bazanskicbd02be2021-09-24 13:39:12 +020025//
26// If the workspace directory path cannot be inferred based on the above
27// assumptions, an error is returned.
28func WorkspaceDirectory() (string, error) {
29 if p := os.Getenv("BUILD_WORKSPACE_DIRECTORY"); p != "" && isWorkspace(p) {
30 return p, nil
31 }
32
Tim Windelschmidt62a02ea2024-04-17 02:33:55 +020033 if p, err := os.Getwd(); err == nil && isWorkspace(p) {
Serge Bazanskicbd02be2021-09-24 13:39:12 +020034 return p, nil
35 }
36
37 return "", fmt.Errorf("not invoked from `bazel run` and not running in workspace directory")
38}