From 73658a7629e618f779112949e653ca04a0627441 Mon Sep 17 00:00:00 2001 From: James Rowe Date: Thu, 16 Mar 2017 21:00:16 -0600 Subject: [PATCH] Move TrimSourcePath to string_util --- src/common/string_util.cpp | 22 ++++++++++++++++++++++ src/common/string_util.h | 12 ++++++++++++ 2 files changed, 34 insertions(+) diff --git a/src/common/string_util.cpp b/src/common/string_util.cpp index bad311793..9d5ae5bb4 100644 --- a/src/common/string_util.cpp +++ b/src/common/string_util.cpp @@ -462,4 +462,26 @@ std::string StringFromFixedZeroTerminatedBuffer(const char* buffer, size_t max_l return std::string(buffer, len); } + +const char* TrimSourcePath(const char* path, const char* root) { + const char* p = path; + + while (*p != '\0') { + const char* next_slash = p; + while (*next_slash != '\0' && *next_slash != '/' && *next_slash != '\\') { + ++next_slash; + } + + bool is_src = Common::ComparePartialString(p, next_slash, root); + p = next_slash; + + if (*p != '\0') { + ++p; + } + if (is_src) { + path = p; + } + } + return path; +} } diff --git a/src/common/string_util.h b/src/common/string_util.h index 075bf4ecb..f340e321d 100644 --- a/src/common/string_util.h +++ b/src/common/string_util.h @@ -134,4 +134,16 @@ bool ComparePartialString(InIt begin, InIt end, const char* other) { * NUL-terminated then the string ends at max_len characters. */ std::string StringFromFixedZeroTerminatedBuffer(const char* buffer, size_t max_len); + +/** + * Attempts to trim an arbitrary prefix from `path`, leaving only the part starting at `root`. It's + * intended to be used to strip a system-specific build directory from the `__FILE__` macro, + * leaving only the path relative to the sources root. + * + * @param path The input file path as a null-terminated string + * @param root The name of the root source directory as a null-terminated string. Path up to and + * including the last occurrence of this name will be stripped + * @return A pointer to the same string passed as `path`, but starting at the trimmed portion + */ +const char* TrimSourcePath(const char* path, const char* root = "src"); }