blob: 5213504aabe10d9aeb58df09cb9668a7fc1e2c8f [file] [log] [blame]
Tim Windelschmidt6d33a432025-02-04 14:34:25 +01001// Copyright The Monogon Project Authors.
2// SPDX-License-Identifier: Apache-2.0
3
Serge Bazanskicbd02be2021-09-24 13:39:12 +02004package toolbase
5
6import (
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.
14func 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 Windelschmidt99e15112025-02-05 17:38:16 +010025// 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 Bazanskicbd02be2021-09-24 13:39:12 +020028//
29// If the workspace directory path cannot be inferred based on the above
30// assumptions, an error is returned.
31func WorkspaceDirectory() (string, error) {
32 if p := os.Getenv("BUILD_WORKSPACE_DIRECTORY"); p != "" && isWorkspace(p) {
33 return p, nil
34 }
35
Tim Windelschmidt62a02ea2024-04-17 02:33:55 +020036 if p, err := os.Getwd(); err == nil && isWorkspace(p) {
Serge Bazanskicbd02be2021-09-24 13:39:12 +020037 return p, nil
38 }
39
40 return "", fmt.Errorf("not invoked from `bazel run` and not running in workspace directory")
41}