gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/test/util/test_util_runfiles.cc (about)

     1  // Copyright 2019 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  #include <iostream>
    16  #include <string>
    17  
    18  #include "test/util/fs_util.h"
    19  #include "test/util/test_util.h"
    20  #include "tools/cpp/runfiles/runfiles.h"
    21  
    22  namespace gvisor {
    23  namespace testing {
    24  
    25  std::string RunfilePath(std::string path) {
    26    static const bazel::tools::cpp::runfiles::Runfiles* const runfiles = [] {
    27      std::string error;
    28      auto* runfiles =
    29          bazel::tools::cpp::runfiles::Runfiles::CreateForTest(&error);
    30      if (runfiles == nullptr) {
    31        std::cerr << "Unable to find runfiles: " << error << std::endl;
    32      }
    33      return runfiles;
    34    }();
    35  
    36    if (!runfiles) {
    37      // Can't find runfiles? This probably won't work, but __main__/path is our
    38      // best guess.
    39      return JoinPath("__main__", path);
    40    }
    41  
    42    // Try to resolve the path as it was passed to us, and check that it exists
    43    // before returning.
    44    std::string runfile_path = runfiles->Rlocation(JoinPath("__main__", path));
    45    struct stat st = {};
    46    if (!runfile_path.empty() && stat(runfile_path.c_str(), &st) == 0) {
    47      // Found it.
    48      return runfile_path;
    49    }
    50  
    51    // You are not gonna like this, but go_binary data dependencies have an extra
    52    // directory name with a "_" suffix, so we must check for that path too.
    53    //
    54    // For example, a go_binary with name"//foo/bar:baz" will be placed in
    55    // "<runfiles_dir>/foo/bar/baz_/baz".
    56    //
    57    // See
    58    // https://github.com/bazelbuild/rules_go/blob/d2a3cf2d6b18f5be19adccc6a6806e0c3b8c410b/go/private/context.bzl#L137.
    59    absl::string_view dirname = Dirname(path);
    60    absl::string_view basename = Basename(path);
    61    std::string go_binary_path =
    62        JoinPath(dirname, absl::StrCat(basename, "_"), basename);
    63    return runfiles->Rlocation(JoinPath("__main__", go_binary_path));
    64  }
    65  
    66  }  // namespace testing
    67  }  // namespace gvisor