Permalink
Browse files

Merge pull request #8 from laurence6/master

Fix Path::expand, close #7.
  • Loading branch information...
pbeckingham committed May 26, 2018
2 parents 81fc6f7 + 9e5c930 commit a802f69191a2bea81d2f78870732e856b52482c1
Showing with 28 additions and 22 deletions.
  1. +24 −21 src/FS.cpp
  2. +4 −1 test/fs.t.cpp
@@ -258,56 +258,59 @@ bool Path::rename (const std::string& new_name)
// ~ --> /home/user
// ~foo/x --> /home/foo/s
// ~/x --> /home/foo/x
// . --> $PWD
// ./x --> $PWD/x
// x --> $PWD/x
std::string Path::expand (const std::string& in)
{
std::string copy = in;

auto tilde = copy.find ('~');
std::string::size_type slash;

if (tilde != std::string::npos)
if (in.empty ())
{ }

else if (in.front () == '~')
{
const char *home = getenv("HOME");
const char* home = getenv ("HOME");
if (home == nullptr)
{
struct passwd* pw = getpwuid (getuid ());
home = pw->pw_dir;
}

// Convert: ~ --> /home/user
if (copy.length () == 1)
if (in.length () == 1)
copy = home;

// Convert: ~/x --> /home/user/x
else if (copy.length () > tilde + 1 &&
copy[tilde + 1] == '/')
{
copy.replace (tilde, 1, home);
}
else if (in.at (1) == '/')
copy = home + in.substr (1);

// Convert: ~foo/x --> /home/foo/x
else if ((slash = copy.find ('/', tilde)) != std::string::npos)
else if ((slash = in.find ('/', 1)) != std::string::npos)
{
std::string name = copy.substr (tilde + 1, slash - tilde - 1);
std::string name = in.substr (1, slash - 1);
struct passwd* pw = getpwnam (name.c_str ());
if (pw)
copy.replace (tilde, slash - tilde, pw->pw_dir);
copy = pw->pw_dir + in.substr (slash);
}
}

// Relative paths
else if (in.length () > 2 &&
in.substr (0, 2) == "./")
{
copy = Directory::cwd () + in.substr (1);
}
else if (in.length () > 1 &&
in[0] != '.' &&
in[0] != '/')
else if (in.front () != '/')
{
copy = Directory::cwd () + '/' + in;
// Convert: ., ./ --> $PWD
if (in == ".")
copy = Directory::cwd ();

// Convert: ./x --> $PWD/x
else if (in.substr (0, 2) == "./")
copy = Directory::cwd () + in.substr (1);

// Convert: x --> $PWD/x
else
copy = Directory::cwd () + '/' + in;
}

return copy;
@@ -33,7 +33,7 @@

int main (int, char**)
{
UnitTest t (117);
UnitTest t (120);

try
{
@@ -99,6 +99,9 @@ int main (int, char**)
// static std::string expand (const std::string&);
t.ok (Path::expand ("~") != "~", "Path::expand ~ != ~");
t.ok (Path::expand ("~/") != "~/", "Path::expand ~/ != ~/");
t.ok (Path::expand (".") != ".", "Path::expand . != .");
t.ok (Path::expand ("./") != "./", "Path::expand ./ != ./");
t.ok (Path::expand (".a") != ".a", "Path::expand .a != .a");

// static std::vector <std::string> glob (const std::string&);
std::vector <std::string> out = Path::glob ("/tmp");

0 comments on commit a802f69

Please sign in to comment.