Serge Bazanski | cbd02be | 2021-09-24 13:39:12 +0200 | [diff] [blame] | 1 | package toolbase |
| 2 | |
| 3 | import ( |
| 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. |
| 11 | func 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 | // |
| 22 | // 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). |
| 25 | // |
| 26 | // If the workspace directory path cannot be inferred based on the above |
| 27 | // assumptions, an error is returned. |
| 28 | func WorkspaceDirectory() (string, error) { |
| 29 | if p := os.Getenv("BUILD_WORKSPACE_DIRECTORY"); p != "" && isWorkspace(p) { |
| 30 | return p, nil |
| 31 | } |
| 32 | |
| 33 | if p, err := os.Getwd(); err != nil && isWorkspace(p) { |
| 34 | return p, nil |
| 35 | } |
| 36 | |
| 37 | return "", fmt.Errorf("not invoked from `bazel run` and not running in workspace directory") |
| 38 | } |