Path: blob/main/libshaderc_util/src/file_finder.cc
1560 views
// Copyright 2015 The Shaderc Authors. All rights reserved.1//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 at5//6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314#include "libshaderc_util/file_finder.h"15#include "libshaderc_util/string_piece.h"1617#include <cassert>18#include <fstream>19#include <ios>2021namespace {2223// Returns "" if path is empty or ends in '/'. Otherwise, returns "/".24std::string MaybeSlash(const shaderc_util::string_piece& path) {25return (path.empty() || path.back() == '/') ? "" : "/";26}2728} // anonymous namespace2930namespace shaderc_util {3132std::string FileFinder::FindReadableFilepath(33const std::string& filename) const {34assert(!filename.empty());35static const auto for_reading = std::ios_base::in;36std::filebuf opener;37for (const auto& prefix : search_path_) {38const std::string prefixed_filename =39prefix + MaybeSlash(prefix) + filename;40if (opener.open(prefixed_filename, for_reading)) return prefixed_filename;41}42return "";43}4445std::string FileFinder::FindRelativeReadableFilepath(46const std::string& requesting_file, const std::string& filename) const {47assert(!filename.empty());4849string_piece dir_name(requesting_file);5051size_t last_slash = requesting_file.find_last_of("/\\");52if (last_slash != std::string::npos) {53dir_name = string_piece(requesting_file.c_str(),54requesting_file.c_str() + last_slash);55}5657if (dir_name.size() == requesting_file.size()) {58dir_name.clear();59}6061static const auto for_reading = std::ios_base::in;62std::filebuf opener;63const std::string relative_filename =64dir_name.str() + MaybeSlash(dir_name) + filename;65if (opener.open(relative_filename, for_reading)) return relative_filename;6667return FindReadableFilepath(filename);68}6970} // namespace shaderc_util717273