forked from RobotLocomotion/drake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
find_resource.cc
309 lines (269 loc) · 10.8 KB
/
find_resource.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
#include "drake/common/find_resource.h"
#include <cstdlib>
#include <utility>
#include <vector>
#include <fmt/format.h>
#include "drake/common/drake_marker.h"
#include "drake/common/drake_throw.h"
#include "drake/common/filesystem.h"
#include "drake/common/find_loaded_library.h"
#include "drake/common/find_runfiles.h"
#include "drake/common/never_destroyed.h"
#include "drake/common/text_logging.h"
using std::getenv;
using std::string;
namespace drake {
using Result = FindResourceResult;
std::optional<string>
Result::get_absolute_path() const {
return absolute_path_;
}
string
Result::get_absolute_path_or_throw() const {
// If we have a path, return it.
const auto& optional_path = get_absolute_path();
if (optional_path) { return *optional_path; }
// Otherwise, throw the error message.
const auto& optional_error = get_error_message();
DRAKE_ASSERT(optional_error != std::nullopt);
throw std::runtime_error(*optional_error);
}
std::optional<string>
Result::get_error_message() const {
// If an error has been set, return it.
if (error_message_ != std::nullopt) {
DRAKE_ASSERT(absolute_path_ == std::nullopt);
return error_message_;
}
// If successful, return no-error.
if (absolute_path_ != std::nullopt) {
return std::nullopt;
}
// Both optionals are null; we are empty; return a default error message.
DRAKE_ASSERT(resource_path_.empty());
return string("No resource was requested (empty result)");
}
string Result::get_resource_path() const {
return resource_path_;
}
Result Result::make_success(string resource_path, string absolute_path) {
DRAKE_THROW_UNLESS(!resource_path.empty());
DRAKE_THROW_UNLESS(!absolute_path.empty());
Result result;
result.resource_path_ = std::move(resource_path);
result.absolute_path_ = std::move(absolute_path);
result.CheckInvariants();
return result;
}
Result Result::make_error(string resource_path, string error_message) {
DRAKE_THROW_UNLESS(!resource_path.empty());
DRAKE_THROW_UNLESS(!error_message.empty());
Result result;
result.resource_path_ = std::move(resource_path);
result.error_message_ = std::move(error_message);
result.CheckInvariants();
return result;
}
Result Result::make_empty() {
Result result;
result.CheckInvariants();
return result;
}
void Result::CheckInvariants() {
if (resource_path_.empty()) {
// For our "empty" state, both success and error must be empty.
DRAKE_DEMAND(absolute_path_ == std::nullopt);
DRAKE_DEMAND(error_message_ == std::nullopt);
} else {
// For our "non-empty" state, we must have exactly one of success or error.
DRAKE_DEMAND(
(absolute_path_ == std::nullopt) != (error_message_ == std::nullopt));
}
// When non-nullopt, the path and error cannot be the empty string.
DRAKE_DEMAND((absolute_path_ == std::nullopt) || !absolute_path_->empty());
DRAKE_DEMAND((error_message_ == std::nullopt) || !error_message_->empty());
}
namespace {
// A valid resource root will always contain this file.
const char* const kSentinelRelpath = "drake/.drake-find_resource-sentinel";
bool StartsWith(const string& str, const string& prefix) {
return str.compare(0, prefix.size(), prefix) == 0;
}
// Returns true iff the path is relative (not absolute nor empty).
bool IsRelativePath(const string& path) {
return !path.empty() && (path[0] != '/');
}
// Taking `root` to be Drake's resource root, confirm that the sentinel file
// exists and return the found resource_path (or an error if either the
// sentinel or resource_path was missing).
Result CheckAndMakeResult(
const string& root_description, const string& root,
const string& resource_path) {
DRAKE_DEMAND(!root_description.empty());
DRAKE_DEMAND(!root.empty());
DRAKE_DEMAND(!resource_path.empty());
DRAKE_DEMAND(filesystem::is_directory({root}));
DRAKE_DEMAND(IsRelativePath(resource_path));
// Check for the sentinel.
if (!filesystem::is_regular_file({root + "/" + kSentinelRelpath})) {
return Result::make_error(resource_path, fmt::format(
"Could not find Drake resource_path '{}' because {} specified a "
"resource root of '{}' but that root did not contain the expected "
"sentinel file '{}'.",
resource_path, root_description, root, kSentinelRelpath));
}
// Check for the resource_path.
const string abspath = root + '/' + resource_path;
if (!filesystem::is_regular_file({abspath})) {
return Result::make_error(resource_path, fmt::format(
"Could not find Drake resource_path '{}' because {} specified a "
"resource root of '{}' but that root did not contain the expected "
"file '{}'.",
resource_path, root_description, root, abspath));
}
return Result::make_success(resource_path, abspath);
}
// Opportunistically searches inside the attic for multibody resource paths.
// This function is not unit tested -- only acceptance-tested by the fact that
// none of the tests in the attic fail.
std::optional<string> MaybeFindResourceInAttic(const string& resource_path) {
const string prefix("drake/");
DRAKE_DEMAND(StartsWith(resource_path, prefix));
const string substr = resource_path.substr(prefix.size());
for (const auto& directory : {
"multibody/collision/test",
"multibody/parsers/test/package_map_test",
"multibody/parsers/test/parsers_frames_test",
"multibody/parsers/test/urdf_parser_test",
"multibody/rigid_body_plant/test",
"multibody/shapes/test",
"multibody/test",
"systems/controllers/qp_inverse_dynamics/test"
}) {
if (StartsWith(substr, directory)) {
const auto rlocation_or_error =
FindRunfile(prefix + string("attic/") + substr);
if (rlocation_or_error.error.empty()) {
return rlocation_or_error.abspath;
}
}
}
return std::nullopt;
}
// If the DRAKE_RESOURCE_ROOT environment variable is usable as a resource
// root, returns its value, else returns nullopt.
std::optional<string> MaybeGetEnvironmentResourceRoot() {
const char* const env_name = kDrakeResourceRootEnvironmentVariableName;
const char* const env_value = getenv(env_name);
if (!env_value) {
log()->debug(
"FindResource ignoring {} because it is not set.",
env_name);
return std::nullopt;
}
const std::string root{env_value};
if (!filesystem::is_directory({root})) {
static const logging::Warn log_once(
"FindResource ignoring {}='{}' because it does not exist.",
env_name, env_value);
return std::nullopt;
}
if (!filesystem::is_directory({root + "/drake"})) {
static const logging::Warn log_once(
"FindResource ignoring {}='{}' because it does not contain a 'drake' "
"subdirectory.", env_name, env_value);
return std::nullopt;
}
if (!filesystem::is_regular_file({root + "/" + kSentinelRelpath})) {
static const logging::Warn log_once(
"FindResource ignoring {}='{}' because it does not contain the "
"expected sentinel file '{}'.", env_name, env_value, kSentinelRelpath);
return std::nullopt;
}
return root;
}
// If we are linked against libdrake_marker.so, and the install-tree-relative
// path resolves correctly, returns the install tree resource root, else
// returns nullopt.
std::optional<string> MaybeGetInstallResourceRoot() {
// Ensure that we have the library loaded.
DRAKE_DEMAND(drake::internal::drake_marker_lib_check() == 1234);
std::optional<string> libdrake_dir = LoadedLibraryPath("libdrake_marker.so");
if (libdrake_dir) {
const string root = *libdrake_dir + "/../share";
if (filesystem::is_directory({root})) {
return root;
} else {
log()->debug("FindResource ignoring CMake install candidate '{}' "
"because it does not exist", root);
}
} else {
log()->debug("FindResource has no CMake install candidate");
}
return std::nullopt;
}
} // namespace
const char* const kDrakeResourceRootEnvironmentVariableName =
"DRAKE_RESOURCE_ROOT";
Result FindResource(const string& resource_path) {
// Check if resource_path is well-formed: a relative path that starts with
// "drake" as its first directory name. A valid example would look like:
// "drake/common/test/find_resource_test_data.txt". Requiring strings passed
// to drake::FindResource to start with "drake" is redundant, but preserves
// compatibility with the original semantics of this function; if we want to
// offer a function that takes paths without "drake", we can use a new name.
if (!IsRelativePath(resource_path)) {
return Result::make_error(resource_path, fmt::format(
"Drake resource_path '{}' is not a relative path.",
resource_path));
}
const string prefix("drake/");
if (!StartsWith(resource_path, prefix)) {
return Result::make_error(resource_path, fmt::format(
"Drake resource_path '{}' does not start with {}.",
resource_path, prefix));
}
// We will check each potential resource root one by one. The first root
// that is present will be chosen, even if does not contain the particular
// resource_path. We expect that all sources offer all files.
// (1) Check the environment variable.
if (auto guess = MaybeGetEnvironmentResourceRoot()) {
return CheckAndMakeResult(
fmt::format("{} environment variable",
kDrakeResourceRootEnvironmentVariableName),
*guess, resource_path);
}
// (2) Check the Runfiles.
if (HasRunfiles()) {
auto rlocation_or_error = FindRunfile(resource_path);
if (rlocation_or_error.error.empty()) {
return Result::make_success(
resource_path, rlocation_or_error.abspath);
}
// As a compatibility shim, for resource paths that have been moved into the
// attic, we opportunistically try a fallback search path for them. This
// heuristic is only helpful for source trees -- any install data files from
// the attic should be installed without the "attic/" portion of their path.
if (auto attic_abspath = MaybeFindResourceInAttic(resource_path)) {
return Result::make_success(resource_path, *attic_abspath);
}
return Result::make_error(resource_path, rlocation_or_error.error);
}
// (3) Check the `libdrake_marker.so` location in the install tree.
if (auto guess = MaybeGetInstallResourceRoot()) {
return CheckAndMakeResult(
"Drake CMake install marker",
*guess, resource_path);
}
// No resource roots were found.
return Result::make_error(resource_path, fmt::format(
"Could not find Drake resource_path '{}' because no resource roots of "
"any kind could be found: {} is unset, a {} could not be created, and "
"there is no Drake CMake install marker.",
resource_path, kDrakeResourceRootEnvironmentVariableName,
"bazel::tools::cpp::runfiles::Runfiles"));
}
string FindResourceOrThrow(const string& resource_path) {
return FindResource(resource_path).get_absolute_path_or_throw();
}
} // namespace drake