diff --git a/lib/path.cpp b/lib/path.cpp index 54a8d7d9a..1af4d36e0 100644 --- a/lib/path.cpp +++ b/lib/path.cpp @@ -104,6 +104,19 @@ std::string Path::simplifyPath(const char *originalPath) return oss.str(); } +std::string Path::getPathFromFilename(const std::string &filename) +{ + std::string path = ""; + + std::size_t pos = filename.find_last_of("\\/"); + + if (pos != std::string::npos) + path = filename.substr(0, 1 + pos); + + return path; +} + + bool Path::sameFileName(const std::string &fname1, const std::string &fname2) { #if defined(__linux__) || defined(__sun) || defined(__hpux) diff --git a/lib/path.h b/lib/path.h index ed20eb474..17d8ee9e0 100644 --- a/lib/path.h +++ b/lib/path.h @@ -56,6 +56,13 @@ public: */ static std::string simplifyPath(const char *originalPath); + /** + * @brief Lookup the path part from a filename (e.g., '/tmp/a.h' -> '/tmp/', 'a.h' -> '') + * @param filename filename to lookup, must have / -separators. + * @return path part of the filename + */ + static std::string getPathFromFilename(const std::string &filename); + /** * @brief Compare filenames to see if they are the same. * On Linux the comparison is case-sensitive. On Windows it is case-insensitive. diff --git a/lib/preprocessor.cpp b/lib/preprocessor.cpp index 263d9ca15..0b3bb7bbb 100644 --- a/lib/preprocessor.cpp +++ b/lib/preprocessor.cpp @@ -815,15 +815,8 @@ void Preprocessor::preprocess(std::istream &srcCodeStream, std::string &processe fin.open(cur.c_str()); if (!fin.is_open()) { if (_settings && !_settings->nomsg.isSuppressed("missingInclude", cur, 1)) { - std::string path = ""; - - std::size_t pos = cur.find_last_of("\\/"); - - if (pos != std::string::npos) - path = cur.substr(0, 1 + pos); - missingIncludeFlag = true; - missingInclude(Path::toNativeSeparators(path), + missingInclude(Path::toNativeSeparators(Path::getPathFromFilename(cur)), 1, cur, true); diff --git a/test/testpath.cpp b/test/testpath.cpp index 7267a822d..e881e3e68 100644 --- a/test/testpath.cpp +++ b/test/testpath.cpp @@ -33,6 +33,7 @@ private: TEST_CASE(getRelative); TEST_CASE(is_c); TEST_CASE(is_cpp); + TEST_CASE(get_path_from_filename); } void simplify_path() const { @@ -117,6 +118,13 @@ private: ASSERT(Path::isCPP("C:\\foo\\index.cpp")); ASSERT(Path::isCPP("C:\\foo\\index.Cpp")); } + + void get_path_from_filename() const { + ASSERT_EQUALS("", Path::getPathFromFilename("index.h")); + ASSERT_EQUALS("/tmp/", Path::getPathFromFilename("/tmp/index.h")); + ASSERT_EQUALS("a/b/c/", Path::getPathFromFilename("a/b/c/index.h")); + ASSERT_EQUALS("a/b/c/", Path::getPathFromFilename("a/b/c/")); + } }; REGISTER_TEST(TestPath)