[FileSystem] Add expand_tilde function

In D54435 there was some discussion about the expand_tilde flag for
real_path that I wanted to expose through the VFS. The consensus is that
these two things should be separate functions. Since we already have the
code for this I went ahead and added a function expand_tilde that does
just that.

Differential revision: https://reviews.llvm.org/D54448

llvm-svn: 346776
This commit is contained in:
Jonas Devlieghere 2018-11-13 18:23:32 +00:00
parent 7716ddf18d
commit b23f430ec9
4 changed files with 50 additions and 0 deletions

View File

@ -349,6 +349,12 @@ std::error_code create_hard_link(const Twine &to, const Twine &from);
std::error_code real_path(const Twine &path, SmallVectorImpl<char> &output,
bool expand_tilde = false);
/// Expands ~ expressions to the user's home directory. On Unix ~user
/// directories are resolved as well.
///
/// @param path The path to resolve.
void expand_tilde(const Twine &path, SmallVectorImpl<char> &output);
/// Get the current path.
///
/// @param result Holds the current path on return.

View File

@ -550,6 +550,18 @@ static void expandTildeExpr(SmallVectorImpl<char> &Path) {
llvm::sys::path::append(Path, Storage);
}
void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
dest.clear();
if (path.isTriviallyEmpty())
return;
path.toVector(dest);
expandTildeExpr(dest);
return;
}
static file_type typeForMode(mode_t Mode) {
if (S_ISDIR(Mode))
return file_type::directory_file;

View File

@ -1253,6 +1253,17 @@ static void expandTildeExpr(SmallVectorImpl<char> &Path) {
Path.insert(Path.begin() + 1, HomeDir.begin() + 1, HomeDir.end());
}
void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
dest.clear();
if (path.isTriviallyEmpty())
return;
path.toVector(dest);
expandTildeExpr(dest);
return;
}
std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
bool expand_tilde) {
dest.clear();

View File

@ -516,6 +516,8 @@ TEST_F(FileSystemTest, RealPath) {
EXPECT_EQ(Expected, Actual);
SmallString<64> HomeDir;
// This can fail if $HOME is not set and getpwuid fails.
bool Result = llvm::sys::path::home_directory(HomeDir);
if (Result) {
ASSERT_NO_ERROR(fs::real_path(HomeDir, Expected));
@ -528,6 +530,25 @@ TEST_F(FileSystemTest, RealPath) {
ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/test1"));
}
TEST_F(FileSystemTest, ExpandTilde) {
SmallString<64> Expected;
SmallString<64> Actual;
SmallString<64> HomeDir;
// This can fail if $HOME is not set and getpwuid fails.
bool Result = llvm::sys::path::home_directory(HomeDir);
if (Result) {
fs::expand_tilde(HomeDir, Expected);
fs::expand_tilde("~", Actual);
EXPECT_EQ(Expected, Actual);
path::append(Expected, "foo");
fs::expand_tilde("~/foo", Actual);
EXPECT_EQ(Expected, Actual);
}
}
#ifdef LLVM_ON_UNIX
TEST_F(FileSystemTest, RealPathNoReadPerm) {
SmallString<64> Expanded;