finder.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /* Copyright 2016 The Bazel Authors. All rights reserved.
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. // Package wspace provides functions to locate and modify a bazel WORKSPACE file.
  13. package wspace
  14. import (
  15. "os"
  16. "path/filepath"
  17. "strings"
  18. )
  19. const workspaceFile = "WORKSPACE"
  20. // Find searches from the given dir and up for the WORKSPACE file
  21. // returning the directory containing it, or an error if none found in the tree.
  22. func Find(dir string) (string, error) {
  23. dir, err := filepath.Abs(dir)
  24. if err != nil {
  25. return "", err
  26. }
  27. for {
  28. _, err = os.Stat(filepath.Join(dir, workspaceFile))
  29. if err == nil {
  30. return dir, nil
  31. }
  32. if !os.IsNotExist(err) {
  33. return "", err
  34. }
  35. if strings.HasSuffix(dir, string(os.PathSeparator)) { // stop at root dir
  36. return "", os.ErrNotExist
  37. }
  38. dir = filepath.Dir(dir)
  39. }
  40. }