From a1e9c30af2c38fa1aebadec78bebe3d71274d55b Mon Sep 17 00:00:00 2001 From: Josh Holtrop Date: Sun, 22 Jun 2014 20:36:54 -0400 Subject: [PATCH] add Path::ext() --- src/lib/include/jes/Path.h | 1 + src/lib/src/Path.cc | 26 ++++++++++++++++++++++++++ test/src/test_Path.cc | 11 +++++++++++ 3 files changed, 38 insertions(+) diff --git a/src/lib/include/jes/Path.h b/src/lib/include/jes/Path.h index b92ce3e..89b75fc 100644 --- a/src/lib/include/jes/Path.h +++ b/src/lib/include/jes/Path.h @@ -15,6 +15,7 @@ namespace jes Path(const char * path); Path(const std::string & path); PathRef dirname(); + PathRef ext(const std::string & new_ext); PathRef join(const Path & other); const std::string & to_s() { return m_path; } bool exists(); diff --git a/src/lib/src/Path.cc b/src/lib/src/Path.cc index 2773f74..32c62b1 100644 --- a/src/lib/src/Path.cc +++ b/src/lib/src/Path.cc @@ -20,6 +20,8 @@ namespace jes PathRef Path::dirname() { + if (m_path.size() == 0) + return new Path(""); size_t i = m_path.size() - 1; while (m_path[i] == '/') { @@ -42,6 +44,30 @@ namespace jes return new Path(std::string(m_path, 0, i + 1)); } + PathRef Path::ext(const std::string & new_ext) + { + if (m_path.size() == 0) + return new Path(""); + size_t i = m_path.size() - 1; + while (m_path[i] != '.') + { + if ((i == 0) || (m_path[i] == '/')) + { + i = m_path.size(); + break; + } + i--; + } + if (new_ext[0] == '.') + { + return new Path(std::string(m_path, 0, i) + new_ext); + } + else + { + return new Path(std::string(m_path, 0, i) + "." + new_ext); + } + } + PathRef Path::join(const Path & other) { if (m_path.size() > 0 && *m_path.rbegin() == '/') diff --git a/test/src/test_Path.cc b/test/src/test_Path.cc index 9a1a92d..fcc7752 100644 --- a/test/src/test_Path.cc +++ b/test/src/test_Path.cc @@ -31,6 +31,7 @@ TEST(PathTest, joins_two_paths_together) TEST(PathTest, dirname) { + EXPECT_EQ("", Path("").dirname()->to_s()); EXPECT_EQ("/one/two", Path("/one/two/f.c").dirname()->to_s()); EXPECT_EQ("C:/a", Path("C:\\a\\b\\").dirname()->to_s()); EXPECT_EQ("/", Path("/").dirname()->to_s()); @@ -40,6 +41,16 @@ TEST(PathTest, dirname) EXPECT_EQ("a", Path("a/b").dirname()->to_s()); } +TEST(PathTest, ext) +{ + EXPECT_EQ("", Path("").ext("")->to_s()); + EXPECT_EQ("", Path("").ext("h")->to_s()); + EXPECT_EQ("file.h", Path("file.c").ext(".h")->to_s()); + EXPECT_EQ("file.h", Path("file.c").ext("h")->to_s()); + EXPECT_EQ("/some/crazy/dir/foo.txt", Path("/some/crazy/dir/foo").ext(".txt")->to_s()); + EXPECT_EQ("/some/crazy/dir/foo.txt", Path("/some/crazy/dir/foo").ext("txt")->to_s()); +} + TEST(PathTest, exists) { EXPECT_TRUE(Path("runtime").exists());