Skip to content

Commit 98c89ee

Browse files
committed
Path: added isRelative()
1 parent 6bbfee2 commit 98c89ee

3 files changed

Lines changed: 35 additions & 0 deletions

File tree

lib/path.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,12 @@ bool Path::isAbsolute(const std::string& path)
189189
#endif
190190
}
191191

192+
bool Path::isRelative(const std::string& path)
193+
{
194+
const std::string p = fromNativeSeparators(path);
195+
return (p.find('/') != std::string::npos) && !isAbsolute(path);
196+
}
197+
192198
std::string Path::getRelativePath(const std::string& absolutePath, const std::vector<std::string>& basePaths)
193199
{
194200
for (const std::string &bp : basePaths) {

lib/path.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,13 @@ class CPPCHECKLIB Path {
118118
*/
119119
static bool isAbsolute(const std::string& path);
120120

121+
/**
122+
* @brief Check if given path is relative
123+
* @param path Path to check
124+
* @return true if given path is relative
125+
*/
126+
static bool isRelative(const std::string& path);
127+
121128
/**
122129
* @brief Create a relative path from an absolute one, if absolute path is inside the basePaths.
123130
* @param absolutePath Path to be made relative.

test/testpath.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ class TestPath : public TestFixture {
5757
TEST_CASE(getAbsolutePath);
5858
TEST_CASE(exists);
5959
TEST_CASE(fromNativeSeparators);
60+
TEST_CASE(isRelative);
6061
}
6162

6263
void removeQuotationMarks() const {
@@ -618,6 +619,27 @@ class TestPath : public TestFixture {
618619
ASSERT_EQUALS("//lib/file.c", Path::fromNativeSeparators("\\\\lib\\file.c"));
619620
ASSERT_EQUALS("./lib/file.c", Path::fromNativeSeparators(".\\lib\\file.c"));
620621
}
622+
623+
void isRelative() const {
624+
ASSERT_EQUALS(true, Path::isRelative("dir/file"));
625+
ASSERT_EQUALS(true, Path::isRelative("dir\\file"));
626+
627+
// TODO: is this expected?
628+
ASSERT_EQUALS(true, Path::isRelative("file/"));
629+
ASSERT_EQUALS(true, Path::isRelative("file\\"));
630+
631+
ASSERT_EQUALS(false, Path::isRelative("file"));
632+
ASSERT_EQUALS(false, Path::isRelative("/dir/file"));
633+
634+
// TODO: this is not detected as absolute path in _WIN32 builds
635+
#ifdef _WIN32
636+
ASSERT_EQUALS(false, Path::isRelative("c:\\dir\\file"));
637+
ASSERT_EQUALS(false, Path::isRelative("c:/dir/file"));
638+
#else
639+
ASSERT_EQUALS(true, Path::isRelative("c:\\dir\\file"));
640+
ASSERT_EQUALS(true, Path::isRelative("c:/dir/file"));
641+
#endif
642+
}
621643
};
622644

623645
REGISTER_TEST(TestPath)

0 commit comments

Comments
 (0)