| Tim Windelschmidt | 6d33a43 | 2025-02-04 14:34:25 +0100 | [diff] [blame^] | 1 | // Copyright The Monogon Project Authors. |
| 2 | // SPDX-License-Identifier: Apache-2.0 |
| 3 | |
| Serge Bazanski | cbd02be | 2021-09-24 13:39:12 +0200 | [diff] [blame] | 4 | package toolbase |
| 5 | |
| 6 | import ( |
| 7 | "fmt" |
| 8 | "os" |
| 9 | "path" |
| 10 | ) |
| 11 | |
| 12 | // isWorkspace returns whether a given string is a valid path pointing to a |
| 13 | // Bazel workspace directory. |
| 14 | func isWorkspace(dir string) bool { |
| 15 | w := path.Join(dir, "WORKSPACE") |
| 16 | if _, err := os.Stat(w); err == nil { |
| 17 | return true |
| 18 | } |
| 19 | return false |
| 20 | } |
| 21 | |
| 22 | // WorkspaceDirectory returns the workspace directory from which a given |
| 23 | // command line tool is running. This handles the following cases: |
| 24 | // |
| Tim Windelschmidt | 99e1511 | 2025-02-05 17:38:16 +0100 | [diff] [blame] | 25 | // 1. The command line tool was invoked via `bazel run`. |
| 26 | // 2. The command line tool was started directly in a workspace directory (but |
| 27 | // not a subdirectory). |
| Serge Bazanski | cbd02be | 2021-09-24 13:39:12 +0200 | [diff] [blame] | 28 | // |
| 29 | // If the workspace directory path cannot be inferred based on the above |
| 30 | // assumptions, an error is returned. |
| 31 | func WorkspaceDirectory() (string, error) { |
| 32 | if p := os.Getenv("BUILD_WORKSPACE_DIRECTORY"); p != "" && isWorkspace(p) { |
| 33 | return p, nil |
| 34 | } |
| 35 | |
| Tim Windelschmidt | 62a02ea | 2024-04-17 02:33:55 +0200 | [diff] [blame] | 36 | if p, err := os.Getwd(); err == nil && isWorkspace(p) { |
| Serge Bazanski | cbd02be | 2021-09-24 13:39:12 +0200 | [diff] [blame] | 37 | return p, nil |
| 38 | } |
| 39 | |
| 40 | return "", fmt.Errorf("not invoked from `bazel run` and not running in workspace directory") |
| 41 | } |