* \brief Resolve `_file` indirection in a property-map JSON object. * * Returns a self-contained JSON object that no longer references external * files. Inline `_`-meta keys take precedence over the external file's meta * keys. If `_file` is set, the external file must contain a property map * and the inline object must not contain any non-meta keys. Only one level * of indirecti
| 249 | * the caller once the map has been assembled. |
| 250 | */ |
| 251 | json ResolvePropertyMap(const json &mapJson, const fs::path &basePath, const std::string &context) |
| 252 | { |
| 253 | if (!mapJson.is_object()) |
| 254 | { |
| 255 | mitkThrow() << "Property map in " << context << " must be a JSON object."; |
| 256 | } |
| 257 | |
| 258 | const auto fileIt = mapJson.find(META_FILE); |
| 259 | if (fileIt == mapJson.end() || fileIt->is_null()) |
| 260 | return mapJson; |
| 261 | |
| 262 | if (!fileIt->is_string()) |
| 263 | { |
| 264 | mitkThrow() << "'_file' in property map (" << context << ") must be a string."; |
| 265 | } |
| 266 | |
| 267 | // inline must only contain meta keys when _file is present |
| 268 | for (auto it = mapJson.begin(); it != mapJson.end(); ++it) |
| 269 | { |
| 270 | if (!it.key().empty() && it.key().front() != '_') |
| 271 | { |
| 272 | mitkThrow() << "Property map in " << context |
| 273 | << " specifies '_file' but also contains inline property '" << it.key() |
| 274 | << "'. Mixing the two is not allowed."; |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | const fs::path path = ResolvePath(basePath, fileIt->get<std::string>()); |
| 279 | std::ifstream in(path.string()); |
| 280 | if (!in.good()) |
| 281 | { |
| 282 | mitkThrow() << "Property map '_file' in " << context << " refers to missing/unreadable file '" |
| 283 | << path.string() << "'."; |
| 284 | } |
| 285 | |
| 286 | json external; |
| 287 | try |
| 288 | { |
| 289 | in >> external; |
| 290 | } |
| 291 | catch (const json::exception &e) |
| 292 | { |
| 293 | mitkThrow() << "Property map '_file' in " << context << " ('" << path.string() |
| 294 | << "') is not valid JSON: " << e.what(); |
| 295 | } |
| 296 | |
| 297 | if (!external.is_object()) |
| 298 | { |
| 299 | mitkThrow() << "Property map file '" << path.string() << "' (referenced from " << context |
| 300 | << ") must contain a JSON object."; |
| 301 | } |
| 302 | |
| 303 | // Inline meta keys override external ones. |
| 304 | for (auto it = mapJson.begin(); it != mapJson.end(); ++it) |
| 305 | { |
| 306 | if (it.key() == META_FILE) |
| 307 | continue; |
| 308 | external[it.key()] = it.value(); |