bazel_working_dir.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef CARBON_COMMON_BAZEL_WORKING_DIR_H_
  5. #define CARBON_COMMON_BAZEL_WORKING_DIR_H_
  6. #include <stdlib.h>
  7. #include <filesystem>
  8. #include <system_error>
  9. #include "common/check.h"
  10. #include "common/filesystem.h"
  11. namespace Carbon {
  12. // Change working directory to behave as if it is where `bazel run` was invoked.
  13. //
  14. // Accepts an optional `exe_path` argument that will be adjusted to continue to
  15. // be valid after this adjustment.
  16. //
  17. // There is no reasonable recovery we can do if either we can't make the path
  18. // absolute or we can't change directory. As a consequence, this aborts if
  19. // either of those fail rather than propagating any error.
  20. inline auto SetWorkingDirForBazelRun(std::filesystem::path exe_path = {})
  21. -> std::filesystem::path {
  22. char* build_working_dir = getenv("BUILD_WORKING_DIRECTORY");
  23. if (build_working_dir == nullptr) {
  24. return exe_path;
  25. }
  26. // Adjust `exe_path` before changing directory.
  27. if (!exe_path.empty()) {
  28. std::error_code err;
  29. exe_path = std::filesystem::absolute(exe_path, err);
  30. CARBON_CHECK(!err, "Unable to make an absolute path for `{0}`: {1}",
  31. exe_path, err.message());
  32. }
  33. auto chdir_result = Filesystem::Cwd().Chdir(build_working_dir);
  34. CARBON_CHECK(chdir_result.ok(),
  35. "Unable to change working directory to `{0}`: {1}",
  36. build_working_dir, chdir_result.error());
  37. return exe_path;
  38. }
  39. } // namespace Carbon
  40. #endif // CARBON_COMMON_BAZEL_WORKING_DIR_H_