add Path::ext()

This commit is contained in:
Josh Holtrop 2014-06-22 20:36:54 -04:00
parent 87c3abe0fa
commit a1e9c30af2
3 changed files with 38 additions and 0 deletions

View File

@ -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();

View File

@ -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() == '/')

View File

@ -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());