head	1.1;
branch	1.1.1;
access;
symbols
	netbsd-11-0-RC4:1.1.1.9
	netbsd-11-0-RC3:1.1.1.9
	netbsd-11-0-RC2:1.1.1.9
	netbsd-11-0-RC1:1.1.1.9
	perseant-exfatfs-base-20250801:1.1.1.9
	netbsd-11:1.1.1.9.0.10
	netbsd-11-base:1.1.1.9
	netbsd-10-1-RELEASE:1.1.1.9
	perseant-exfatfs-base-20240630:1.1.1.9
	perseant-exfatfs:1.1.1.9.0.8
	perseant-exfatfs-base:1.1.1.9
	netbsd-8-3-RELEASE:1.1.1.6
	netbsd-9-4-RELEASE:1.1.1.8
	netbsd-10-0-RELEASE:1.1.1.9
	netbsd-10-0-RC6:1.1.1.9
	netbsd-10-0-RC5:1.1.1.9
	netbsd-10-0-RC4:1.1.1.9
	netbsd-10-0-RC3:1.1.1.9
	netbsd-10-0-RC2:1.1.1.9
	netbsd-10-0-RC1:1.1.1.9
	netbsd-10:1.1.1.9.0.6
	netbsd-10-base:1.1.1.9
	netbsd-9-3-RELEASE:1.1.1.8
	cjep_sun2x:1.1.1.9.0.4
	cjep_sun2x-base:1.1.1.9
	cjep_staticlib_x-base1:1.1.1.9
	netbsd-9-2-RELEASE:1.1.1.8
	cjep_staticlib_x:1.1.1.9.0.2
	cjep_staticlib_x-base:1.1.1.9
	netbsd-9-1-RELEASE:1.1.1.8
	phil-wifi-20200421:1.1.1.9
	phil-wifi-20200411:1.1.1.9
	phil-wifi-20200406:1.1.1.9
	netbsd-8-2-RELEASE:1.1.1.6
	netbsd-9-0-RELEASE:1.1.1.8
	netbsd-9-0-RC2:1.1.1.8
	netbsd-9-0-RC1:1.1.1.8
	netbsd-9:1.1.1.8.0.2
	netbsd-9-base:1.1.1.8
	phil-wifi-20190609:1.1.1.8
	netbsd-8-1-RELEASE:1.1.1.6
	netbsd-8-1-RC1:1.1.1.6
	pgoyette-compat-merge-20190127:1.1.1.7.2.1
	pgoyette-compat-20190127:1.1.1.8
	pgoyette-compat-20190118:1.1.1.8
	pgoyette-compat-1226:1.1.1.8
	pgoyette-compat-1126:1.1.1.8
	pgoyette-compat-1020:1.1.1.8
	pgoyette-compat-0930:1.1.1.8
	pgoyette-compat-0906:1.1.1.8
	netbsd-7-2-RELEASE:1.1.1.3.2.1
	pgoyette-compat-0728:1.1.1.8
	clang-337282:1.1.1.8
	netbsd-8-0-RELEASE:1.1.1.6
	phil-wifi:1.1.1.7.0.4
	phil-wifi-base:1.1.1.7
	pgoyette-compat-0625:1.1.1.7
	netbsd-8-0-RC2:1.1.1.6
	pgoyette-compat-0521:1.1.1.7
	pgoyette-compat-0502:1.1.1.7
	pgoyette-compat-0422:1.1.1.7
	netbsd-8-0-RC1:1.1.1.6
	pgoyette-compat-0415:1.1.1.7
	pgoyette-compat-0407:1.1.1.7
	pgoyette-compat-0330:1.1.1.7
	pgoyette-compat-0322:1.1.1.7
	pgoyette-compat-0315:1.1.1.7
	netbsd-7-1-2-RELEASE:1.1.1.3.2.1
	pgoyette-compat:1.1.1.7.0.2
	pgoyette-compat-base:1.1.1.7
	netbsd-7-1-1-RELEASE:1.1.1.3.2.1
	clang-319952:1.1.1.7
	matt-nb8-mediatek:1.1.1.6.0.10
	matt-nb8-mediatek-base:1.1.1.6
	clang-309604:1.1.1.7
	perseant-stdc-iso10646:1.1.1.6.0.8
	perseant-stdc-iso10646-base:1.1.1.6
	netbsd-8:1.1.1.6.0.6
	netbsd-8-base:1.1.1.6
	prg-localcount2-base3:1.1.1.6
	prg-localcount2-base2:1.1.1.6
	prg-localcount2-base1:1.1.1.6
	prg-localcount2:1.1.1.6.0.4
	prg-localcount2-base:1.1.1.6
	pgoyette-localcount-20170426:1.1.1.6
	bouyer-socketcan-base1:1.1.1.6
	pgoyette-localcount-20170320:1.1.1.6
	netbsd-7-1:1.1.1.3.2.1.0.6
	netbsd-7-1-RELEASE:1.1.1.3.2.1
	netbsd-7-1-RC2:1.1.1.3.2.1
	clang-294123:1.1.1.6
	netbsd-7-nhusb-base-20170116:1.1.1.3.2.1
	bouyer-socketcan:1.1.1.6.0.2
	bouyer-socketcan-base:1.1.1.6
	clang-291444:1.1.1.6
	pgoyette-localcount-20170107:1.1.1.5
	netbsd-7-1-RC1:1.1.1.3.2.1
	pgoyette-localcount-20161104:1.1.1.5
	netbsd-7-0-2-RELEASE:1.1.1.3.2.1
	localcount-20160914:1.1.1.5
	netbsd-7-nhusb:1.1.1.3.2.1.0.4
	netbsd-7-nhusb-base:1.1.1.3.2.1
	clang-280599:1.1.1.5
	pgoyette-localcount-20160806:1.1.1.5
	pgoyette-localcount-20160726:1.1.1.5
	pgoyette-localcount:1.1.1.5.0.2
	pgoyette-localcount-base:1.1.1.5
	netbsd-7-0-1-RELEASE:1.1.1.3.2.1
	clang-261930:1.1.1.5
	netbsd-7-0:1.1.1.3.2.1.0.2
	netbsd-7-0-RELEASE:1.1.1.3.2.1
	netbsd-7-0-RC3:1.1.1.3.2.1
	netbsd-7-0-RC2:1.1.1.3.2.1
	netbsd-7-0-RC1:1.1.1.3.2.1
	clang-237755:1.1.1.4
	clang-232565:1.1.1.4
	clang-227398:1.1.1.4
	tls-maxphys-base:1.1.1.3
	tls-maxphys:1.1.1.3.0.4
	netbsd-7:1.1.1.3.0.2
	netbsd-7-base:1.1.1.3
	clang-215315:1.1.1.3
	clang-209886:1.1.1.2
	yamt-pagecache:1.1.1.1.0.4
	yamt-pagecache-base9:1.1.1.1
	tls-earlyentropy:1.1.1.1.0.2
	tls-earlyentropy-base:1.1.1.2
	riastradh-xf86-video-intel-2-7-1-pre-2-21-15:1.1.1.1
	riastradh-drm2-base3:1.1.1.1
	clang-202566:1.1.1.1
	LLVM:1.1.1;
locks; strict;
comment	@// @;


1.1
date	2014.03.04.19.53.23;	author joerg;	state Exp;
branches
	1.1.1.1;
next	;
commitid	29z1hJonZISIXprx;

1.1.1.1
date	2014.03.04.19.53.23;	author joerg;	state Exp;
branches
	1.1.1.1.2.1
	1.1.1.1.4.1;
next	1.1.1.2;
commitid	29z1hJonZISIXprx;

1.1.1.2
date	2014.05.30.18.14.50;	author joerg;	state Exp;
branches;
next	1.1.1.3;
commitid	8q0kdlBlCn09GACx;

1.1.1.3
date	2014.08.10.17.08.25;	author joerg;	state Exp;
branches
	1.1.1.3.2.1
	1.1.1.3.4.1;
next	1.1.1.4;
commitid	N85tXAN6Ex9VZPLx;

1.1.1.4
date	2015.01.29.19.57.28;	author joerg;	state Exp;
branches;
next	1.1.1.5;
commitid	mlISSizlPKvepX7y;

1.1.1.5
date	2016.02.27.22.11.46;	author joerg;	state Exp;
branches
	1.1.1.5.2.1;
next	1.1.1.6;
commitid	tIimz3oDlh1NpBWy;

1.1.1.6
date	2017.01.11.10.33.08;	author joerg;	state Exp;
branches;
next	1.1.1.7;
commitid	CNnUNfII1jgNmxBz;

1.1.1.7
date	2017.08.01.19.34.42;	author joerg;	state Exp;
branches
	1.1.1.7.2.1
	1.1.1.7.4.1;
next	1.1.1.8;
commitid	pMuDy65V0VicSx1A;

1.1.1.8
date	2018.07.17.18.32.14;	author joerg;	state Exp;
branches;
next	1.1.1.9;
commitid	wDzL46ALjrCZgwKA;

1.1.1.9
date	2019.11.13.22.23.09;	author joerg;	state dead;
branches;
next	;
commitid	QD8YATxuNG34YJKB;

1.1.1.1.2.1
date	2014.08.10.07.08.25;	author tls;	state Exp;
branches;
next	;
commitid	t01A1TLTYxkpGMLx;

1.1.1.1.4.1
date	2014.03.04.19.53.23;	author yamt;	state dead;
branches;
next	1.1.1.1.4.2;
commitid	WSrDtL5nYAUyiyBx;

1.1.1.1.4.2
date	2014.05.22.16.19.48;	author yamt;	state Exp;
branches;
next	;
commitid	WSrDtL5nYAUyiyBx;

1.1.1.3.2.1
date	2015.06.04.20.04.47;	author snj;	state Exp;
branches;
next	;
commitid	yRnjq9fueSo6n9oy;

1.1.1.3.4.1
date	2014.08.10.17.08.25;	author tls;	state dead;
branches;
next	1.1.1.3.4.2;
commitid	jTnpym9Qu0o4R1Nx;

1.1.1.3.4.2
date	2014.08.19.23.49.28;	author tls;	state Exp;
branches;
next	;
commitid	jTnpym9Qu0o4R1Nx;

1.1.1.5.2.1
date	2017.03.20.06.53.38;	author pgoyette;	state Exp;
branches;
next	;
commitid	jjw7cAwgyKq7RfKz;

1.1.1.7.2.1
date	2018.07.28.04.34.18;	author pgoyette;	state Exp;
branches;
next	;
commitid	1UP1xAIUxv1ZgRLA;

1.1.1.7.4.1
date	2019.06.10.21.46.45;	author christos;	state Exp;
branches;
next	1.1.1.7.4.2;
commitid	jtc8rnCzWiEEHGqB;

1.1.1.7.4.2
date	2020.04.13.07.50.37;	author martin;	state dead;
branches;
next	;
commitid	X01YhRUPVUDaec4C;


desc
@@


1.1
log
@Initial revision
@
text
@//===- unittests/Basic/VirtualFileSystem.cpp ---------------- VFS tests ---===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/Basic/VirtualFileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SourceMgr.h"
#include "gtest/gtest.h"
#include <map>
using namespace clang;
using namespace llvm;
using llvm::sys::fs::UniqueID;

namespace {
class DummyFileSystem : public vfs::FileSystem {
  int FSID;   // used to produce UniqueIDs
  int FileID; // used to produce UniqueIDs
  std::map<std::string, vfs::Status> FilesAndDirs;

  static int getNextFSID() {
    static int Count = 0;
    return Count++;
  }

public:
  DummyFileSystem() : FSID(getNextFSID()), FileID(0) {}

  ErrorOr<vfs::Status> status(const Twine &Path) {
    std::map<std::string, vfs::Status>::iterator I =
        FilesAndDirs.find(Path.str());
    if (I == FilesAndDirs.end())
      return error_code(errc::no_such_file_or_directory, posix_category());
    return I->second;
  }
  error_code openFileForRead(const Twine &Path, OwningPtr<vfs::File> &Result) {
    llvm_unreachable("unimplemented");
  }
  error_code getBufferForFile(const Twine &Name,
                              OwningPtr<MemoryBuffer> &Result,
                              int64_t FileSize = -1,
                              bool RequiresNullTerminator = true) {
    llvm_unreachable("unimplemented");
  }

  void addEntry(StringRef Path, const vfs::Status &Status) {
    FilesAndDirs[Path] = Status;
  }

  void addRegularFile(StringRef Path, sys::fs::perms Perms = sys::fs::all_all) {
    vfs::Status S(Path, Path, UniqueID(FSID, FileID++), sys::TimeValue::now(),
                  0, 0, 1024, sys::fs::file_type::regular_file, Perms);
    addEntry(Path, S);
  }

  void addDirectory(StringRef Path, sys::fs::perms Perms = sys::fs::all_all) {
    vfs::Status S(Path, Path, UniqueID(FSID, FileID++), sys::TimeValue::now(),
                  0, 0, 0, sys::fs::file_type::directory_file, Perms);
    addEntry(Path, S);
  }

  void addSymlink(StringRef Path) {
    vfs::Status S(Path, Path, UniqueID(FSID, FileID++), sys::TimeValue::now(),
                  0, 0, 0, sys::fs::file_type::symlink_file, sys::fs::all_all);
    addEntry(Path, S);
  }
};
} // end anonymous namespace

TEST(VirtualFileSystemTest, StatusQueries) {
  IntrusiveRefCntPtr<DummyFileSystem> D(new DummyFileSystem());
  ErrorOr<vfs::Status> Status((error_code()));

  D->addRegularFile("/foo");
  Status = D->status("/foo");
  ASSERT_EQ(errc::success, Status.getError());
  EXPECT_TRUE(Status->isStatusKnown());
  EXPECT_FALSE(Status->isDirectory());
  EXPECT_TRUE(Status->isRegularFile());
  EXPECT_FALSE(Status->isSymlink());
  EXPECT_FALSE(Status->isOther());
  EXPECT_TRUE(Status->exists());

  D->addDirectory("/bar");
  Status = D->status("/bar");
  ASSERT_EQ(errc::success, Status.getError());
  EXPECT_TRUE(Status->isStatusKnown());
  EXPECT_TRUE(Status->isDirectory());
  EXPECT_FALSE(Status->isRegularFile());
  EXPECT_FALSE(Status->isSymlink());
  EXPECT_FALSE(Status->isOther());
  EXPECT_TRUE(Status->exists());

  D->addSymlink("/baz");
  Status = D->status("/baz");
  ASSERT_EQ(errc::success, Status.getError());
  EXPECT_TRUE(Status->isStatusKnown());
  EXPECT_FALSE(Status->isDirectory());
  EXPECT_FALSE(Status->isRegularFile());
  EXPECT_TRUE(Status->isSymlink());
  EXPECT_FALSE(Status->isOther());
  EXPECT_TRUE(Status->exists());

  EXPECT_TRUE(Status->equivalent(*Status));
  ErrorOr<vfs::Status> Status2 = D->status("/foo");
  ASSERT_EQ(errc::success, Status2.getError());
  EXPECT_FALSE(Status->equivalent(*Status2));
}

TEST(VirtualFileSystemTest, BaseOnlyOverlay) {
  IntrusiveRefCntPtr<DummyFileSystem> D(new DummyFileSystem());
  ErrorOr<vfs::Status> Status((error_code()));
  EXPECT_FALSE(Status = D->status("/foo"));

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(new vfs::OverlayFileSystem(D));
  EXPECT_FALSE(Status = O->status("/foo"));

  D->addRegularFile("/foo");
  Status = D->status("/foo");
  EXPECT_EQ(errc::success, Status.getError());

  ErrorOr<vfs::Status> Status2((error_code()));
  Status2 = O->status("/foo");
  EXPECT_EQ(errc::success, Status2.getError());
  EXPECT_TRUE(Status->equivalent(*Status2));
}

TEST(VirtualFileSystemTest, OverlayFiles) {
  IntrusiveRefCntPtr<DummyFileSystem> Base(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Middle(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Top(new DummyFileSystem());
  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Base));
  O->pushOverlay(Middle);
  O->pushOverlay(Top);

  ErrorOr<vfs::Status> Status1((error_code())), Status2((error_code())),
      Status3((error_code())), StatusB((error_code())), StatusM((error_code())),
      StatusT((error_code()));

  Base->addRegularFile("/foo");
  StatusB = Base->status("/foo");
  ASSERT_EQ(errc::success, StatusB.getError());
  Status1 = O->status("/foo");
  ASSERT_EQ(errc::success, Status1.getError());
  Middle->addRegularFile("/foo");
  StatusM = Middle->status("/foo");
  ASSERT_EQ(errc::success, StatusM.getError());
  Status2 = O->status("/foo");
  ASSERT_EQ(errc::success, Status2.getError());
  Top->addRegularFile("/foo");
  StatusT = Top->status("/foo");
  ASSERT_EQ(errc::success, StatusT.getError());
  Status3 = O->status("/foo");
  ASSERT_EQ(errc::success, Status3.getError());

  EXPECT_TRUE(Status1->equivalent(*StatusB));
  EXPECT_TRUE(Status2->equivalent(*StatusM));
  EXPECT_TRUE(Status3->equivalent(*StatusT));

  EXPECT_FALSE(Status1->equivalent(*Status2));
  EXPECT_FALSE(Status2->equivalent(*Status3));
  EXPECT_FALSE(Status1->equivalent(*Status3));
}

TEST(VirtualFileSystemTest, OverlayDirsNonMerged) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Upper);

  Lower->addDirectory("/lower-only");
  Upper->addDirectory("/upper-only");

  // non-merged paths should be the same
  ErrorOr<vfs::Status> Status1 = Lower->status("/lower-only");
  ASSERT_EQ(errc::success, Status1.getError());
  ErrorOr<vfs::Status> Status2 = O->status("/lower-only");
  ASSERT_EQ(errc::success, Status2.getError());
  EXPECT_TRUE(Status1->equivalent(*Status2));

  Status1 = Upper->status("/upper-only");
  ASSERT_EQ(errc::success, Status1.getError());
  Status2 = O->status("/upper-only");
  ASSERT_EQ(errc::success, Status2.getError());
  EXPECT_TRUE(Status1->equivalent(*Status2));
}

TEST(VirtualFileSystemTest, MergedDirPermissions) {
  // merged directories get the permissions of the upper dir
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Upper);

  ErrorOr<vfs::Status> Status((error_code()));
  Lower->addDirectory("/both", sys::fs::owner_read);
  Upper->addDirectory("/both", sys::fs::owner_all | sys::fs::group_read);
  Status = O->status("/both");
  ASSERT_EQ(errc::success, Status.getError());
  EXPECT_EQ(0740, Status->getPermissions());

  // permissions (as usual) are not recursively applied
  Lower->addRegularFile("/both/foo", sys::fs::owner_read);
  Upper->addRegularFile("/both/bar", sys::fs::owner_write);
  Status = O->status("/both/foo");
  ASSERT_EQ(errc::success, Status.getError());
  EXPECT_EQ(0400, Status->getPermissions());
  Status = O->status("/both/bar");
  ASSERT_EQ(errc::success, Status.getError());
  EXPECT_EQ(0200, Status->getPermissions());
}

class VFSFromYAMLTest : public ::testing::Test {
public:
  int NumDiagnostics;
  void SetUp() {
    NumDiagnostics = 0;
  }

  static void CountingDiagHandler(const SMDiagnostic &, void *Context) {
    VFSFromYAMLTest *Test = static_cast<VFSFromYAMLTest *>(Context);
    ++Test->NumDiagnostics;
  }

  IntrusiveRefCntPtr<vfs::FileSystem>
  getFromYAMLRawString(StringRef Content,
                       IntrusiveRefCntPtr<vfs::FileSystem> ExternalFS) {
    MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(Content);
    return getVFSFromYAML(Buffer, CountingDiagHandler, this, ExternalFS);
  }

  IntrusiveRefCntPtr<vfs::FileSystem> getFromYAMLString(
      StringRef Content,
      IntrusiveRefCntPtr<vfs::FileSystem> ExternalFS = new DummyFileSystem()) {
    std::string VersionPlusContent("{\n  'version':0,\n");
    VersionPlusContent += Content.slice(Content.find('{') + 1, StringRef::npos);
    return getFromYAMLRawString(VersionPlusContent, ExternalFS);
  }

};

TEST_F(VFSFromYAMLTest, BasicVFSFromYAML) {
  IntrusiveRefCntPtr<vfs::FileSystem> FS;
  FS = getFromYAMLString("");
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString("[]");
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString("'string'");
  EXPECT_EQ(NULL, FS.getPtr());
  EXPECT_EQ(3, NumDiagnostics);
}

TEST_F(VFSFromYAMLTest, MappedFiles) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("/foo/bar/a");
  IntrusiveRefCntPtr<vfs::FileSystem> FS =
      getFromYAMLString("{ 'roots': [\n"
                        "{\n"
                        "  'type': 'directory',\n"
                        "  'name': '/',\n"
                        "  'contents': [ {\n"
                        "                  'type': 'file',\n"
                        "                  'name': 'file1',\n"
                        "                  'external-contents': '/foo/bar/a'\n"
                        "                },\n"
                        "                {\n"
                        "                  'type': 'file',\n"
                        "                  'name': 'file2',\n"
                        "                  'external-contents': '/foo/b'\n"
                        "                }\n"
                        "              ]\n"
                        "}\n"
                        "]\n"
                        "}",
                        Lower);
  ASSERT_TRUE(FS.getPtr() != NULL);

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(FS);

  // file
  ErrorOr<vfs::Status> S = O->status("/file1");
  ASSERT_EQ(errc::success, S.getError());
  EXPECT_EQ("/foo/bar/a", S->getName());

  ErrorOr<vfs::Status> SLower = O->status("/foo/bar/a");
  EXPECT_EQ("/foo/bar/a", SLower->getName());
  EXPECT_TRUE(S->equivalent(*SLower));

  // directory
  S = O->status("/");
  ASSERT_EQ(errc::success, S.getError());
  EXPECT_TRUE(S->isDirectory());
  EXPECT_TRUE(S->equivalent(*O->status("/"))); // non-volatile UniqueID

  // broken mapping
  EXPECT_EQ(errc::no_such_file_or_directory, O->status("/file2").getError());
  EXPECT_EQ(0, NumDiagnostics);
}

TEST_F(VFSFromYAMLTest, CaseInsensitive) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("/foo/bar/a");
  IntrusiveRefCntPtr<vfs::FileSystem> FS =
      getFromYAMLString("{ 'case-sensitive': 'false',\n"
                        "  'roots': [\n"
                        "{\n"
                        "  'type': 'directory',\n"
                        "  'name': '/',\n"
                        "  'contents': [ {\n"
                        "                  'type': 'file',\n"
                        "                  'name': 'XX',\n"
                        "                  'external-contents': '/foo/bar/a'\n"
                        "                }\n"
                        "              ]\n"
                        "}]}",
                        Lower);
  ASSERT_TRUE(FS.getPtr() != NULL);

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(FS);

  ErrorOr<vfs::Status> S = O->status("/XX");
  ASSERT_EQ(errc::success, S.getError());

  ErrorOr<vfs::Status> SS = O->status("/xx");
  ASSERT_EQ(errc::success, SS.getError());
  EXPECT_TRUE(S->equivalent(*SS));
  SS = O->status("/xX");
  EXPECT_TRUE(S->equivalent(*SS));
  SS = O->status("/Xx");
  EXPECT_TRUE(S->equivalent(*SS));
  EXPECT_EQ(0, NumDiagnostics);
}

TEST_F(VFSFromYAMLTest, CaseSensitive) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("/foo/bar/a");
  IntrusiveRefCntPtr<vfs::FileSystem> FS =
      getFromYAMLString("{ 'case-sensitive': 'true',\n"
                        "  'roots': [\n"
                        "{\n"
                        "  'type': 'directory',\n"
                        "  'name': '/',\n"
                        "  'contents': [ {\n"
                        "                  'type': 'file',\n"
                        "                  'name': 'XX',\n"
                        "                  'external-contents': '/foo/bar/a'\n"
                        "                }\n"
                        "              ]\n"
                        "}]}",
                        Lower);
  ASSERT_TRUE(FS.getPtr() != NULL);

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(FS);

  ErrorOr<vfs::Status> SS = O->status("/xx");
  EXPECT_EQ(errc::no_such_file_or_directory, SS.getError());
  SS = O->status("/xX");
  EXPECT_EQ(errc::no_such_file_or_directory, SS.getError());
  SS = O->status("/Xx");
  EXPECT_EQ(errc::no_such_file_or_directory, SS.getError());
  EXPECT_EQ(0, NumDiagnostics);
}

TEST_F(VFSFromYAMLTest, IllegalVFSFile) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());

  // invalid YAML at top-level
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString("{]", Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  // invalid YAML in roots
  FS = getFromYAMLString("{ 'roots':[}", Lower);
  // invalid YAML in directory
  FS = getFromYAMLString(
      "{ 'roots':[ { 'name': 'foo', 'type': 'directory', 'contents': [}",
      Lower);
  EXPECT_EQ(NULL, FS.getPtr());

  // invalid configuration
  FS = getFromYAMLString("{ 'knobular': 'true', 'roots':[] }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString("{ 'case-sensitive': 'maybe', 'roots':[] }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());

  // invalid roots
  FS = getFromYAMLString("{ 'roots':'' }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString("{ 'roots':{} }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());

  // invalid entries
  FS = getFromYAMLString(
      "{ 'roots':[ { 'type': 'other', 'name': 'me', 'contents': '' }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString("{ 'roots':[ { 'type': 'file', 'name': [], "
                         "'external-contents': 'other' }",
                         Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString(
      "{ 'roots':[ { 'type': 'file', 'name': 'me', 'external-contents': [] }",
      Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString(
      "{ 'roots':[ { 'type': 'file', 'name': 'me', 'external-contents': {} }",
      Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString(
      "{ 'roots':[ { 'type': 'directory', 'name': 'me', 'contents': {} }",
      Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString(
      "{ 'roots':[ { 'type': 'directory', 'name': 'me', 'contents': '' }",
      Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString(
      "{ 'roots':[ { 'thingy': 'directory', 'name': 'me', 'contents': [] }",
      Lower);
  EXPECT_EQ(NULL, FS.getPtr());

  // missing mandatory fields
  FS = getFromYAMLString("{ 'roots':[ { 'type': 'file', 'name': 'me' }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString(
      "{ 'roots':[ { 'type': 'file', 'external-contents': 'other' }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString("{ 'roots':[ { 'name': 'me', 'contents': [] }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());

  // duplicate keys
  FS = getFromYAMLString("{ 'roots':[], 'roots':[] }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString(
      "{ 'case-sensitive':'true', 'case-sensitive':'true', 'roots':[] }",
      Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS =
      getFromYAMLString("{ 'roots':[{'name':'me', 'name':'you', 'type':'file', "
                        "'external-contents':'blah' } ] }",
                        Lower);
  EXPECT_EQ(NULL, FS.getPtr());

  // missing version
  FS = getFromYAMLRawString("{ 'roots':[] }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());

  // bad version number
  FS = getFromYAMLRawString("{ 'version':'foo', 'roots':[] }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLRawString("{ 'version':-1, 'roots':[] }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLRawString("{ 'version':100000, 'roots':[] }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  EXPECT_EQ(24, NumDiagnostics);
}

TEST_F(VFSFromYAMLTest, UseExternalName) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("/external/file");

  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'roots': [\n"
      "  { 'type': 'file', 'name': '/A',\n"
      "    'external-contents': '/external/file'\n"
      "  },\n"
      "  { 'type': 'file', 'name': '/B',\n"
      "    'use-external-name': true,\n"
      "    'external-contents': '/external/file'\n"
      "  },\n"
      "  { 'type': 'file', 'name': '/C',\n"
      "    'use-external-name': false,\n"
      "    'external-contents': '/external/file'\n"
      "  }\n"
      "] }", Lower);
  ASSERT_TRUE(NULL != FS.getPtr());

  // default true
  EXPECT_EQ("/external/file", FS->status("/A")->getName());
  // explicit
  EXPECT_EQ("/external/file", FS->status("/B")->getName());
  EXPECT_EQ("/C", FS->status("/C")->getName());

  // global configuration
  FS = getFromYAMLString(
      "{ 'use-external-names': false,\n"
      "  'roots': [\n"
      "  { 'type': 'file', 'name': '/A',\n"
      "    'external-contents': '/external/file'\n"
      "  },\n"
      "  { 'type': 'file', 'name': '/B',\n"
      "    'use-external-name': true,\n"
      "    'external-contents': '/external/file'\n"
      "  },\n"
      "  { 'type': 'file', 'name': '/C',\n"
      "    'use-external-name': false,\n"
      "    'external-contents': '/external/file'\n"
      "  }\n"
      "] }", Lower);
  ASSERT_TRUE(NULL != FS.getPtr());

  // default
  EXPECT_EQ("/A", FS->status("/A")->getName());
  // explicit
  EXPECT_EQ("/external/file", FS->status("/B")->getName());
  EXPECT_EQ("/C", FS->status("/C")->getName());
}

TEST_F(VFSFromYAMLTest, MultiComponentPath) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("/other");

  // file in roots
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'roots': [\n"
      "  { 'type': 'file', 'name': '/path/to/file',\n"
      "    'external-contents': '/other' }]\n"
      "}", Lower);
  ASSERT_TRUE(NULL != FS.getPtr());
  EXPECT_EQ(errc::success, FS->status("/path/to/file").getError());
  EXPECT_EQ(errc::success, FS->status("/path/to").getError());
  EXPECT_EQ(errc::success, FS->status("/path").getError());
  EXPECT_EQ(errc::success, FS->status("/").getError());

  // at the start
  FS = getFromYAMLString(
      "{ 'roots': [\n"
      "  { 'type': 'directory', 'name': '/path/to',\n"
      "    'contents': [ { 'type': 'file', 'name': 'file',\n"
      "                    'external-contents': '/other' }]}]\n"
      "}", Lower);
  ASSERT_TRUE(NULL != FS.getPtr());
  EXPECT_EQ(errc::success, FS->status("/path/to/file").getError());
  EXPECT_EQ(errc::success, FS->status("/path/to").getError());
  EXPECT_EQ(errc::success, FS->status("/path").getError());
  EXPECT_EQ(errc::success, FS->status("/").getError());

  // at the end
  FS = getFromYAMLString(
      "{ 'roots': [\n"
      "  { 'type': 'directory', 'name': '/',\n"
      "    'contents': [ { 'type': 'file', 'name': 'path/to/file',\n"
      "                    'external-contents': '/other' }]}]\n"
      "}", Lower);
  ASSERT_TRUE(NULL != FS.getPtr());
  EXPECT_EQ(errc::success, FS->status("/path/to/file").getError());
  EXPECT_EQ(errc::success, FS->status("/path/to").getError());
  EXPECT_EQ(errc::success, FS->status("/path").getError());
  EXPECT_EQ(errc::success, FS->status("/").getError());
}

TEST_F(VFSFromYAMLTest, TrailingSlashes) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("/other");

  // file in roots
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'roots': [\n"
      "  { 'type': 'directory', 'name': '/path/to////',\n"
      "    'contents': [ { 'type': 'file', 'name': 'file',\n"
      "                    'external-contents': '/other' }]}]\n"
      "}", Lower);
  ASSERT_TRUE(NULL != FS.getPtr());
  EXPECT_EQ(errc::success, FS->status("/path/to/file").getError());
  EXPECT_EQ(errc::success, FS->status("/path/to").getError());
  EXPECT_EQ(errc::success, FS->status("/path").getError());
  EXPECT_EQ(errc::success, FS->status("/").getError());
}
@


1.1.1.1
log
@Import Clang 3.5svn r202566.
@
text
@@


1.1.1.1.2.1
log
@Rebase.
@
text
@d41 1
a41 2
  error_code openFileForRead(const Twine &Path,
                             std::unique_ptr<vfs::File> &Result) {
d45 1
a45 1
                              std::unique_ptr<MemoryBuffer> &Result,
a220 2
// NOTE: in the tests below, we use '//root/' as our root directory, since it is
// a legal *absolute* path on Windows as well as *nix.
a223 1

d247 1
d263 1
a263 1
  Lower->addRegularFile("//root/foo/bar/a");
d268 1
a268 1
                        "  'name': '//root/',\n"
d272 1
a272 1
                        "                  'external-contents': '//root/foo/bar/a'\n"
d277 1
a277 1
                        "                  'external-contents': '//root/foo/b'\n"
d291 1
a291 1
  ErrorOr<vfs::Status> S = O->status("//root/file1");
d293 1
a293 1
  EXPECT_EQ("//root/foo/bar/a", S->getName());
d295 2
a296 2
  ErrorOr<vfs::Status> SLower = O->status("//root/foo/bar/a");
  EXPECT_EQ("//root/foo/bar/a", SLower->getName());
d300 1
a300 1
  S = O->status("//root/");
d303 1
a303 1
  EXPECT_TRUE(S->equivalent(*O->status("//root/"))); // non-volatile UniqueID
d306 1
a306 1
  EXPECT_EQ(errc::no_such_file_or_directory, O->status("//root/file2").getError());
d312 1
a312 1
  Lower->addRegularFile("//root/foo/bar/a");
d318 1
a318 1
                        "  'name': '//root/',\n"
d322 1
a322 1
                        "                  'external-contents': '//root/foo/bar/a'\n"
d333 1
a333 1
  ErrorOr<vfs::Status> S = O->status("//root/XX");
d336 1
a336 1
  ErrorOr<vfs::Status> SS = O->status("//root/xx");
d339 1
a339 1
  SS = O->status("//root/xX");
d341 1
a341 1
  SS = O->status("//root/Xx");
d348 1
a348 1
  Lower->addRegularFile("//root/foo/bar/a");
d354 1
a354 1
                        "  'name': '//root/',\n"
d358 1
a358 1
                        "                  'external-contents': '//root/foo/bar/a'\n"
d369 1
a369 1
  ErrorOr<vfs::Status> SS = O->status("//root/xx");
d371 1
a371 1
  SS = O->status("//root/xX");
d373 1
a373 1
  SS = O->status("//root/Xx");
d471 1
a471 1
  Lower->addRegularFile("//root/external/file");
d475 2
a476 2
      "  { 'type': 'file', 'name': '//root/A',\n"
      "    'external-contents': '//root/external/file'\n"
d478 1
a478 1
      "  { 'type': 'file', 'name': '//root/B',\n"
d480 1
a480 1
      "    'external-contents': '//root/external/file'\n"
d482 1
a482 1
      "  { 'type': 'file', 'name': '//root/C',\n"
d484 1
a484 1
      "    'external-contents': '//root/external/file'\n"
d490 1
a490 1
  EXPECT_EQ("//root/external/file", FS->status("//root/A")->getName());
d492 2
a493 2
  EXPECT_EQ("//root/external/file", FS->status("//root/B")->getName());
  EXPECT_EQ("//root/C", FS->status("//root/C")->getName());
d499 2
a500 2
      "  { 'type': 'file', 'name': '//root/A',\n"
      "    'external-contents': '//root/external/file'\n"
d502 1
a502 1
      "  { 'type': 'file', 'name': '//root/B',\n"
d504 1
a504 1
      "    'external-contents': '//root/external/file'\n"
d506 1
a506 1
      "  { 'type': 'file', 'name': '//root/C',\n"
d508 1
a508 1
      "    'external-contents': '//root/external/file'\n"
d514 1
a514 1
  EXPECT_EQ("//root/A", FS->status("//root/A")->getName());
d516 2
a517 2
  EXPECT_EQ("//root/external/file", FS->status("//root/B")->getName());
  EXPECT_EQ("//root/C", FS->status("//root/C")->getName());
d522 1
a522 1
  Lower->addRegularFile("//root/other");
d527 2
a528 2
      "  { 'type': 'file', 'name': '//root/path/to/file',\n"
      "    'external-contents': '//root/other' }]\n"
d531 4
a534 4
  EXPECT_EQ(errc::success, FS->status("//root/path/to/file").getError());
  EXPECT_EQ(errc::success, FS->status("//root/path/to").getError());
  EXPECT_EQ(errc::success, FS->status("//root/path").getError());
  EXPECT_EQ(errc::success, FS->status("//root/").getError());
d539 1
a539 1
      "  { 'type': 'directory', 'name': '//root/path/to',\n"
d541 1
a541 1
      "                    'external-contents': '//root/other' }]}]\n"
d544 4
a547 4
  EXPECT_EQ(errc::success, FS->status("//root/path/to/file").getError());
  EXPECT_EQ(errc::success, FS->status("//root/path/to").getError());
  EXPECT_EQ(errc::success, FS->status("//root/path").getError());
  EXPECT_EQ(errc::success, FS->status("//root/").getError());
d552 1
a552 1
      "  { 'type': 'directory', 'name': '//root/',\n"
d554 1
a554 1
      "                    'external-contents': '//root/other' }]}]\n"
d557 4
a560 4
  EXPECT_EQ(errc::success, FS->status("//root/path/to/file").getError());
  EXPECT_EQ(errc::success, FS->status("//root/path/to").getError());
  EXPECT_EQ(errc::success, FS->status("//root/path").getError());
  EXPECT_EQ(errc::success, FS->status("//root/").getError());
d565 1
a565 1
  Lower->addRegularFile("//root/other");
d570 1
a570 1
      "  { 'type': 'directory', 'name': '//root/path/to////',\n"
d572 1
a572 1
      "                    'external-contents': '//root/other' }]}]\n"
d575 4
a578 4
  EXPECT_EQ(errc::success, FS->status("//root/path/to/file").getError());
  EXPECT_EQ(errc::success, FS->status("//root/path/to").getError());
  EXPECT_EQ(errc::success, FS->status("//root/path").getError());
  EXPECT_EQ(errc::success, FS->status("//root/").getError());
@


1.1.1.2
log
@Import Clang 3.5svn r209886.
@
text
@d41 1
a41 2
  error_code openFileForRead(const Twine &Path,
                             std::unique_ptr<vfs::File> &Result) {
d45 1
a45 1
                              std::unique_ptr<MemoryBuffer> &Result,
a220 2
// NOTE: in the tests below, we use '//root/' as our root directory, since it is
// a legal *absolute* path on Windows as well as *nix.
a223 1

d247 1
d263 1
a263 1
  Lower->addRegularFile("//root/foo/bar/a");
d268 1
a268 1
                        "  'name': '//root/',\n"
d272 1
a272 1
                        "                  'external-contents': '//root/foo/bar/a'\n"
d277 1
a277 1
                        "                  'external-contents': '//root/foo/b'\n"
d291 1
a291 1
  ErrorOr<vfs::Status> S = O->status("//root/file1");
d293 1
a293 1
  EXPECT_EQ("//root/foo/bar/a", S->getName());
d295 2
a296 2
  ErrorOr<vfs::Status> SLower = O->status("//root/foo/bar/a");
  EXPECT_EQ("//root/foo/bar/a", SLower->getName());
d300 1
a300 1
  S = O->status("//root/");
d303 1
a303 1
  EXPECT_TRUE(S->equivalent(*O->status("//root/"))); // non-volatile UniqueID
d306 1
a306 1
  EXPECT_EQ(errc::no_such_file_or_directory, O->status("//root/file2").getError());
d312 1
a312 1
  Lower->addRegularFile("//root/foo/bar/a");
d318 1
a318 1
                        "  'name': '//root/',\n"
d322 1
a322 1
                        "                  'external-contents': '//root/foo/bar/a'\n"
d333 1
a333 1
  ErrorOr<vfs::Status> S = O->status("//root/XX");
d336 1
a336 1
  ErrorOr<vfs::Status> SS = O->status("//root/xx");
d339 1
a339 1
  SS = O->status("//root/xX");
d341 1
a341 1
  SS = O->status("//root/Xx");
d348 1
a348 1
  Lower->addRegularFile("//root/foo/bar/a");
d354 1
a354 1
                        "  'name': '//root/',\n"
d358 1
a358 1
                        "                  'external-contents': '//root/foo/bar/a'\n"
d369 1
a369 1
  ErrorOr<vfs::Status> SS = O->status("//root/xx");
d371 1
a371 1
  SS = O->status("//root/xX");
d373 1
a373 1
  SS = O->status("//root/Xx");
d471 1
a471 1
  Lower->addRegularFile("//root/external/file");
d475 2
a476 2
      "  { 'type': 'file', 'name': '//root/A',\n"
      "    'external-contents': '//root/external/file'\n"
d478 1
a478 1
      "  { 'type': 'file', 'name': '//root/B',\n"
d480 1
a480 1
      "    'external-contents': '//root/external/file'\n"
d482 1
a482 1
      "  { 'type': 'file', 'name': '//root/C',\n"
d484 1
a484 1
      "    'external-contents': '//root/external/file'\n"
d490 1
a490 1
  EXPECT_EQ("//root/external/file", FS->status("//root/A")->getName());
d492 2
a493 2
  EXPECT_EQ("//root/external/file", FS->status("//root/B")->getName());
  EXPECT_EQ("//root/C", FS->status("//root/C")->getName());
d499 2
a500 2
      "  { 'type': 'file', 'name': '//root/A',\n"
      "    'external-contents': '//root/external/file'\n"
d502 1
a502 1
      "  { 'type': 'file', 'name': '//root/B',\n"
d504 1
a504 1
      "    'external-contents': '//root/external/file'\n"
d506 1
a506 1
      "  { 'type': 'file', 'name': '//root/C',\n"
d508 1
a508 1
      "    'external-contents': '//root/external/file'\n"
d514 1
a514 1
  EXPECT_EQ("//root/A", FS->status("//root/A")->getName());
d516 2
a517 2
  EXPECT_EQ("//root/external/file", FS->status("//root/B")->getName());
  EXPECT_EQ("//root/C", FS->status("//root/C")->getName());
d522 1
a522 1
  Lower->addRegularFile("//root/other");
d527 2
a528 2
      "  { 'type': 'file', 'name': '//root/path/to/file',\n"
      "    'external-contents': '//root/other' }]\n"
d531 4
a534 4
  EXPECT_EQ(errc::success, FS->status("//root/path/to/file").getError());
  EXPECT_EQ(errc::success, FS->status("//root/path/to").getError());
  EXPECT_EQ(errc::success, FS->status("//root/path").getError());
  EXPECT_EQ(errc::success, FS->status("//root/").getError());
d539 1
a539 1
      "  { 'type': 'directory', 'name': '//root/path/to',\n"
d541 1
a541 1
      "                    'external-contents': '//root/other' }]}]\n"
d544 4
a547 4
  EXPECT_EQ(errc::success, FS->status("//root/path/to/file").getError());
  EXPECT_EQ(errc::success, FS->status("//root/path/to").getError());
  EXPECT_EQ(errc::success, FS->status("//root/path").getError());
  EXPECT_EQ(errc::success, FS->status("//root/").getError());
d552 1
a552 1
      "  { 'type': 'directory', 'name': '//root/',\n"
d554 1
a554 1
      "                    'external-contents': '//root/other' }]}]\n"
d557 4
a560 4
  EXPECT_EQ(errc::success, FS->status("//root/path/to/file").getError());
  EXPECT_EQ(errc::success, FS->status("//root/path/to").getError());
  EXPECT_EQ(errc::success, FS->status("//root/path").getError());
  EXPECT_EQ(errc::success, FS->status("//root/").getError());
d565 1
a565 1
  Lower->addRegularFile("//root/other");
d570 1
a570 1
      "  { 'type': 'directory', 'name': '//root/path/to////',\n"
d572 1
a572 1
      "                    'external-contents': '//root/other' }]}]\n"
d575 4
a578 4
  EXPECT_EQ(errc::success, FS->status("//root/path/to/file").getError());
  EXPECT_EQ(errc::success, FS->status("//root/path/to").getError());
  EXPECT_EQ(errc::success, FS->status("//root/path").getError());
  EXPECT_EQ(errc::success, FS->status("//root/").getError());
@


1.1.1.3
log
@Import clang 3.6svn r215315.
@
text
@a10 1
#include "llvm/Support/Errc.h"
d38 1
a38 1
      return make_error_code(llvm::errc::no_such_file_or_directory);
d41 2
a42 2
  std::error_code openFileForRead(const Twine &Path,
                                  std::unique_ptr<vfs::File> &Result) {
d45 4
a48 4
  std::error_code getBufferForFile(const Twine &Name,
                                   std::unique_ptr<MemoryBuffer> &Result,
                                   int64_t FileSize = -1,
                                   bool RequiresNullTerminator = true) {
a51 43
  struct DirIterImpl : public clang::vfs::detail::DirIterImpl {
    std::map<std::string, vfs::Status> &FilesAndDirs;
    std::map<std::string, vfs::Status>::iterator I;
    std::string Path;
    bool isInPath(StringRef S) {
      if (Path.size() < S.size() && S.find(Path) == 0) {
        auto LastSep = S.find_last_of('/');
        if (LastSep == Path.size() || LastSep == Path.size()-1)
          return true;
      }
      return false;
    }
    DirIterImpl(std::map<std::string, vfs::Status> &FilesAndDirs,
                const Twine &_Path)
        : FilesAndDirs(FilesAndDirs), I(FilesAndDirs.begin()),
          Path(_Path.str()) {
      for ( ; I != FilesAndDirs.end(); ++I) {
        if (isInPath(I->first)) {
          CurrentEntry = I->second;
          break;
        }
      }
    }
    std::error_code increment() override {
      ++I;
      for ( ; I != FilesAndDirs.end(); ++I) {
        if (isInPath(I->first)) {
          CurrentEntry = I->second;
          break;
        }
      }
      if (I == FilesAndDirs.end())
        CurrentEntry = vfs::Status();
      return std::error_code();
    }
  };

  vfs::directory_iterator dir_begin(const Twine &Dir,
                                    std::error_code &EC) override {
    return vfs::directory_iterator(
        std::make_shared<DirIterImpl>(FilesAndDirs, Dir));
  }

d78 1
a78 1
  ErrorOr<vfs::Status> Status((std::error_code()));
d82 1
a82 1
  ASSERT_FALSE(Status.getError());
d92 1
a92 1
  ASSERT_FALSE(Status.getError());
d102 1
a102 1
  ASSERT_FALSE(Status.getError());
d112 1
a112 1
  ASSERT_FALSE(Status2.getError());
d118 1
a118 1
  ErrorOr<vfs::Status> Status((std::error_code()));
d126 1
a126 1
  EXPECT_FALSE(Status.getError());
d128 1
a128 1
  ErrorOr<vfs::Status> Status2((std::error_code()));
d130 1
a130 1
  EXPECT_FALSE(Status2.getError());
d143 3
a145 4
  ErrorOr<vfs::Status> Status1((std::error_code())),
      Status2((std::error_code())), Status3((std::error_code())),
      StatusB((std::error_code())), StatusM((std::error_code())),
      StatusT((std::error_code()));
d149 1
a149 1
  ASSERT_FALSE(StatusB.getError());
d151 1
a151 1
  ASSERT_FALSE(Status1.getError());
d154 1
a154 1
  ASSERT_FALSE(StatusM.getError());
d156 1
a156 1
  ASSERT_FALSE(Status2.getError());
d159 1
a159 1
  ASSERT_FALSE(StatusT.getError());
d161 1
a161 1
  ASSERT_FALSE(Status3.getError());
d184 1
a184 1
  ASSERT_FALSE(Status1.getError());
d186 1
a186 1
  ASSERT_FALSE(Status2.getError());
d190 1
a190 1
  ASSERT_FALSE(Status1.getError());
d192 1
a192 1
  ASSERT_FALSE(Status2.getError());
d204 1
a204 1
  ErrorOr<vfs::Status> Status((std::error_code()));
d208 1
a208 1
  ASSERT_FALSE(Status.getError());
d215 1
a215 1
  ASSERT_FALSE( Status.getError());
d218 1
a218 1
  ASSERT_FALSE(Status.getError());
a221 257
namespace {
struct ScopedDir {
  SmallString<128> Path;
  ScopedDir(const Twine &Name, bool Unique=false) {
    std::error_code EC;
    if (Unique) {
      EC =  llvm::sys::fs::createUniqueDirectory(Name, Path);
    } else {
      Path = Name.str();
      EC = llvm::sys::fs::create_directory(Twine(Path));
    }
    if (EC)
      Path = "";
    EXPECT_FALSE(EC);
  }
  ~ScopedDir() {
    if (Path != "")
      EXPECT_FALSE(llvm::sys::fs::remove(Path.str()));
  }
  operator StringRef() { return Path.str(); }
};
}

TEST(VirtualFileSystemTest, BasicRealFSIteration) {
  ScopedDir TestDirectory("virtual-file-system-test", /*Unique*/true);
  IntrusiveRefCntPtr<vfs::FileSystem> FS = vfs::getRealFileSystem();

  std::error_code EC;
  vfs::directory_iterator I = FS->dir_begin(Twine(TestDirectory), EC);
  ASSERT_FALSE(EC);
  EXPECT_EQ(vfs::directory_iterator(), I); // empty directory is empty

  ScopedDir _a(TestDirectory+"/a");
  ScopedDir _ab(TestDirectory+"/a/b");
  ScopedDir _c(TestDirectory+"/c");
  ScopedDir _cd(TestDirectory+"/c/d");

  I = FS->dir_begin(Twine(TestDirectory), EC);
  ASSERT_FALSE(EC);
  ASSERT_NE(vfs::directory_iterator(), I);
  // Check either a or c, since we can't rely on the iteration order.
  EXPECT_TRUE(I->getName().endswith("a") || I->getName().endswith("c"));
  I.increment(EC);
  ASSERT_FALSE(EC);
  ASSERT_NE(vfs::directory_iterator(), I);
  EXPECT_TRUE(I->getName().endswith("a") || I->getName().endswith("c"));
  I.increment(EC);
  EXPECT_EQ(vfs::directory_iterator(), I);
}

TEST(VirtualFileSystemTest, BasicRealFSRecursiveIteration) {
  ScopedDir TestDirectory("virtual-file-system-test", /*Unique*/true);
  IntrusiveRefCntPtr<vfs::FileSystem> FS = vfs::getRealFileSystem();

  std::error_code EC;
  auto I = vfs::recursive_directory_iterator(*FS, Twine(TestDirectory), EC);
  ASSERT_FALSE(EC);
  EXPECT_EQ(vfs::recursive_directory_iterator(), I); // empty directory is empty

  ScopedDir _a(TestDirectory+"/a");
  ScopedDir _ab(TestDirectory+"/a/b");
  ScopedDir _c(TestDirectory+"/c");
  ScopedDir _cd(TestDirectory+"/c/d");

  I = vfs::recursive_directory_iterator(*FS, Twine(TestDirectory), EC);
  ASSERT_FALSE(EC);
  ASSERT_NE(vfs::recursive_directory_iterator(), I);


  std::vector<std::string> Contents;
  for (auto E = vfs::recursive_directory_iterator(); !EC && I != E;
       I.increment(EC)) {
    Contents.push_back(I->getName());
  }

  // Check contents, which may be in any order
  EXPECT_EQ(4U, Contents.size());
  int Counts[4] = { 0, 0, 0, 0 };
  for (const std::string &Name : Contents) {
    ASSERT_FALSE(Name.empty());
    int Index = Name[Name.size()-1] - 'a';
    ASSERT_TRUE(Index >= 0 && Index < 4);
    Counts[Index]++;
  }
  EXPECT_EQ(1, Counts[0]); // a
  EXPECT_EQ(1, Counts[1]); // b
  EXPECT_EQ(1, Counts[2]); // c
  EXPECT_EQ(1, Counts[3]); // d
}

template <typename T, size_t N>
std::vector<StringRef> makeStringRefVector(const T (&Arr)[N]) {
  std::vector<StringRef> Vec;
  for (size_t i = 0; i != N; ++i)
    Vec.push_back(Arr[i]);
  return Vec;
}

template <typename DirIter>
static void checkContents(DirIter I, ArrayRef<StringRef> Expected) {
  std::error_code EC;
  auto ExpectedIter = Expected.begin(), ExpectedEnd = Expected.end();
  for (DirIter E;
       !EC && I != E && ExpectedIter != ExpectedEnd;
       I.increment(EC), ++ExpectedIter)
    EXPECT_EQ(*ExpectedIter, I->getName());

  EXPECT_EQ(ExpectedEnd, ExpectedIter);
  EXPECT_EQ(DirIter(), I);
}

TEST(VirtualFileSystemTest, OverlayIteration) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Upper);

  std::error_code EC;
  checkContents(O->dir_begin("/", EC), ArrayRef<StringRef>());

  Lower->addRegularFile("/file1");
  checkContents(O->dir_begin("/", EC), ArrayRef<StringRef>("/file1"));

  Upper->addRegularFile("/file2");
  {
    const char *Contents[] = {"/file2", "/file1"};
    checkContents(O->dir_begin("/", EC), makeStringRefVector(Contents));
  }

  Lower->addDirectory("/dir1");
  Lower->addRegularFile("/dir1/foo");
  Upper->addDirectory("/dir2");
  Upper->addRegularFile("/dir2/foo");
  checkContents(O->dir_begin("/dir2", EC), ArrayRef<StringRef>("/dir2/foo"));
  {
    const char *Contents[] = {"/dir2", "/file2", "/dir1", "/file1"};
    checkContents(O->dir_begin("/", EC), makeStringRefVector(Contents));
  }
}

TEST(VirtualFileSystemTest, OverlayRecursiveIteration) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Middle(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Middle);
  O->pushOverlay(Upper);

  std::error_code EC;
  checkContents(vfs::recursive_directory_iterator(*O, "/", EC),
                ArrayRef<StringRef>());

  Lower->addRegularFile("/file1");
  checkContents(vfs::recursive_directory_iterator(*O, "/", EC),
                ArrayRef<StringRef>("/file1"));

  Upper->addDirectory("/dir");
  Upper->addRegularFile("/dir/file2");
  {
    const char *Contents[] = {"/dir", "/dir/file2", "/file1"};
    checkContents(vfs::recursive_directory_iterator(*O, "/", EC),
                  makeStringRefVector(Contents));
  }

  Lower->addDirectory("/dir1");
  Lower->addRegularFile("/dir1/foo");
  Lower->addDirectory("/dir1/a");
  Lower->addRegularFile("/dir1/a/b");
  Middle->addDirectory("/a");
  Middle->addDirectory("/a/b");
  Middle->addDirectory("/a/b/c");
  Middle->addRegularFile("/a/b/c/d");
  Middle->addRegularFile("/hiddenByUp");
  Upper->addDirectory("/dir2");
  Upper->addRegularFile("/dir2/foo");
  Upper->addRegularFile("/hiddenByUp");
  checkContents(vfs::recursive_directory_iterator(*O, "/dir2", EC),
                ArrayRef<StringRef>("/dir2/foo"));
  {
    const char *Contents[] = { "/dir", "/dir/file2", "/dir2", "/dir2/foo",
        "/hiddenByUp", "/a", "/a/b", "/a/b/c", "/a/b/c/d", "/dir1", "/dir1/a",
        "/dir1/a/b", "/dir1/foo", "/file1" };
    checkContents(vfs::recursive_directory_iterator(*O, "/", EC),
                  makeStringRefVector(Contents));
  }
}

TEST(VirtualFileSystemTest, ThreeLevelIteration) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Middle(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Middle);
  O->pushOverlay(Upper);

  std::error_code EC;
  checkContents(O->dir_begin("/", EC), ArrayRef<StringRef>());

  Middle->addRegularFile("/file2");
  checkContents(O->dir_begin("/", EC), ArrayRef<StringRef>("/file2"));

  Lower->addRegularFile("/file1");
  Upper->addRegularFile("/file3");
  {
    const char *Contents[] = {"/file3", "/file2", "/file1"};
    checkContents(O->dir_begin("/", EC), makeStringRefVector(Contents));
  }
}

TEST(VirtualFileSystemTest, HiddenInIteration) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Middle(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Middle);
  O->pushOverlay(Upper);

  std::error_code EC;
  Lower->addRegularFile("/onlyInLow", sys::fs::owner_read);
  Lower->addRegularFile("/hiddenByMid", sys::fs::owner_read);
  Lower->addRegularFile("/hiddenByUp", sys::fs::owner_read);
  Middle->addRegularFile("/onlyInMid", sys::fs::owner_write);
  Middle->addRegularFile("/hiddenByMid", sys::fs::owner_write);
  Middle->addRegularFile("/hiddenByUp", sys::fs::owner_write);
  Upper->addRegularFile("/onlyInUp", sys::fs::owner_all);
  Upper->addRegularFile("/hiddenByUp", sys::fs::owner_all);
  {
    const char *Contents[] = {"/hiddenByUp", "/onlyInUp", "/hiddenByMid",
                              "/onlyInMid", "/onlyInLow"};
    checkContents(O->dir_begin("/", EC), makeStringRefVector(Contents));
  }

  // Make sure we get the top-most entry
  {
    std::error_code EC;
    vfs::directory_iterator I = O->dir_begin("/", EC), E;
    for ( ; !EC && I != E; I.increment(EC))
      if (I->getName() == "/hiddenByUp")
        break;
    ASSERT_NE(E, I);
    EXPECT_EQ(sys::fs::owner_all, I->getPermissions());
  }
  {
    std::error_code EC;
    vfs::directory_iterator I = O->dir_begin("/", EC), E;
    for ( ; !EC && I != E; I.increment(EC))
      if (I->getName() == "/hiddenByMid")
        break;
    ASSERT_NE(E, I);
    EXPECT_EQ(sys::fs::owner_write, I->getPermissions());
  }
}

d256 1
a256 1
  EXPECT_EQ(nullptr, FS.get());
d258 1
a258 1
  EXPECT_EQ(nullptr, FS.get());
d260 1
a260 1
  EXPECT_EQ(nullptr, FS.get());
d287 1
a287 1
  ASSERT_TRUE(FS.get() != nullptr);
d295 1
a295 1
  ASSERT_FALSE(S.getError());
d304 1
a304 1
  ASSERT_FALSE(S.getError());
d309 1
a309 2
  EXPECT_EQ(O->status("//root/file2").getError(),
            llvm::errc::no_such_file_or_directory);
d330 1
a330 1
  ASSERT_TRUE(FS.get() != nullptr);
d337 1
a337 1
  ASSERT_FALSE(S.getError());
d340 1
a340 1
  ASSERT_FALSE(SS.getError());
d366 1
a366 1
  ASSERT_TRUE(FS.get() != nullptr);
d373 1
a373 1
  EXPECT_EQ(SS.getError(), llvm::errc::no_such_file_or_directory);
d375 1
a375 1
  EXPECT_EQ(SS.getError(), llvm::errc::no_such_file_or_directory);
d377 1
a377 1
  EXPECT_EQ(SS.getError(), llvm::errc::no_such_file_or_directory);
d386 1
a386 1
  EXPECT_EQ(nullptr, FS.get());
d393 1
a393 1
  EXPECT_EQ(nullptr, FS.get());
d397 1
a397 1
  EXPECT_EQ(nullptr, FS.get());
d399 1
a399 1
  EXPECT_EQ(nullptr, FS.get());
d403 1
a403 1
  EXPECT_EQ(nullptr, FS.get());
d405 1
a405 1
  EXPECT_EQ(nullptr, FS.get());
d410 1
a410 1
  EXPECT_EQ(nullptr, FS.get());
d414 1
a414 1
  EXPECT_EQ(nullptr, FS.get());
d418 1
a418 1
  EXPECT_EQ(nullptr, FS.get());
d422 1
a422 1
  EXPECT_EQ(nullptr, FS.get());
d426 1
a426 1
  EXPECT_EQ(nullptr, FS.get());
d430 1
a430 1
  EXPECT_EQ(nullptr, FS.get());
d434 1
a434 1
  EXPECT_EQ(nullptr, FS.get());
d438 1
a438 1
  EXPECT_EQ(nullptr, FS.get());
d441 1
a441 1
  EXPECT_EQ(nullptr, FS.get());
d443 1
a443 1
  EXPECT_EQ(nullptr, FS.get());
d447 1
a447 1
  EXPECT_EQ(nullptr, FS.get());
d451 1
a451 1
  EXPECT_EQ(nullptr, FS.get());
d456 1
a456 1
  EXPECT_EQ(nullptr, FS.get());
d460 1
a460 1
  EXPECT_EQ(nullptr, FS.get());
d464 1
a464 1
  EXPECT_EQ(nullptr, FS.get());
d466 1
a466 1
  EXPECT_EQ(nullptr, FS.get());
d468 1
a468 1
  EXPECT_EQ(nullptr, FS.get());
d490 1
a490 1
  ASSERT_TRUE(nullptr != FS.get());
d514 1
a514 1
  ASSERT_TRUE(nullptr != FS.get());
d533 5
a537 5
  ASSERT_TRUE(nullptr != FS.get());
  EXPECT_FALSE(FS->status("//root/path/to/file").getError());
  EXPECT_FALSE(FS->status("//root/path/to").getError());
  EXPECT_FALSE(FS->status("//root/path").getError());
  EXPECT_FALSE(FS->status("//root/").getError());
d546 5
a550 5
  ASSERT_TRUE(nullptr != FS.get());
  EXPECT_FALSE(FS->status("//root/path/to/file").getError());
  EXPECT_FALSE(FS->status("//root/path/to").getError());
  EXPECT_FALSE(FS->status("//root/path").getError());
  EXPECT_FALSE(FS->status("//root/").getError());
d559 5
a563 5
  ASSERT_TRUE(nullptr != FS.get());
  EXPECT_FALSE(FS->status("//root/path/to/file").getError());
  EXPECT_FALSE(FS->status("//root/path/to").getError());
  EXPECT_FALSE(FS->status("//root/path").getError());
  EXPECT_FALSE(FS->status("//root/").getError());
d577 5
a581 54
  ASSERT_TRUE(nullptr != FS.get());
  EXPECT_FALSE(FS->status("//root/path/to/file").getError());
  EXPECT_FALSE(FS->status("//root/path/to").getError());
  EXPECT_FALSE(FS->status("//root/path").getError());
  EXPECT_FALSE(FS->status("//root/").getError());
}

TEST_F(VFSFromYAMLTest, DirectoryIteration) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addDirectory("//root/");
  Lower->addDirectory("//root/foo");
  Lower->addDirectory("//root/foo/bar");
  Lower->addRegularFile("//root/foo/bar/a");
  Lower->addRegularFile("//root/foo/bar/b");
  Lower->addRegularFile("//root/file3");
  IntrusiveRefCntPtr<vfs::FileSystem> FS =
  getFromYAMLString("{ 'use-external-names': false,\n"
                    "  'roots': [\n"
                    "{\n"
                    "  'type': 'directory',\n"
                    "  'name': '//root/',\n"
                    "  'contents': [ {\n"
                    "                  'type': 'file',\n"
                    "                  'name': 'file1',\n"
                    "                  'external-contents': '//root/foo/bar/a'\n"
                    "                },\n"
                    "                {\n"
                    "                  'type': 'file',\n"
                    "                  'name': 'file2',\n"
                    "                  'external-contents': '//root/foo/bar/b'\n"
                    "                }\n"
                    "              ]\n"
                    "}\n"
                    "]\n"
                    "}",
                    Lower);
  ASSERT_TRUE(FS.get() != NULL);

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(FS);

  std::error_code EC;
  {
    const char *Contents[] = {"//root/file1", "//root/file2", "//root/file3",
                              "//root/foo"};
    checkContents(O->dir_begin("//root/", EC), makeStringRefVector(Contents));
  }

  {
    const char *Contents[] = {"//root/foo/bar/a", "//root/foo/bar/b"};
    checkContents(O->dir_begin("//root/foo/bar", EC),
                  makeStringRefVector(Contents));
  }
@


1.1.1.3.2.1
log
@Update LLVM to 3.6.1, requested by joerg in ticket 824.
@
text
@d35 1
a35 1
  ErrorOr<vfs::Status> status(const Twine &Path) override {
d42 8
a49 2
  ErrorOr<std::unique_ptr<vfs::File>>
  openFileForRead(const Twine &Path) override {
d542 2
a543 3
    std::unique_ptr<MemoryBuffer> Buffer = MemoryBuffer::getMemBuffer(Content);
    return getVFSFromYAML(std::move(Buffer), CountingDiagHandler, this,
                          ExternalFS);
@


1.1.1.4
log
@Import Clang 3.6RC1 r227398.
@
text
@d35 1
a35 1
  ErrorOr<vfs::Status> status(const Twine &Path) override {
d42 8
a49 2
  ErrorOr<std::unique_ptr<vfs::File>>
  openFileForRead(const Twine &Path) override {
d542 2
a543 3
    std::unique_ptr<MemoryBuffer> Buffer = MemoryBuffer::getMemBuffer(Content);
    return getVFSFromYAML(std::move(Buffer), CountingDiagHandler, this,
                          ExternalFS);
@


1.1.1.5
log
@Import Clang 3.8.0rc3 r261930.
@
text
@a16 1

a21 12
struct DummyFile : public vfs::File {
  vfs::Status S;
  explicit DummyFile(vfs::Status S) : S(S) {}
  llvm::ErrorOr<vfs::Status> status() override { return S; }
  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
  getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
            bool IsVolatile) override {
    llvm_unreachable("unimplemented");
  }
  virtual std::error_code close() override { return std::error_code(); }
};

d44 1
a44 10
    auto S = status(Path);
    if (S)
      return std::unique_ptr<vfs::File>(new DummyFile{*S});
    return S.getError();
  }
  llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
    return std::string();
  }
  std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
    return std::error_code();
d95 2
a96 2
    vfs::Status S(Path, UniqueID(FSID, FileID++), sys::TimeValue::now(), 0, 0,
                  1024, sys::fs::file_type::regular_file, Perms);
d101 2
a102 2
    vfs::Status S(Path, UniqueID(FSID, FileID++), sys::TimeValue::now(), 0, 0,
                  0, sys::fs::file_type::directory_file, Perms);
d107 2
a108 2
    vfs::Status S(Path, UniqueID(FSID, FileID++), sys::TimeValue::now(), 0, 0,
                  0, sys::fs::file_type::symlink_file, sys::fs::all_all);
d282 1
a282 1
} // end anonymous namespace
d351 8
d386 4
a389 1
  checkContents(O->dir_begin("/", EC), {"/file2", "/file1"});
d396 4
a399 1
  checkContents(O->dir_begin("/", EC), {"/dir2", "/file2", "/dir1", "/file1"});
d421 5
a425 2
  checkContents(vfs::recursive_directory_iterator(*O, "/", EC),
                {"/dir", "/dir/file2", "/file1"});
d441 7
a447 4
  checkContents(vfs::recursive_directory_iterator(*O, "/", EC),
                {"/dir", "/dir/file2", "/dir2", "/dir2/foo", "/hiddenByUp",
                 "/a", "/a/b", "/a/b/c", "/a/b/c/d", "/dir1", "/dir1/a",
                 "/dir1/a/b", "/dir1/foo", "/file1"});
d467 4
a470 1
  checkContents(O->dir_begin("/", EC), {"/file3", "/file2", "/file1"});
d491 5
a495 3
  checkContents(
      O->dir_begin("/", EC),
      {"/hiddenByUp", "/onlyInUp", "/hiddenByMid", "/onlyInMid", "/onlyInLow"});
a517 134
class InMemoryFileSystemTest : public ::testing::Test {
protected:
  clang::vfs::InMemoryFileSystem FS;
  clang::vfs::InMemoryFileSystem NormalizedFS;

  InMemoryFileSystemTest()
      : FS(/*UseNormalizedPaths=*/false),
        NormalizedFS(/*UseNormalizedPaths=*/true) {}
};

TEST_F(InMemoryFileSystemTest, IsEmpty) {
  auto Stat = FS.status("/a");
  ASSERT_EQ(Stat.getError(),errc::no_such_file_or_directory) << FS.toString();
  Stat = FS.status("/");
  ASSERT_EQ(Stat.getError(), errc::no_such_file_or_directory) << FS.toString();
}

TEST_F(InMemoryFileSystemTest, WindowsPath) {
  FS.addFile("c:/windows/system128/foo.cpp", 0, MemoryBuffer::getMemBuffer(""));
  auto Stat = FS.status("c:");
#if !defined(_WIN32)
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << FS.toString();
#endif
  Stat = FS.status("c:/windows/system128/foo.cpp");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << FS.toString();
  FS.addFile("d:/windows/foo.cpp", 0, MemoryBuffer::getMemBuffer(""));
  Stat = FS.status("d:/windows/foo.cpp");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << FS.toString();
}

TEST_F(InMemoryFileSystemTest, OverlayFile) {
  FS.addFile("/a", 0, MemoryBuffer::getMemBuffer("a"));
  NormalizedFS.addFile("/a", 0, MemoryBuffer::getMemBuffer("a"));
  auto Stat = FS.status("/");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << FS.toString();
  Stat = FS.status("/.");
  ASSERT_FALSE(Stat);
  Stat = NormalizedFS.status("/.");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << FS.toString();
  Stat = FS.status("/a");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_EQ("/a", Stat->getName());
}

TEST_F(InMemoryFileSystemTest, OverlayFileNoOwn) {
  auto Buf = MemoryBuffer::getMemBuffer("a");
  FS.addFileNoOwn("/a", 0, Buf.get());
  auto Stat = FS.status("/a");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_EQ("/a", Stat->getName());
}

TEST_F(InMemoryFileSystemTest, OpenFileForRead) {
  FS.addFile("/a", 0, MemoryBuffer::getMemBuffer("a"));
  FS.addFile("././c", 0, MemoryBuffer::getMemBuffer("c"));
  FS.addFile("./d/../d", 0, MemoryBuffer::getMemBuffer("d"));
  NormalizedFS.addFile("/a", 0, MemoryBuffer::getMemBuffer("a"));
  NormalizedFS.addFile("././c", 0, MemoryBuffer::getMemBuffer("c"));
  NormalizedFS.addFile("./d/../d", 0, MemoryBuffer::getMemBuffer("d"));
  auto File = FS.openFileForRead("/a");
  ASSERT_EQ("a", (*(*File)->getBuffer("ignored"))->getBuffer());
  File = FS.openFileForRead("/a"); // Open again.
  ASSERT_EQ("a", (*(*File)->getBuffer("ignored"))->getBuffer());
  File = NormalizedFS.openFileForRead("/././a"); // Open again.
  ASSERT_EQ("a", (*(*File)->getBuffer("ignored"))->getBuffer());
  File = FS.openFileForRead("/");
  ASSERT_EQ(File.getError(), errc::invalid_argument) << FS.toString();
  File = FS.openFileForRead("/b");
  ASSERT_EQ(File.getError(), errc::no_such_file_or_directory) << FS.toString();
  File = FS.openFileForRead("./c");
  ASSERT_FALSE(File);
  File = FS.openFileForRead("e/../d");
  ASSERT_FALSE(File);
  File = NormalizedFS.openFileForRead("./c");
  ASSERT_EQ("c", (*(*File)->getBuffer("ignored"))->getBuffer());
  File = NormalizedFS.openFileForRead("e/../d");
  ASSERT_EQ("d", (*(*File)->getBuffer("ignored"))->getBuffer());
}

TEST_F(InMemoryFileSystemTest, DuplicatedFile) {
  ASSERT_TRUE(FS.addFile("/a", 0, MemoryBuffer::getMemBuffer("a")));
  ASSERT_FALSE(FS.addFile("/a/b", 0, MemoryBuffer::getMemBuffer("a")));
  ASSERT_TRUE(FS.addFile("/a", 0, MemoryBuffer::getMemBuffer("a")));
  ASSERT_FALSE(FS.addFile("/a", 0, MemoryBuffer::getMemBuffer("b")));
}

TEST_F(InMemoryFileSystemTest, DirectoryIteration) {
  FS.addFile("/a", 0, MemoryBuffer::getMemBuffer(""));
  FS.addFile("/b/c", 0, MemoryBuffer::getMemBuffer(""));

  std::error_code EC;
  vfs::directory_iterator I = FS.dir_begin("/", EC);
  ASSERT_FALSE(EC);
  ASSERT_EQ("/a", I->getName());
  I.increment(EC);
  ASSERT_FALSE(EC);
  ASSERT_EQ("/b", I->getName());
  I.increment(EC);
  ASSERT_FALSE(EC);
  ASSERT_EQ(vfs::directory_iterator(), I);

  I = FS.dir_begin("/b", EC);
  ASSERT_FALSE(EC);
  ASSERT_EQ("/b/c", I->getName());
  I.increment(EC);
  ASSERT_FALSE(EC);
  ASSERT_EQ(vfs::directory_iterator(), I);
}

TEST_F(InMemoryFileSystemTest, WorkingDirectory) {
  FS.setCurrentWorkingDirectory("/b");
  FS.addFile("c", 0, MemoryBuffer::getMemBuffer(""));

  auto Stat = FS.status("/b/c");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_EQ("c", Stat->getName());
  ASSERT_EQ("/b", *FS.getCurrentWorkingDirectory());

  Stat = FS.status("c");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();

  auto ReplaceBackslashes = [](std::string S) {
    std::replace(S.begin(), S.end(), '\\', '/');
    return S;
  };
  NormalizedFS.setCurrentWorkingDirectory("/b/c");
  NormalizedFS.setCurrentWorkingDirectory(".");
  ASSERT_EQ("/b/c", ReplaceBackslashes(
                        NormalizedFS.getCurrentWorkingDirectory().get()));
  NormalizedFS.setCurrentWorkingDirectory("..");
  ASSERT_EQ("/b", ReplaceBackslashes(
                      NormalizedFS.getCurrentWorkingDirectory().get()));
}

d524 3
a526 1
  void SetUp() override { NumDiagnostics = 0; }
a593 1
  EXPECT_TRUE(S->IsVFSMapped);
a597 9
  EXPECT_FALSE(SLower->IsVFSMapped);

  // file after opening
  auto OpenedF = O->openFileForRead("//root/file1");
  ASSERT_FALSE(OpenedF.getError());
  auto OpenedS = (*OpenedF)->status();
  ASSERT_FALSE(OpenedS.getError());
  EXPECT_EQ("//root/foo/bar/a", OpenedS->getName());
  EXPECT_TRUE(OpenedS->IsVFSMapped);
d911 1
a911 1
  ASSERT_TRUE(FS.get() != nullptr);
d918 5
a922 2
  checkContents(O->dir_begin("//root/", EC),
                {"//root/file1", "//root/file2", "//root/file3", "//root/foo"});
d924 5
a928 2
  checkContents(O->dir_begin("//root/foo/bar", EC),
                {"//root/foo/bar/a", "//root/foo/bar/b"});
@


1.1.1.5.2.1
log
@Sync with HEAD
@
text
@a10 1
#include "llvm/ADT/Triple.h"
a11 1
#include "llvm/Support/Host.h"
d13 1
d32 1
a32 1
  std::error_code close() override { return std::error_code(); }
d117 2
a118 3
    vfs::Status S(Path, UniqueID(FSID, FileID++),
                  std::chrono::system_clock::now(), 0, 0, 1024,
                  sys::fs::file_type::regular_file, Perms);
d123 2
a124 3
    vfs::Status S(Path, UniqueID(FSID, FileID++),
                  std::chrono::system_clock::now(), 0, 0, 0,
                  sys::fs::file_type::directory_file, Perms);
d129 2
a130 3
    vfs::Status S(Path, UniqueID(FSID, FileID++),
                  std::chrono::system_clock::now(), 0, 0, 0,
                  sys::fs::file_type::symlink_file, sys::fs::all_all);
d351 1
d374 1
a374 1
static void checkContents(DirIter I, ArrayRef<StringRef> ExpectedOut) {
d376 5
a380 2
  SmallVector<StringRef, 4> Expected(ExpectedOut.begin(), ExpectedOut.end());
  SmallVector<std::string, 4> InputToCheck;
d382 2
a383 12
  // Do not rely on iteration order to check for contents, sort both
  // content vectors before comparison.
  for (DirIter E; !EC && I != E; I.increment(EC))
    InputToCheck.push_back(I->getName());

  std::sort(InputToCheck.begin(), InputToCheck.end());
  std::sort(Expected.begin(), Expected.end());
  EXPECT_EQ(InputToCheck.size(), Expected.size());

  unsigned LastElt = std::min(InputToCheck.size(), Expected.size());
  for (unsigned Idx = 0; Idx != LastElt; ++Idx)
    EXPECT_EQ(StringRef(InputToCheck[Idx]), Expected[Idx]);
d666 1
a666 1
    return getVFSFromYAML(std::move(Buffer), CountingDiagHandler, "", this,
a676 6

  // This is intended as a "XFAIL" for windows hosts.
  bool supportsSameDirMultipleYAMLEntries() {
    Triple Host(Triple::normalize(sys::getProcessTriple()));
    return !Host.isOSWindows();
  }
a1062 90

TEST_F(VFSFromYAMLTest, DirectoryIterationSameDirMultipleEntries) {
  // https://llvm.org/bugs/show_bug.cgi?id=27725
  if (!supportsSameDirMultipleYAMLEntries())
    return;

  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addDirectory("//root/zab");
  Lower->addDirectory("//root/baz");
  Lower->addRegularFile("//root/zab/a");
  Lower->addRegularFile("//root/zab/b");
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'use-external-names': false,\n"
      "  'roots': [\n"
      "{\n"
      "  'type': 'directory',\n"
      "  'name': '//root/baz/',\n"
      "  'contents': [ {\n"
      "                  'type': 'file',\n"
      "                  'name': 'x',\n"
      "                  'external-contents': '//root/zab/a'\n"
      "                }\n"
      "              ]\n"
      "},\n"
      "{\n"
      "  'type': 'directory',\n"
      "  'name': '//root/baz/',\n"
      "  'contents': [ {\n"
      "                  'type': 'file',\n"
      "                  'name': 'y',\n"
      "                  'external-contents': '//root/zab/b'\n"
      "                }\n"
      "              ]\n"
      "}\n"
      "]\n"
      "}",
      Lower);
  ASSERT_TRUE(FS.get() != nullptr);

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(FS);

  std::error_code EC;

  checkContents(O->dir_begin("//root/baz/", EC),
                {"//root/baz/x", "//root/baz/y"});
}

TEST_F(VFSFromYAMLTest, RecursiveDirectoryIterationLevel) {

  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addDirectory("//root/a");
  Lower->addDirectory("//root/a/b");
  Lower->addDirectory("//root/a/b/c");
  Lower->addRegularFile("//root/a/b/c/file");
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'use-external-names': false,\n"
      "  'roots': [\n"
      "{\n"
      "  'type': 'directory',\n"
      "  'name': '//root/a/b/c/',\n"
      "  'contents': [ {\n"
      "                  'type': 'file',\n"
      "                  'name': 'file',\n"
      "                  'external-contents': '//root/a/b/c/file'\n"
      "                }\n"
      "              ]\n"
      "},\n"
      "]\n"
      "}",
      Lower);
  ASSERT_TRUE(FS.get() != nullptr);

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(FS);

  std::error_code EC;

  // Test recursive_directory_iterator level()
  vfs::recursive_directory_iterator I = vfs::recursive_directory_iterator(
                                        *O, "//root", EC), E;
  ASSERT_FALSE(EC);
  for (int l = 0; I != E; I.increment(EC), ++l) {
    ASSERT_FALSE(EC);
    EXPECT_EQ(I.level(), l);
  }
  EXPECT_EQ(I, E);
}
@


1.1.1.6
log
@Import Clang pre-4.0.0 r291444.
@
text
@a10 1
#include "llvm/ADT/Triple.h"
a11 1
#include "llvm/Support/Host.h"
d13 1
d32 1
a32 1
  std::error_code close() override { return std::error_code(); }
d117 2
a118 3
    vfs::Status S(Path, UniqueID(FSID, FileID++),
                  std::chrono::system_clock::now(), 0, 0, 1024,
                  sys::fs::file_type::regular_file, Perms);
d123 2
a124 3
    vfs::Status S(Path, UniqueID(FSID, FileID++),
                  std::chrono::system_clock::now(), 0, 0, 0,
                  sys::fs::file_type::directory_file, Perms);
d129 2
a130 3
    vfs::Status S(Path, UniqueID(FSID, FileID++),
                  std::chrono::system_clock::now(), 0, 0, 0,
                  sys::fs::file_type::symlink_file, sys::fs::all_all);
d351 1
d374 1
a374 1
static void checkContents(DirIter I, ArrayRef<StringRef> ExpectedOut) {
d376 5
a380 2
  SmallVector<StringRef, 4> Expected(ExpectedOut.begin(), ExpectedOut.end());
  SmallVector<std::string, 4> InputToCheck;
d382 2
a383 12
  // Do not rely on iteration order to check for contents, sort both
  // content vectors before comparison.
  for (DirIter E; !EC && I != E; I.increment(EC))
    InputToCheck.push_back(I->getName());

  std::sort(InputToCheck.begin(), InputToCheck.end());
  std::sort(Expected.begin(), Expected.end());
  EXPECT_EQ(InputToCheck.size(), Expected.size());

  unsigned LastElt = std::min(InputToCheck.size(), Expected.size());
  for (unsigned Idx = 0; Idx != LastElt; ++Idx)
    EXPECT_EQ(StringRef(InputToCheck[Idx]), Expected[Idx]);
d666 1
a666 1
    return getVFSFromYAML(std::move(Buffer), CountingDiagHandler, "", this,
a676 6

  // This is intended as a "XFAIL" for windows hosts.
  bool supportsSameDirMultipleYAMLEntries() {
    Triple Host(Triple::normalize(sys::getProcessTriple()));
    return !Host.isOSWindows();
  }
a1062 90

TEST_F(VFSFromYAMLTest, DirectoryIterationSameDirMultipleEntries) {
  // https://llvm.org/bugs/show_bug.cgi?id=27725
  if (!supportsSameDirMultipleYAMLEntries())
    return;

  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addDirectory("//root/zab");
  Lower->addDirectory("//root/baz");
  Lower->addRegularFile("//root/zab/a");
  Lower->addRegularFile("//root/zab/b");
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'use-external-names': false,\n"
      "  'roots': [\n"
      "{\n"
      "  'type': 'directory',\n"
      "  'name': '//root/baz/',\n"
      "  'contents': [ {\n"
      "                  'type': 'file',\n"
      "                  'name': 'x',\n"
      "                  'external-contents': '//root/zab/a'\n"
      "                }\n"
      "              ]\n"
      "},\n"
      "{\n"
      "  'type': 'directory',\n"
      "  'name': '//root/baz/',\n"
      "  'contents': [ {\n"
      "                  'type': 'file',\n"
      "                  'name': 'y',\n"
      "                  'external-contents': '//root/zab/b'\n"
      "                }\n"
      "              ]\n"
      "}\n"
      "]\n"
      "}",
      Lower);
  ASSERT_TRUE(FS.get() != nullptr);

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(FS);

  std::error_code EC;

  checkContents(O->dir_begin("//root/baz/", EC),
                {"//root/baz/x", "//root/baz/y"});
}

TEST_F(VFSFromYAMLTest, RecursiveDirectoryIterationLevel) {

  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addDirectory("//root/a");
  Lower->addDirectory("//root/a/b");
  Lower->addDirectory("//root/a/b/c");
  Lower->addRegularFile("//root/a/b/c/file");
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'use-external-names': false,\n"
      "  'roots': [\n"
      "{\n"
      "  'type': 'directory',\n"
      "  'name': '//root/a/b/c/',\n"
      "  'contents': [ {\n"
      "                  'type': 'file',\n"
      "                  'name': 'file',\n"
      "                  'external-contents': '//root/a/b/c/file'\n"
      "                }\n"
      "              ]\n"
      "},\n"
      "]\n"
      "}",
      Lower);
  ASSERT_TRUE(FS.get() != nullptr);

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(FS);

  std::error_code EC;

  // Test recursive_directory_iterator level()
  vfs::recursive_directory_iterator I = vfs::recursive_directory_iterator(
                                        *O, "//root", EC), E;
  ASSERT_FALSE(EC);
  for (int l = 0; I != E; I.increment(EC), ++l) {
    ASSERT_FALSE(EC);
    EXPECT_EQ(I.level(), l);
  }
  EXPECT_EQ(I, E);
}
@


1.1.1.7
log
@Import clang r309604 from branches/release_50
@
text
@d303 1
a303 1
    if (Path != "") {
a304 18
    }
  }
  operator StringRef() { return Path.str(); }
};

struct ScopedLink {
  SmallString<128> Path;
  ScopedLink(const Twine &To, const Twine &From) {
    Path = From.str();
    std::error_code EC = sys::fs::create_link(To, From);
    if (EC)
      Path = "";
    EXPECT_FALSE(EC);
  }
  ~ScopedLink() {
    if (Path != "") {
      EXPECT_FALSE(llvm::sys::fs::remove(Path.str()));
    }
a336 36
#ifdef LLVM_ON_UNIX
TEST(VirtualFileSystemTest, BrokenSymlinkRealFSIteration) {
  ScopedDir TestDirectory("virtual-file-system-test", /*Unique*/ true);
  IntrusiveRefCntPtr<vfs::FileSystem> FS = vfs::getRealFileSystem();

  ScopedLink _a("no_such_file", TestDirectory + "/a");
  ScopedDir _b(TestDirectory + "/b");
  ScopedLink _c("no_such_file", TestDirectory + "/c");

  std::error_code EC;
  for (vfs::directory_iterator I = FS->dir_begin(Twine(TestDirectory), EC), E;
       I != E; I.increment(EC)) {
    // Skip broken symlinks.
    auto EC2 = std::make_error_code(std::errc::no_such_file_or_directory);
    if (EC == EC2) {
      EC.clear();
      continue;
    }
    // For bot debugging.
    if (EC) {
      outs() << "Error code found:\n"
             << "EC value: " << EC.value() << "\n"
             << "EC category: " << EC.category().name()
             << "EC message: " << EC.message() << "\n";

      outs() << "Error code tested for:\n"
             << "EC value: " << EC2.value() << "\n"
             << "EC category: " << EC2.category().name()
             << "EC message: " << EC2.message() << "\n";
    }
    ASSERT_FALSE(EC);
    EXPECT_TRUE(I->getName() == _b);
  }
}
#endif

a375 50
#ifdef LLVM_ON_UNIX
TEST(VirtualFileSystemTest, BrokenSymlinkRealFSRecursiveIteration) {
  ScopedDir TestDirectory("virtual-file-system-test", /*Unique*/ true);
  IntrusiveRefCntPtr<vfs::FileSystem> FS = vfs::getRealFileSystem();

  ScopedLink _a("no_such_file", TestDirectory + "/a");
  ScopedDir _b(TestDirectory + "/b");
  ScopedLink _ba("no_such_file", TestDirectory + "/b/a");
  ScopedDir _bb(TestDirectory + "/b/b");
  ScopedLink _bc("no_such_file", TestDirectory + "/b/c");
  ScopedLink _c("no_such_file", TestDirectory + "/c");
  ScopedDir _d(TestDirectory + "/d");
  ScopedDir _dd(TestDirectory + "/d/d");
  ScopedDir _ddd(TestDirectory + "/d/d/d");
  ScopedLink _e("no_such_file", TestDirectory + "/e");
  std::vector<StringRef> Expected = {_b, _bb, _d, _dd, _ddd};

  std::vector<std::string> Contents;
  std::error_code EC;
  for (vfs::recursive_directory_iterator I(*FS, Twine(TestDirectory), EC), E;
       I != E; I.increment(EC)) {
    // Skip broken symlinks.
    auto EC2 = std::make_error_code(std::errc::no_such_file_or_directory);
    if (EC == EC2) {
      EC.clear();
      continue;
    }
    // For bot debugging.
    if (EC) {
      outs() << "Error code found:\n"
             << "EC value: " << EC.value() << "\n"
             << "EC category: " << EC.category().name()
             << "EC message: " << EC.message() << "\n";

      outs() << "Error code tested for:\n"
             << "EC value: " << EC2.value() << "\n"
             << "EC category: " << EC2.category().name()
             << "EC message: " << EC2.message() << "\n";
    }
    ASSERT_FALSE(EC);
    Contents.push_back(I->getName());
  }

  // Check sorted contents.
  std::sort(Contents.begin(), Contents.end());
  EXPECT_EQ(Expected.size(), Contents.size());
  EXPECT_TRUE(std::equal(Contents.begin(), Contents.end(), Expected.begin()));
}
#endif

@


1.1.1.7.4.1
log
@Sync with HEAD
@
text
@a11 1
#include "llvm/Config/llvm-config.h"
a68 15
  // Map any symlink to "/symlink".
  std::error_code getRealPath(const Twine &Path,
                              SmallVectorImpl<char> &Output) const override {
    auto I = FilesAndDirs.find(Path.str());
    if (I == FilesAndDirs.end())
      return make_error_code(llvm::errc::no_such_file_or_directory);
    if (I->second.isSymlink()) {
      Output.clear();
      Twine("/symlink").toVector(Output);
      return std::error_code();
    }
    Output.clear();
    Path.toVector(Output);
    return std::error_code();
  }
a197 29
TEST(VirtualFileSystemTest, GetRealPathInOverlay) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("/foo");
  Lower->addSymlink("/lower_link");
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Upper);

  // Regular file.
  SmallString<16> RealPath;
  EXPECT_FALSE(O->getRealPath("/foo", RealPath));
  EXPECT_EQ(RealPath.str(), "/foo");

  // Expect no error getting real path for symlink in lower overlay.
  EXPECT_FALSE(O->getRealPath("/lower_link", RealPath));
  EXPECT_EQ(RealPath.str(), "/symlink");

  // Try a non-existing link.
  EXPECT_EQ(O->getRealPath("/upper_link", RealPath),
            errc::no_such_file_or_directory);

  // Add a new symlink in upper.
  Upper->addSymlink("/upper_link");
  EXPECT_FALSE(O->getRealPath("/upper_link", RealPath));
  EXPECT_EQ(RealPath.str(), "/symlink");
}

d445 1
d447 1
a447 4
  std::vector<StringRef> ExpectedBrokenSymlinks = {_a, _ba, _bc, _c, _e};
  std::vector<StringRef> ExpectedNonBrokenSymlinks = {_b, _bb, _d, _dd, _ddd};
  std::vector<std::string> VisitedBrokenSymlinks;
  std::vector<std::string> VisitedNonBrokenSymlinks;
d451 1
d454 1
a454 1
      VisitedBrokenSymlinks.push_back(I->getName());
d470 1
a470 1
    VisitedNonBrokenSymlinks.push_back(I->getName());
d473 4
a476 11
  // Check visited file names.
  std::sort(VisitedBrokenSymlinks.begin(), VisitedBrokenSymlinks.end());
  std::sort(VisitedNonBrokenSymlinks.begin(), VisitedNonBrokenSymlinks.end());
  EXPECT_EQ(ExpectedBrokenSymlinks.size(), VisitedBrokenSymlinks.size());
  EXPECT_TRUE(std::equal(VisitedBrokenSymlinks.begin(),
                         VisitedBrokenSymlinks.end(),
                         ExpectedBrokenSymlinks.begin()));
  EXPECT_EQ(ExpectedNonBrokenSymlinks.size(), VisitedNonBrokenSymlinks.size());
  EXPECT_TRUE(std::equal(VisitedNonBrokenSymlinks.begin(),
                         VisitedNonBrokenSymlinks.end(),
                         ExpectedNonBrokenSymlinks.begin()));
d491 2
a492 2
  llvm::sort(InputToCheck.begin(), InputToCheck.end());
  llvm::sort(Expected.begin(), Expected.end());
a762 106
#if !defined(_WIN32)
TEST_F(InMemoryFileSystemTest, GetRealPath) {
  SmallString<16> Path;
  EXPECT_EQ(FS.getRealPath("b", Path), errc::operation_not_permitted);

  auto GetRealPath = [this](StringRef P) {
    SmallString<16> Output;
    auto EC = FS.getRealPath(P, Output);
    EXPECT_FALSE(EC);
    return Output.str().str();
  };

  FS.setCurrentWorkingDirectory("a");
  EXPECT_EQ(GetRealPath("b"), "a/b");
  EXPECT_EQ(GetRealPath("../b"), "b");
  EXPECT_EQ(GetRealPath("b/./c"), "a/b/c");

  FS.setCurrentWorkingDirectory("/a");
  EXPECT_EQ(GetRealPath("b"), "/a/b");
  EXPECT_EQ(GetRealPath("../b"), "/b");
  EXPECT_EQ(GetRealPath("b/./c"), "/a/b/c");
}
#endif // _WIN32

TEST_F(InMemoryFileSystemTest, AddFileWithUser) {
  FS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), 0xFEEDFACE);
  auto Stat = FS.status("/a");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  ASSERT_EQ(0xFEEDFACE, Stat->getUser());
  Stat = FS.status("/a/b");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  ASSERT_EQ(0xFEEDFACE, Stat->getUser());
  Stat = FS.status("/a/b/c");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isRegularFile());
  ASSERT_EQ(sys::fs::perms::all_all, Stat->getPermissions());
  ASSERT_EQ(0xFEEDFACE, Stat->getUser());
}

TEST_F(InMemoryFileSystemTest, AddFileWithGroup) {
  FS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), None, 0xDABBAD00);
  auto Stat = FS.status("/a");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  ASSERT_EQ(0xDABBAD00, Stat->getGroup());
  Stat = FS.status("/a/b");
  ASSERT_TRUE(Stat->isDirectory());
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_EQ(0xDABBAD00, Stat->getGroup());
  Stat = FS.status("/a/b/c");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isRegularFile());
  ASSERT_EQ(sys::fs::perms::all_all, Stat->getPermissions());
  ASSERT_EQ(0xDABBAD00, Stat->getGroup());
}

TEST_F(InMemoryFileSystemTest, AddFileWithFileType) {
  FS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), None, None,
             sys::fs::file_type::socket_file);
  auto Stat = FS.status("/a");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  Stat = FS.status("/a/b");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  Stat = FS.status("/a/b/c");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_EQ(sys::fs::file_type::socket_file, Stat->getType());
  ASSERT_EQ(sys::fs::perms::all_all, Stat->getPermissions());
}

TEST_F(InMemoryFileSystemTest, AddFileWithPerms) {
  FS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), None, None,
             None, sys::fs::perms::owner_read | sys::fs::perms::owner_write);
  auto Stat = FS.status("/a");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  ASSERT_EQ(sys::fs::perms::owner_read | sys::fs::perms::owner_write |
            sys::fs::perms::owner_exe, Stat->getPermissions());
  Stat = FS.status("/a/b");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  ASSERT_EQ(sys::fs::perms::owner_read | sys::fs::perms::owner_write |
            sys::fs::perms::owner_exe, Stat->getPermissions());
  Stat = FS.status("/a/b/c");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isRegularFile());
  ASSERT_EQ(sys::fs::perms::owner_read | sys::fs::perms::owner_write,
            Stat->getPermissions());
}

TEST_F(InMemoryFileSystemTest, AddDirectoryThenAddChild) {
  FS.addFile("/a", 0, MemoryBuffer::getMemBuffer(""), /*User=*/None,
             /*Group=*/None, sys::fs::file_type::directory_file);
  FS.addFile("/a/b", 0, MemoryBuffer::getMemBuffer("abc"), /*User=*/None,
             /*Group=*/None, sys::fs::file_type::regular_file);
  auto Stat = FS.status("/a");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  Stat = FS.status("/a/b");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isRegularFile());
}

@


1.1.1.7.4.2
log
@Mostly merge changes from HEAD upto 20200411
@
text
@@


1.1.1.7.2.1
log
@Sync with HEAD
@
text
@a11 1
#include "llvm/Config/llvm-config.h"
a68 15
  // Map any symlink to "/symlink".
  std::error_code getRealPath(const Twine &Path,
                              SmallVectorImpl<char> &Output) const override {
    auto I = FilesAndDirs.find(Path.str());
    if (I == FilesAndDirs.end())
      return make_error_code(llvm::errc::no_such_file_or_directory);
    if (I->second.isSymlink()) {
      Output.clear();
      Twine("/symlink").toVector(Output);
      return std::error_code();
    }
    Output.clear();
    Path.toVector(Output);
    return std::error_code();
  }
a197 29
TEST(VirtualFileSystemTest, GetRealPathInOverlay) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("/foo");
  Lower->addSymlink("/lower_link");
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Upper);

  // Regular file.
  SmallString<16> RealPath;
  EXPECT_FALSE(O->getRealPath("/foo", RealPath));
  EXPECT_EQ(RealPath.str(), "/foo");

  // Expect no error getting real path for symlink in lower overlay.
  EXPECT_FALSE(O->getRealPath("/lower_link", RealPath));
  EXPECT_EQ(RealPath.str(), "/symlink");

  // Try a non-existing link.
  EXPECT_EQ(O->getRealPath("/upper_link", RealPath),
            errc::no_such_file_or_directory);

  // Add a new symlink in upper.
  Upper->addSymlink("/upper_link");
  EXPECT_FALSE(O->getRealPath("/upper_link", RealPath));
  EXPECT_EQ(RealPath.str(), "/symlink");
}

d445 1
d447 1
a447 4
  std::vector<StringRef> ExpectedBrokenSymlinks = {_a, _ba, _bc, _c, _e};
  std::vector<StringRef> ExpectedNonBrokenSymlinks = {_b, _bb, _d, _dd, _ddd};
  std::vector<std::string> VisitedBrokenSymlinks;
  std::vector<std::string> VisitedNonBrokenSymlinks;
d451 1
d454 1
a454 1
      VisitedBrokenSymlinks.push_back(I->getName());
d470 1
a470 1
    VisitedNonBrokenSymlinks.push_back(I->getName());
d473 4
a476 11
  // Check visited file names.
  std::sort(VisitedBrokenSymlinks.begin(), VisitedBrokenSymlinks.end());
  std::sort(VisitedNonBrokenSymlinks.begin(), VisitedNonBrokenSymlinks.end());
  EXPECT_EQ(ExpectedBrokenSymlinks.size(), VisitedBrokenSymlinks.size());
  EXPECT_TRUE(std::equal(VisitedBrokenSymlinks.begin(),
                         VisitedBrokenSymlinks.end(),
                         ExpectedBrokenSymlinks.begin()));
  EXPECT_EQ(ExpectedNonBrokenSymlinks.size(), VisitedNonBrokenSymlinks.size());
  EXPECT_TRUE(std::equal(VisitedNonBrokenSymlinks.begin(),
                         VisitedNonBrokenSymlinks.end(),
                         ExpectedNonBrokenSymlinks.begin()));
d491 2
a492 2
  llvm::sort(InputToCheck.begin(), InputToCheck.end());
  llvm::sort(Expected.begin(), Expected.end());
a762 106
#if !defined(_WIN32)
TEST_F(InMemoryFileSystemTest, GetRealPath) {
  SmallString<16> Path;
  EXPECT_EQ(FS.getRealPath("b", Path), errc::operation_not_permitted);

  auto GetRealPath = [this](StringRef P) {
    SmallString<16> Output;
    auto EC = FS.getRealPath(P, Output);
    EXPECT_FALSE(EC);
    return Output.str().str();
  };

  FS.setCurrentWorkingDirectory("a");
  EXPECT_EQ(GetRealPath("b"), "a/b");
  EXPECT_EQ(GetRealPath("../b"), "b");
  EXPECT_EQ(GetRealPath("b/./c"), "a/b/c");

  FS.setCurrentWorkingDirectory("/a");
  EXPECT_EQ(GetRealPath("b"), "/a/b");
  EXPECT_EQ(GetRealPath("../b"), "/b");
  EXPECT_EQ(GetRealPath("b/./c"), "/a/b/c");
}
#endif // _WIN32

TEST_F(InMemoryFileSystemTest, AddFileWithUser) {
  FS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), 0xFEEDFACE);
  auto Stat = FS.status("/a");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  ASSERT_EQ(0xFEEDFACE, Stat->getUser());
  Stat = FS.status("/a/b");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  ASSERT_EQ(0xFEEDFACE, Stat->getUser());
  Stat = FS.status("/a/b/c");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isRegularFile());
  ASSERT_EQ(sys::fs::perms::all_all, Stat->getPermissions());
  ASSERT_EQ(0xFEEDFACE, Stat->getUser());
}

TEST_F(InMemoryFileSystemTest, AddFileWithGroup) {
  FS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), None, 0xDABBAD00);
  auto Stat = FS.status("/a");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  ASSERT_EQ(0xDABBAD00, Stat->getGroup());
  Stat = FS.status("/a/b");
  ASSERT_TRUE(Stat->isDirectory());
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_EQ(0xDABBAD00, Stat->getGroup());
  Stat = FS.status("/a/b/c");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isRegularFile());
  ASSERT_EQ(sys::fs::perms::all_all, Stat->getPermissions());
  ASSERT_EQ(0xDABBAD00, Stat->getGroup());
}

TEST_F(InMemoryFileSystemTest, AddFileWithFileType) {
  FS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), None, None,
             sys::fs::file_type::socket_file);
  auto Stat = FS.status("/a");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  Stat = FS.status("/a/b");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  Stat = FS.status("/a/b/c");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_EQ(sys::fs::file_type::socket_file, Stat->getType());
  ASSERT_EQ(sys::fs::perms::all_all, Stat->getPermissions());
}

TEST_F(InMemoryFileSystemTest, AddFileWithPerms) {
  FS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), None, None,
             None, sys::fs::perms::owner_read | sys::fs::perms::owner_write);
  auto Stat = FS.status("/a");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  ASSERT_EQ(sys::fs::perms::owner_read | sys::fs::perms::owner_write |
            sys::fs::perms::owner_exe, Stat->getPermissions());
  Stat = FS.status("/a/b");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  ASSERT_EQ(sys::fs::perms::owner_read | sys::fs::perms::owner_write |
            sys::fs::perms::owner_exe, Stat->getPermissions());
  Stat = FS.status("/a/b/c");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isRegularFile());
  ASSERT_EQ(sys::fs::perms::owner_read | sys::fs::perms::owner_write,
            Stat->getPermissions());
}

TEST_F(InMemoryFileSystemTest, AddDirectoryThenAddChild) {
  FS.addFile("/a", 0, MemoryBuffer::getMemBuffer(""), /*User=*/None,
             /*Group=*/None, sys::fs::file_type::directory_file);
  FS.addFile("/a/b", 0, MemoryBuffer::getMemBuffer("abc"), /*User=*/None,
             /*Group=*/None, sys::fs::file_type::regular_file);
  auto Stat = FS.status("/a");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  Stat = FS.status("/a/b");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isRegularFile());
}

@


1.1.1.8
log
@Import clang r337282 from trunk
@
text
@a11 1
#include "llvm/Config/llvm-config.h"
a68 15
  // Map any symlink to "/symlink".
  std::error_code getRealPath(const Twine &Path,
                              SmallVectorImpl<char> &Output) const override {
    auto I = FilesAndDirs.find(Path.str());
    if (I == FilesAndDirs.end())
      return make_error_code(llvm::errc::no_such_file_or_directory);
    if (I->second.isSymlink()) {
      Output.clear();
      Twine("/symlink").toVector(Output);
      return std::error_code();
    }
    Output.clear();
    Path.toVector(Output);
    return std::error_code();
  }
a197 29
TEST(VirtualFileSystemTest, GetRealPathInOverlay) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("/foo");
  Lower->addSymlink("/lower_link");
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Upper);

  // Regular file.
  SmallString<16> RealPath;
  EXPECT_FALSE(O->getRealPath("/foo", RealPath));
  EXPECT_EQ(RealPath.str(), "/foo");

  // Expect no error getting real path for symlink in lower overlay.
  EXPECT_FALSE(O->getRealPath("/lower_link", RealPath));
  EXPECT_EQ(RealPath.str(), "/symlink");

  // Try a non-existing link.
  EXPECT_EQ(O->getRealPath("/upper_link", RealPath),
            errc::no_such_file_or_directory);

  // Add a new symlink in upper.
  Upper->addSymlink("/upper_link");
  EXPECT_FALSE(O->getRealPath("/upper_link", RealPath));
  EXPECT_EQ(RealPath.str(), "/symlink");
}

d445 1
d447 1
a447 4
  std::vector<StringRef> ExpectedBrokenSymlinks = {_a, _ba, _bc, _c, _e};
  std::vector<StringRef> ExpectedNonBrokenSymlinks = {_b, _bb, _d, _dd, _ddd};
  std::vector<std::string> VisitedBrokenSymlinks;
  std::vector<std::string> VisitedNonBrokenSymlinks;
d451 1
d454 1
a454 1
      VisitedBrokenSymlinks.push_back(I->getName());
d470 1
a470 1
    VisitedNonBrokenSymlinks.push_back(I->getName());
d473 4
a476 11
  // Check visited file names.
  std::sort(VisitedBrokenSymlinks.begin(), VisitedBrokenSymlinks.end());
  std::sort(VisitedNonBrokenSymlinks.begin(), VisitedNonBrokenSymlinks.end());
  EXPECT_EQ(ExpectedBrokenSymlinks.size(), VisitedBrokenSymlinks.size());
  EXPECT_TRUE(std::equal(VisitedBrokenSymlinks.begin(),
                         VisitedBrokenSymlinks.end(),
                         ExpectedBrokenSymlinks.begin()));
  EXPECT_EQ(ExpectedNonBrokenSymlinks.size(), VisitedNonBrokenSymlinks.size());
  EXPECT_TRUE(std::equal(VisitedNonBrokenSymlinks.begin(),
                         VisitedNonBrokenSymlinks.end(),
                         ExpectedNonBrokenSymlinks.begin()));
d491 2
a492 2
  llvm::sort(InputToCheck.begin(), InputToCheck.end());
  llvm::sort(Expected.begin(), Expected.end());
a762 106
#if !defined(_WIN32)
TEST_F(InMemoryFileSystemTest, GetRealPath) {
  SmallString<16> Path;
  EXPECT_EQ(FS.getRealPath("b", Path), errc::operation_not_permitted);

  auto GetRealPath = [this](StringRef P) {
    SmallString<16> Output;
    auto EC = FS.getRealPath(P, Output);
    EXPECT_FALSE(EC);
    return Output.str().str();
  };

  FS.setCurrentWorkingDirectory("a");
  EXPECT_EQ(GetRealPath("b"), "a/b");
  EXPECT_EQ(GetRealPath("../b"), "b");
  EXPECT_EQ(GetRealPath("b/./c"), "a/b/c");

  FS.setCurrentWorkingDirectory("/a");
  EXPECT_EQ(GetRealPath("b"), "/a/b");
  EXPECT_EQ(GetRealPath("../b"), "/b");
  EXPECT_EQ(GetRealPath("b/./c"), "/a/b/c");
}
#endif // _WIN32

TEST_F(InMemoryFileSystemTest, AddFileWithUser) {
  FS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), 0xFEEDFACE);
  auto Stat = FS.status("/a");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  ASSERT_EQ(0xFEEDFACE, Stat->getUser());
  Stat = FS.status("/a/b");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  ASSERT_EQ(0xFEEDFACE, Stat->getUser());
  Stat = FS.status("/a/b/c");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isRegularFile());
  ASSERT_EQ(sys::fs::perms::all_all, Stat->getPermissions());
  ASSERT_EQ(0xFEEDFACE, Stat->getUser());
}

TEST_F(InMemoryFileSystemTest, AddFileWithGroup) {
  FS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), None, 0xDABBAD00);
  auto Stat = FS.status("/a");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  ASSERT_EQ(0xDABBAD00, Stat->getGroup());
  Stat = FS.status("/a/b");
  ASSERT_TRUE(Stat->isDirectory());
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_EQ(0xDABBAD00, Stat->getGroup());
  Stat = FS.status("/a/b/c");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isRegularFile());
  ASSERT_EQ(sys::fs::perms::all_all, Stat->getPermissions());
  ASSERT_EQ(0xDABBAD00, Stat->getGroup());
}

TEST_F(InMemoryFileSystemTest, AddFileWithFileType) {
  FS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), None, None,
             sys::fs::file_type::socket_file);
  auto Stat = FS.status("/a");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  Stat = FS.status("/a/b");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  Stat = FS.status("/a/b/c");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_EQ(sys::fs::file_type::socket_file, Stat->getType());
  ASSERT_EQ(sys::fs::perms::all_all, Stat->getPermissions());
}

TEST_F(InMemoryFileSystemTest, AddFileWithPerms) {
  FS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), None, None,
             None, sys::fs::perms::owner_read | sys::fs::perms::owner_write);
  auto Stat = FS.status("/a");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  ASSERT_EQ(sys::fs::perms::owner_read | sys::fs::perms::owner_write |
            sys::fs::perms::owner_exe, Stat->getPermissions());
  Stat = FS.status("/a/b");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  ASSERT_EQ(sys::fs::perms::owner_read | sys::fs::perms::owner_write |
            sys::fs::perms::owner_exe, Stat->getPermissions());
  Stat = FS.status("/a/b/c");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isRegularFile());
  ASSERT_EQ(sys::fs::perms::owner_read | sys::fs::perms::owner_write,
            Stat->getPermissions());
}

TEST_F(InMemoryFileSystemTest, AddDirectoryThenAddChild) {
  FS.addFile("/a", 0, MemoryBuffer::getMemBuffer(""), /*User=*/None,
             /*Group=*/None, sys::fs::file_type::directory_file);
  FS.addFile("/a/b", 0, MemoryBuffer::getMemBuffer("abc"), /*User=*/None,
             /*Group=*/None, sys::fs::file_type::regular_file);
  auto Stat = FS.status("/a");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  Stat = FS.status("/a/b");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isRegularFile());
}

@


1.1.1.9
log
@Mark old LLVM instance as dead.
@
text
@@


1.1.1.3.4.1
log
@file VirtualFileSystemTest.cpp was added on branch tls-maxphys on 2014-08-19 23:49:28 +0000
@
text
@d1 934
@


1.1.1.3.4.2
log
@Rebase to HEAD as of a few days ago.
@
text
@a0 934
//===- unittests/Basic/VirtualFileSystem.cpp ---------------- VFS tests ---===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/Basic/VirtualFileSystem.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SourceMgr.h"
#include "gtest/gtest.h"
#include <map>
using namespace clang;
using namespace llvm;
using llvm::sys::fs::UniqueID;

namespace {
class DummyFileSystem : public vfs::FileSystem {
  int FSID;   // used to produce UniqueIDs
  int FileID; // used to produce UniqueIDs
  std::map<std::string, vfs::Status> FilesAndDirs;

  static int getNextFSID() {
    static int Count = 0;
    return Count++;
  }

public:
  DummyFileSystem() : FSID(getNextFSID()), FileID(0) {}

  ErrorOr<vfs::Status> status(const Twine &Path) {
    std::map<std::string, vfs::Status>::iterator I =
        FilesAndDirs.find(Path.str());
    if (I == FilesAndDirs.end())
      return make_error_code(llvm::errc::no_such_file_or_directory);
    return I->second;
  }
  std::error_code openFileForRead(const Twine &Path,
                                  std::unique_ptr<vfs::File> &Result) {
    llvm_unreachable("unimplemented");
  }
  std::error_code getBufferForFile(const Twine &Name,
                                   std::unique_ptr<MemoryBuffer> &Result,
                                   int64_t FileSize = -1,
                                   bool RequiresNullTerminator = true) {
    llvm_unreachable("unimplemented");
  }

  struct DirIterImpl : public clang::vfs::detail::DirIterImpl {
    std::map<std::string, vfs::Status> &FilesAndDirs;
    std::map<std::string, vfs::Status>::iterator I;
    std::string Path;
    bool isInPath(StringRef S) {
      if (Path.size() < S.size() && S.find(Path) == 0) {
        auto LastSep = S.find_last_of('/');
        if (LastSep == Path.size() || LastSep == Path.size()-1)
          return true;
      }
      return false;
    }
    DirIterImpl(std::map<std::string, vfs::Status> &FilesAndDirs,
                const Twine &_Path)
        : FilesAndDirs(FilesAndDirs), I(FilesAndDirs.begin()),
          Path(_Path.str()) {
      for ( ; I != FilesAndDirs.end(); ++I) {
        if (isInPath(I->first)) {
          CurrentEntry = I->second;
          break;
        }
      }
    }
    std::error_code increment() override {
      ++I;
      for ( ; I != FilesAndDirs.end(); ++I) {
        if (isInPath(I->first)) {
          CurrentEntry = I->second;
          break;
        }
      }
      if (I == FilesAndDirs.end())
        CurrentEntry = vfs::Status();
      return std::error_code();
    }
  };

  vfs::directory_iterator dir_begin(const Twine &Dir,
                                    std::error_code &EC) override {
    return vfs::directory_iterator(
        std::make_shared<DirIterImpl>(FilesAndDirs, Dir));
  }

  void addEntry(StringRef Path, const vfs::Status &Status) {
    FilesAndDirs[Path] = Status;
  }

  void addRegularFile(StringRef Path, sys::fs::perms Perms = sys::fs::all_all) {
    vfs::Status S(Path, Path, UniqueID(FSID, FileID++), sys::TimeValue::now(),
                  0, 0, 1024, sys::fs::file_type::regular_file, Perms);
    addEntry(Path, S);
  }

  void addDirectory(StringRef Path, sys::fs::perms Perms = sys::fs::all_all) {
    vfs::Status S(Path, Path, UniqueID(FSID, FileID++), sys::TimeValue::now(),
                  0, 0, 0, sys::fs::file_type::directory_file, Perms);
    addEntry(Path, S);
  }

  void addSymlink(StringRef Path) {
    vfs::Status S(Path, Path, UniqueID(FSID, FileID++), sys::TimeValue::now(),
                  0, 0, 0, sys::fs::file_type::symlink_file, sys::fs::all_all);
    addEntry(Path, S);
  }
};
} // end anonymous namespace

TEST(VirtualFileSystemTest, StatusQueries) {
  IntrusiveRefCntPtr<DummyFileSystem> D(new DummyFileSystem());
  ErrorOr<vfs::Status> Status((std::error_code()));

  D->addRegularFile("/foo");
  Status = D->status("/foo");
  ASSERT_FALSE(Status.getError());
  EXPECT_TRUE(Status->isStatusKnown());
  EXPECT_FALSE(Status->isDirectory());
  EXPECT_TRUE(Status->isRegularFile());
  EXPECT_FALSE(Status->isSymlink());
  EXPECT_FALSE(Status->isOther());
  EXPECT_TRUE(Status->exists());

  D->addDirectory("/bar");
  Status = D->status("/bar");
  ASSERT_FALSE(Status.getError());
  EXPECT_TRUE(Status->isStatusKnown());
  EXPECT_TRUE(Status->isDirectory());
  EXPECT_FALSE(Status->isRegularFile());
  EXPECT_FALSE(Status->isSymlink());
  EXPECT_FALSE(Status->isOther());
  EXPECT_TRUE(Status->exists());

  D->addSymlink("/baz");
  Status = D->status("/baz");
  ASSERT_FALSE(Status.getError());
  EXPECT_TRUE(Status->isStatusKnown());
  EXPECT_FALSE(Status->isDirectory());
  EXPECT_FALSE(Status->isRegularFile());
  EXPECT_TRUE(Status->isSymlink());
  EXPECT_FALSE(Status->isOther());
  EXPECT_TRUE(Status->exists());

  EXPECT_TRUE(Status->equivalent(*Status));
  ErrorOr<vfs::Status> Status2 = D->status("/foo");
  ASSERT_FALSE(Status2.getError());
  EXPECT_FALSE(Status->equivalent(*Status2));
}

TEST(VirtualFileSystemTest, BaseOnlyOverlay) {
  IntrusiveRefCntPtr<DummyFileSystem> D(new DummyFileSystem());
  ErrorOr<vfs::Status> Status((std::error_code()));
  EXPECT_FALSE(Status = D->status("/foo"));

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(new vfs::OverlayFileSystem(D));
  EXPECT_FALSE(Status = O->status("/foo"));

  D->addRegularFile("/foo");
  Status = D->status("/foo");
  EXPECT_FALSE(Status.getError());

  ErrorOr<vfs::Status> Status2((std::error_code()));
  Status2 = O->status("/foo");
  EXPECT_FALSE(Status2.getError());
  EXPECT_TRUE(Status->equivalent(*Status2));
}

TEST(VirtualFileSystemTest, OverlayFiles) {
  IntrusiveRefCntPtr<DummyFileSystem> Base(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Middle(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Top(new DummyFileSystem());
  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Base));
  O->pushOverlay(Middle);
  O->pushOverlay(Top);

  ErrorOr<vfs::Status> Status1((std::error_code())),
      Status2((std::error_code())), Status3((std::error_code())),
      StatusB((std::error_code())), StatusM((std::error_code())),
      StatusT((std::error_code()));

  Base->addRegularFile("/foo");
  StatusB = Base->status("/foo");
  ASSERT_FALSE(StatusB.getError());
  Status1 = O->status("/foo");
  ASSERT_FALSE(Status1.getError());
  Middle->addRegularFile("/foo");
  StatusM = Middle->status("/foo");
  ASSERT_FALSE(StatusM.getError());
  Status2 = O->status("/foo");
  ASSERT_FALSE(Status2.getError());
  Top->addRegularFile("/foo");
  StatusT = Top->status("/foo");
  ASSERT_FALSE(StatusT.getError());
  Status3 = O->status("/foo");
  ASSERT_FALSE(Status3.getError());

  EXPECT_TRUE(Status1->equivalent(*StatusB));
  EXPECT_TRUE(Status2->equivalent(*StatusM));
  EXPECT_TRUE(Status3->equivalent(*StatusT));

  EXPECT_FALSE(Status1->equivalent(*Status2));
  EXPECT_FALSE(Status2->equivalent(*Status3));
  EXPECT_FALSE(Status1->equivalent(*Status3));
}

TEST(VirtualFileSystemTest, OverlayDirsNonMerged) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Upper);

  Lower->addDirectory("/lower-only");
  Upper->addDirectory("/upper-only");

  // non-merged paths should be the same
  ErrorOr<vfs::Status> Status1 = Lower->status("/lower-only");
  ASSERT_FALSE(Status1.getError());
  ErrorOr<vfs::Status> Status2 = O->status("/lower-only");
  ASSERT_FALSE(Status2.getError());
  EXPECT_TRUE(Status1->equivalent(*Status2));

  Status1 = Upper->status("/upper-only");
  ASSERT_FALSE(Status1.getError());
  Status2 = O->status("/upper-only");
  ASSERT_FALSE(Status2.getError());
  EXPECT_TRUE(Status1->equivalent(*Status2));
}

TEST(VirtualFileSystemTest, MergedDirPermissions) {
  // merged directories get the permissions of the upper dir
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Upper);

  ErrorOr<vfs::Status> Status((std::error_code()));
  Lower->addDirectory("/both", sys::fs::owner_read);
  Upper->addDirectory("/both", sys::fs::owner_all | sys::fs::group_read);
  Status = O->status("/both");
  ASSERT_FALSE(Status.getError());
  EXPECT_EQ(0740, Status->getPermissions());

  // permissions (as usual) are not recursively applied
  Lower->addRegularFile("/both/foo", sys::fs::owner_read);
  Upper->addRegularFile("/both/bar", sys::fs::owner_write);
  Status = O->status("/both/foo");
  ASSERT_FALSE( Status.getError());
  EXPECT_EQ(0400, Status->getPermissions());
  Status = O->status("/both/bar");
  ASSERT_FALSE(Status.getError());
  EXPECT_EQ(0200, Status->getPermissions());
}

namespace {
struct ScopedDir {
  SmallString<128> Path;
  ScopedDir(const Twine &Name, bool Unique=false) {
    std::error_code EC;
    if (Unique) {
      EC =  llvm::sys::fs::createUniqueDirectory(Name, Path);
    } else {
      Path = Name.str();
      EC = llvm::sys::fs::create_directory(Twine(Path));
    }
    if (EC)
      Path = "";
    EXPECT_FALSE(EC);
  }
  ~ScopedDir() {
    if (Path != "")
      EXPECT_FALSE(llvm::sys::fs::remove(Path.str()));
  }
  operator StringRef() { return Path.str(); }
};
}

TEST(VirtualFileSystemTest, BasicRealFSIteration) {
  ScopedDir TestDirectory("virtual-file-system-test", /*Unique*/true);
  IntrusiveRefCntPtr<vfs::FileSystem> FS = vfs::getRealFileSystem();

  std::error_code EC;
  vfs::directory_iterator I = FS->dir_begin(Twine(TestDirectory), EC);
  ASSERT_FALSE(EC);
  EXPECT_EQ(vfs::directory_iterator(), I); // empty directory is empty

  ScopedDir _a(TestDirectory+"/a");
  ScopedDir _ab(TestDirectory+"/a/b");
  ScopedDir _c(TestDirectory+"/c");
  ScopedDir _cd(TestDirectory+"/c/d");

  I = FS->dir_begin(Twine(TestDirectory), EC);
  ASSERT_FALSE(EC);
  ASSERT_NE(vfs::directory_iterator(), I);
  // Check either a or c, since we can't rely on the iteration order.
  EXPECT_TRUE(I->getName().endswith("a") || I->getName().endswith("c"));
  I.increment(EC);
  ASSERT_FALSE(EC);
  ASSERT_NE(vfs::directory_iterator(), I);
  EXPECT_TRUE(I->getName().endswith("a") || I->getName().endswith("c"));
  I.increment(EC);
  EXPECT_EQ(vfs::directory_iterator(), I);
}

TEST(VirtualFileSystemTest, BasicRealFSRecursiveIteration) {
  ScopedDir TestDirectory("virtual-file-system-test", /*Unique*/true);
  IntrusiveRefCntPtr<vfs::FileSystem> FS = vfs::getRealFileSystem();

  std::error_code EC;
  auto I = vfs::recursive_directory_iterator(*FS, Twine(TestDirectory), EC);
  ASSERT_FALSE(EC);
  EXPECT_EQ(vfs::recursive_directory_iterator(), I); // empty directory is empty

  ScopedDir _a(TestDirectory+"/a");
  ScopedDir _ab(TestDirectory+"/a/b");
  ScopedDir _c(TestDirectory+"/c");
  ScopedDir _cd(TestDirectory+"/c/d");

  I = vfs::recursive_directory_iterator(*FS, Twine(TestDirectory), EC);
  ASSERT_FALSE(EC);
  ASSERT_NE(vfs::recursive_directory_iterator(), I);


  std::vector<std::string> Contents;
  for (auto E = vfs::recursive_directory_iterator(); !EC && I != E;
       I.increment(EC)) {
    Contents.push_back(I->getName());
  }

  // Check contents, which may be in any order
  EXPECT_EQ(4U, Contents.size());
  int Counts[4] = { 0, 0, 0, 0 };
  for (const std::string &Name : Contents) {
    ASSERT_FALSE(Name.empty());
    int Index = Name[Name.size()-1] - 'a';
    ASSERT_TRUE(Index >= 0 && Index < 4);
    Counts[Index]++;
  }
  EXPECT_EQ(1, Counts[0]); // a
  EXPECT_EQ(1, Counts[1]); // b
  EXPECT_EQ(1, Counts[2]); // c
  EXPECT_EQ(1, Counts[3]); // d
}

template <typename T, size_t N>
std::vector<StringRef> makeStringRefVector(const T (&Arr)[N]) {
  std::vector<StringRef> Vec;
  for (size_t i = 0; i != N; ++i)
    Vec.push_back(Arr[i]);
  return Vec;
}

template <typename DirIter>
static void checkContents(DirIter I, ArrayRef<StringRef> Expected) {
  std::error_code EC;
  auto ExpectedIter = Expected.begin(), ExpectedEnd = Expected.end();
  for (DirIter E;
       !EC && I != E && ExpectedIter != ExpectedEnd;
       I.increment(EC), ++ExpectedIter)
    EXPECT_EQ(*ExpectedIter, I->getName());

  EXPECT_EQ(ExpectedEnd, ExpectedIter);
  EXPECT_EQ(DirIter(), I);
}

TEST(VirtualFileSystemTest, OverlayIteration) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Upper);

  std::error_code EC;
  checkContents(O->dir_begin("/", EC), ArrayRef<StringRef>());

  Lower->addRegularFile("/file1");
  checkContents(O->dir_begin("/", EC), ArrayRef<StringRef>("/file1"));

  Upper->addRegularFile("/file2");
  {
    const char *Contents[] = {"/file2", "/file1"};
    checkContents(O->dir_begin("/", EC), makeStringRefVector(Contents));
  }

  Lower->addDirectory("/dir1");
  Lower->addRegularFile("/dir1/foo");
  Upper->addDirectory("/dir2");
  Upper->addRegularFile("/dir2/foo");
  checkContents(O->dir_begin("/dir2", EC), ArrayRef<StringRef>("/dir2/foo"));
  {
    const char *Contents[] = {"/dir2", "/file2", "/dir1", "/file1"};
    checkContents(O->dir_begin("/", EC), makeStringRefVector(Contents));
  }
}

TEST(VirtualFileSystemTest, OverlayRecursiveIteration) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Middle(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Middle);
  O->pushOverlay(Upper);

  std::error_code EC;
  checkContents(vfs::recursive_directory_iterator(*O, "/", EC),
                ArrayRef<StringRef>());

  Lower->addRegularFile("/file1");
  checkContents(vfs::recursive_directory_iterator(*O, "/", EC),
                ArrayRef<StringRef>("/file1"));

  Upper->addDirectory("/dir");
  Upper->addRegularFile("/dir/file2");
  {
    const char *Contents[] = {"/dir", "/dir/file2", "/file1"};
    checkContents(vfs::recursive_directory_iterator(*O, "/", EC),
                  makeStringRefVector(Contents));
  }

  Lower->addDirectory("/dir1");
  Lower->addRegularFile("/dir1/foo");
  Lower->addDirectory("/dir1/a");
  Lower->addRegularFile("/dir1/a/b");
  Middle->addDirectory("/a");
  Middle->addDirectory("/a/b");
  Middle->addDirectory("/a/b/c");
  Middle->addRegularFile("/a/b/c/d");
  Middle->addRegularFile("/hiddenByUp");
  Upper->addDirectory("/dir2");
  Upper->addRegularFile("/dir2/foo");
  Upper->addRegularFile("/hiddenByUp");
  checkContents(vfs::recursive_directory_iterator(*O, "/dir2", EC),
                ArrayRef<StringRef>("/dir2/foo"));
  {
    const char *Contents[] = { "/dir", "/dir/file2", "/dir2", "/dir2/foo",
        "/hiddenByUp", "/a", "/a/b", "/a/b/c", "/a/b/c/d", "/dir1", "/dir1/a",
        "/dir1/a/b", "/dir1/foo", "/file1" };
    checkContents(vfs::recursive_directory_iterator(*O, "/", EC),
                  makeStringRefVector(Contents));
  }
}

TEST(VirtualFileSystemTest, ThreeLevelIteration) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Middle(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Middle);
  O->pushOverlay(Upper);

  std::error_code EC;
  checkContents(O->dir_begin("/", EC), ArrayRef<StringRef>());

  Middle->addRegularFile("/file2");
  checkContents(O->dir_begin("/", EC), ArrayRef<StringRef>("/file2"));

  Lower->addRegularFile("/file1");
  Upper->addRegularFile("/file3");
  {
    const char *Contents[] = {"/file3", "/file2", "/file1"};
    checkContents(O->dir_begin("/", EC), makeStringRefVector(Contents));
  }
}

TEST(VirtualFileSystemTest, HiddenInIteration) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Middle(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Middle);
  O->pushOverlay(Upper);

  std::error_code EC;
  Lower->addRegularFile("/onlyInLow", sys::fs::owner_read);
  Lower->addRegularFile("/hiddenByMid", sys::fs::owner_read);
  Lower->addRegularFile("/hiddenByUp", sys::fs::owner_read);
  Middle->addRegularFile("/onlyInMid", sys::fs::owner_write);
  Middle->addRegularFile("/hiddenByMid", sys::fs::owner_write);
  Middle->addRegularFile("/hiddenByUp", sys::fs::owner_write);
  Upper->addRegularFile("/onlyInUp", sys::fs::owner_all);
  Upper->addRegularFile("/hiddenByUp", sys::fs::owner_all);
  {
    const char *Contents[] = {"/hiddenByUp", "/onlyInUp", "/hiddenByMid",
                              "/onlyInMid", "/onlyInLow"};
    checkContents(O->dir_begin("/", EC), makeStringRefVector(Contents));
  }

  // Make sure we get the top-most entry
  {
    std::error_code EC;
    vfs::directory_iterator I = O->dir_begin("/", EC), E;
    for ( ; !EC && I != E; I.increment(EC))
      if (I->getName() == "/hiddenByUp")
        break;
    ASSERT_NE(E, I);
    EXPECT_EQ(sys::fs::owner_all, I->getPermissions());
  }
  {
    std::error_code EC;
    vfs::directory_iterator I = O->dir_begin("/", EC), E;
    for ( ; !EC && I != E; I.increment(EC))
      if (I->getName() == "/hiddenByMid")
        break;
    ASSERT_NE(E, I);
    EXPECT_EQ(sys::fs::owner_write, I->getPermissions());
  }
}

// NOTE: in the tests below, we use '//root/' as our root directory, since it is
// a legal *absolute* path on Windows as well as *nix.
class VFSFromYAMLTest : public ::testing::Test {
public:
  int NumDiagnostics;

  void SetUp() {
    NumDiagnostics = 0;
  }

  static void CountingDiagHandler(const SMDiagnostic &, void *Context) {
    VFSFromYAMLTest *Test = static_cast<VFSFromYAMLTest *>(Context);
    ++Test->NumDiagnostics;
  }

  IntrusiveRefCntPtr<vfs::FileSystem>
  getFromYAMLRawString(StringRef Content,
                       IntrusiveRefCntPtr<vfs::FileSystem> ExternalFS) {
    MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(Content);
    return getVFSFromYAML(Buffer, CountingDiagHandler, this, ExternalFS);
  }

  IntrusiveRefCntPtr<vfs::FileSystem> getFromYAMLString(
      StringRef Content,
      IntrusiveRefCntPtr<vfs::FileSystem> ExternalFS = new DummyFileSystem()) {
    std::string VersionPlusContent("{\n  'version':0,\n");
    VersionPlusContent += Content.slice(Content.find('{') + 1, StringRef::npos);
    return getFromYAMLRawString(VersionPlusContent, ExternalFS);
  }
};

TEST_F(VFSFromYAMLTest, BasicVFSFromYAML) {
  IntrusiveRefCntPtr<vfs::FileSystem> FS;
  FS = getFromYAMLString("");
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString("[]");
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString("'string'");
  EXPECT_EQ(nullptr, FS.get());
  EXPECT_EQ(3, NumDiagnostics);
}

TEST_F(VFSFromYAMLTest, MappedFiles) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("//root/foo/bar/a");
  IntrusiveRefCntPtr<vfs::FileSystem> FS =
      getFromYAMLString("{ 'roots': [\n"
                        "{\n"
                        "  'type': 'directory',\n"
                        "  'name': '//root/',\n"
                        "  'contents': [ {\n"
                        "                  'type': 'file',\n"
                        "                  'name': 'file1',\n"
                        "                  'external-contents': '//root/foo/bar/a'\n"
                        "                },\n"
                        "                {\n"
                        "                  'type': 'file',\n"
                        "                  'name': 'file2',\n"
                        "                  'external-contents': '//root/foo/b'\n"
                        "                }\n"
                        "              ]\n"
                        "}\n"
                        "]\n"
                        "}",
                        Lower);
  ASSERT_TRUE(FS.get() != nullptr);

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(FS);

  // file
  ErrorOr<vfs::Status> S = O->status("//root/file1");
  ASSERT_FALSE(S.getError());
  EXPECT_EQ("//root/foo/bar/a", S->getName());

  ErrorOr<vfs::Status> SLower = O->status("//root/foo/bar/a");
  EXPECT_EQ("//root/foo/bar/a", SLower->getName());
  EXPECT_TRUE(S->equivalent(*SLower));

  // directory
  S = O->status("//root/");
  ASSERT_FALSE(S.getError());
  EXPECT_TRUE(S->isDirectory());
  EXPECT_TRUE(S->equivalent(*O->status("//root/"))); // non-volatile UniqueID

  // broken mapping
  EXPECT_EQ(O->status("//root/file2").getError(),
            llvm::errc::no_such_file_or_directory);
  EXPECT_EQ(0, NumDiagnostics);
}

TEST_F(VFSFromYAMLTest, CaseInsensitive) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("//root/foo/bar/a");
  IntrusiveRefCntPtr<vfs::FileSystem> FS =
      getFromYAMLString("{ 'case-sensitive': 'false',\n"
                        "  'roots': [\n"
                        "{\n"
                        "  'type': 'directory',\n"
                        "  'name': '//root/',\n"
                        "  'contents': [ {\n"
                        "                  'type': 'file',\n"
                        "                  'name': 'XX',\n"
                        "                  'external-contents': '//root/foo/bar/a'\n"
                        "                }\n"
                        "              ]\n"
                        "}]}",
                        Lower);
  ASSERT_TRUE(FS.get() != nullptr);

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(FS);

  ErrorOr<vfs::Status> S = O->status("//root/XX");
  ASSERT_FALSE(S.getError());

  ErrorOr<vfs::Status> SS = O->status("//root/xx");
  ASSERT_FALSE(SS.getError());
  EXPECT_TRUE(S->equivalent(*SS));
  SS = O->status("//root/xX");
  EXPECT_TRUE(S->equivalent(*SS));
  SS = O->status("//root/Xx");
  EXPECT_TRUE(S->equivalent(*SS));
  EXPECT_EQ(0, NumDiagnostics);
}

TEST_F(VFSFromYAMLTest, CaseSensitive) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("//root/foo/bar/a");
  IntrusiveRefCntPtr<vfs::FileSystem> FS =
      getFromYAMLString("{ 'case-sensitive': 'true',\n"
                        "  'roots': [\n"
                        "{\n"
                        "  'type': 'directory',\n"
                        "  'name': '//root/',\n"
                        "  'contents': [ {\n"
                        "                  'type': 'file',\n"
                        "                  'name': 'XX',\n"
                        "                  'external-contents': '//root/foo/bar/a'\n"
                        "                }\n"
                        "              ]\n"
                        "}]}",
                        Lower);
  ASSERT_TRUE(FS.get() != nullptr);

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(FS);

  ErrorOr<vfs::Status> SS = O->status("//root/xx");
  EXPECT_EQ(SS.getError(), llvm::errc::no_such_file_or_directory);
  SS = O->status("//root/xX");
  EXPECT_EQ(SS.getError(), llvm::errc::no_such_file_or_directory);
  SS = O->status("//root/Xx");
  EXPECT_EQ(SS.getError(), llvm::errc::no_such_file_or_directory);
  EXPECT_EQ(0, NumDiagnostics);
}

TEST_F(VFSFromYAMLTest, IllegalVFSFile) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());

  // invalid YAML at top-level
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString("{]", Lower);
  EXPECT_EQ(nullptr, FS.get());
  // invalid YAML in roots
  FS = getFromYAMLString("{ 'roots':[}", Lower);
  // invalid YAML in directory
  FS = getFromYAMLString(
      "{ 'roots':[ { 'name': 'foo', 'type': 'directory', 'contents': [}",
      Lower);
  EXPECT_EQ(nullptr, FS.get());

  // invalid configuration
  FS = getFromYAMLString("{ 'knobular': 'true', 'roots':[] }", Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString("{ 'case-sensitive': 'maybe', 'roots':[] }", Lower);
  EXPECT_EQ(nullptr, FS.get());

  // invalid roots
  FS = getFromYAMLString("{ 'roots':'' }", Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString("{ 'roots':{} }", Lower);
  EXPECT_EQ(nullptr, FS.get());

  // invalid entries
  FS = getFromYAMLString(
      "{ 'roots':[ { 'type': 'other', 'name': 'me', 'contents': '' }", Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString("{ 'roots':[ { 'type': 'file', 'name': [], "
                         "'external-contents': 'other' }",
                         Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString(
      "{ 'roots':[ { 'type': 'file', 'name': 'me', 'external-contents': [] }",
      Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString(
      "{ 'roots':[ { 'type': 'file', 'name': 'me', 'external-contents': {} }",
      Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString(
      "{ 'roots':[ { 'type': 'directory', 'name': 'me', 'contents': {} }",
      Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString(
      "{ 'roots':[ { 'type': 'directory', 'name': 'me', 'contents': '' }",
      Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString(
      "{ 'roots':[ { 'thingy': 'directory', 'name': 'me', 'contents': [] }",
      Lower);
  EXPECT_EQ(nullptr, FS.get());

  // missing mandatory fields
  FS = getFromYAMLString("{ 'roots':[ { 'type': 'file', 'name': 'me' }", Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString(
      "{ 'roots':[ { 'type': 'file', 'external-contents': 'other' }", Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString("{ 'roots':[ { 'name': 'me', 'contents': [] }", Lower);
  EXPECT_EQ(nullptr, FS.get());

  // duplicate keys
  FS = getFromYAMLString("{ 'roots':[], 'roots':[] }", Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString(
      "{ 'case-sensitive':'true', 'case-sensitive':'true', 'roots':[] }",
      Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS =
      getFromYAMLString("{ 'roots':[{'name':'me', 'name':'you', 'type':'file', "
                        "'external-contents':'blah' } ] }",
                        Lower);
  EXPECT_EQ(nullptr, FS.get());

  // missing version
  FS = getFromYAMLRawString("{ 'roots':[] }", Lower);
  EXPECT_EQ(nullptr, FS.get());

  // bad version number
  FS = getFromYAMLRawString("{ 'version':'foo', 'roots':[] }", Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLRawString("{ 'version':-1, 'roots':[] }", Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLRawString("{ 'version':100000, 'roots':[] }", Lower);
  EXPECT_EQ(nullptr, FS.get());
  EXPECT_EQ(24, NumDiagnostics);
}

TEST_F(VFSFromYAMLTest, UseExternalName) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("//root/external/file");

  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'roots': [\n"
      "  { 'type': 'file', 'name': '//root/A',\n"
      "    'external-contents': '//root/external/file'\n"
      "  },\n"
      "  { 'type': 'file', 'name': '//root/B',\n"
      "    'use-external-name': true,\n"
      "    'external-contents': '//root/external/file'\n"
      "  },\n"
      "  { 'type': 'file', 'name': '//root/C',\n"
      "    'use-external-name': false,\n"
      "    'external-contents': '//root/external/file'\n"
      "  }\n"
      "] }", Lower);
  ASSERT_TRUE(nullptr != FS.get());

  // default true
  EXPECT_EQ("//root/external/file", FS->status("//root/A")->getName());
  // explicit
  EXPECT_EQ("//root/external/file", FS->status("//root/B")->getName());
  EXPECT_EQ("//root/C", FS->status("//root/C")->getName());

  // global configuration
  FS = getFromYAMLString(
      "{ 'use-external-names': false,\n"
      "  'roots': [\n"
      "  { 'type': 'file', 'name': '//root/A',\n"
      "    'external-contents': '//root/external/file'\n"
      "  },\n"
      "  { 'type': 'file', 'name': '//root/B',\n"
      "    'use-external-name': true,\n"
      "    'external-contents': '//root/external/file'\n"
      "  },\n"
      "  { 'type': 'file', 'name': '//root/C',\n"
      "    'use-external-name': false,\n"
      "    'external-contents': '//root/external/file'\n"
      "  }\n"
      "] }", Lower);
  ASSERT_TRUE(nullptr != FS.get());

  // default
  EXPECT_EQ("//root/A", FS->status("//root/A")->getName());
  // explicit
  EXPECT_EQ("//root/external/file", FS->status("//root/B")->getName());
  EXPECT_EQ("//root/C", FS->status("//root/C")->getName());
}

TEST_F(VFSFromYAMLTest, MultiComponentPath) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("//root/other");

  // file in roots
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'roots': [\n"
      "  { 'type': 'file', 'name': '//root/path/to/file',\n"
      "    'external-contents': '//root/other' }]\n"
      "}", Lower);
  ASSERT_TRUE(nullptr != FS.get());
  EXPECT_FALSE(FS->status("//root/path/to/file").getError());
  EXPECT_FALSE(FS->status("//root/path/to").getError());
  EXPECT_FALSE(FS->status("//root/path").getError());
  EXPECT_FALSE(FS->status("//root/").getError());

  // at the start
  FS = getFromYAMLString(
      "{ 'roots': [\n"
      "  { 'type': 'directory', 'name': '//root/path/to',\n"
      "    'contents': [ { 'type': 'file', 'name': 'file',\n"
      "                    'external-contents': '//root/other' }]}]\n"
      "}", Lower);
  ASSERT_TRUE(nullptr != FS.get());
  EXPECT_FALSE(FS->status("//root/path/to/file").getError());
  EXPECT_FALSE(FS->status("//root/path/to").getError());
  EXPECT_FALSE(FS->status("//root/path").getError());
  EXPECT_FALSE(FS->status("//root/").getError());

  // at the end
  FS = getFromYAMLString(
      "{ 'roots': [\n"
      "  { 'type': 'directory', 'name': '//root/',\n"
      "    'contents': [ { 'type': 'file', 'name': 'path/to/file',\n"
      "                    'external-contents': '//root/other' }]}]\n"
      "}", Lower);
  ASSERT_TRUE(nullptr != FS.get());
  EXPECT_FALSE(FS->status("//root/path/to/file").getError());
  EXPECT_FALSE(FS->status("//root/path/to").getError());
  EXPECT_FALSE(FS->status("//root/path").getError());
  EXPECT_FALSE(FS->status("//root/").getError());
}

TEST_F(VFSFromYAMLTest, TrailingSlashes) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("//root/other");

  // file in roots
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'roots': [\n"
      "  { 'type': 'directory', 'name': '//root/path/to////',\n"
      "    'contents': [ { 'type': 'file', 'name': 'file',\n"
      "                    'external-contents': '//root/other' }]}]\n"
      "}", Lower);
  ASSERT_TRUE(nullptr != FS.get());
  EXPECT_FALSE(FS->status("//root/path/to/file").getError());
  EXPECT_FALSE(FS->status("//root/path/to").getError());
  EXPECT_FALSE(FS->status("//root/path").getError());
  EXPECT_FALSE(FS->status("//root/").getError());
}

TEST_F(VFSFromYAMLTest, DirectoryIteration) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addDirectory("//root/");
  Lower->addDirectory("//root/foo");
  Lower->addDirectory("//root/foo/bar");
  Lower->addRegularFile("//root/foo/bar/a");
  Lower->addRegularFile("//root/foo/bar/b");
  Lower->addRegularFile("//root/file3");
  IntrusiveRefCntPtr<vfs::FileSystem> FS =
  getFromYAMLString("{ 'use-external-names': false,\n"
                    "  'roots': [\n"
                    "{\n"
                    "  'type': 'directory',\n"
                    "  'name': '//root/',\n"
                    "  'contents': [ {\n"
                    "                  'type': 'file',\n"
                    "                  'name': 'file1',\n"
                    "                  'external-contents': '//root/foo/bar/a'\n"
                    "                },\n"
                    "                {\n"
                    "                  'type': 'file',\n"
                    "                  'name': 'file2',\n"
                    "                  'external-contents': '//root/foo/bar/b'\n"
                    "                }\n"
                    "              ]\n"
                    "}\n"
                    "]\n"
                    "}",
                    Lower);
  ASSERT_TRUE(FS.get() != NULL);

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(FS);

  std::error_code EC;
  {
    const char *Contents[] = {"//root/file1", "//root/file2", "//root/file3",
                              "//root/foo"};
    checkContents(O->dir_begin("//root/", EC), makeStringRefVector(Contents));
  }

  {
    const char *Contents[] = {"//root/foo/bar/a", "//root/foo/bar/b"};
    checkContents(O->dir_begin("//root/foo/bar", EC),
                  makeStringRefVector(Contents));
  }
}
@


1.1.1.1.4.1
log
@file VirtualFileSystemTest.cpp was added on branch yamt-pagecache on 2014-05-22 16:19:48 +0000
@
text
@d1 579
@


1.1.1.1.4.2
log
@sync with head.

for a reference, the tree before this commit was tagged
as yamt-pagecache-tag8.

this commit was splitted into small chunks to avoid
a limitation of cvs.  ("Protocol error: too many arguments")
@
text
@a0 579
//===- unittests/Basic/VirtualFileSystem.cpp ---------------- VFS tests ---===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/Basic/VirtualFileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SourceMgr.h"
#include "gtest/gtest.h"
#include <map>
using namespace clang;
using namespace llvm;
using llvm::sys::fs::UniqueID;

namespace {
class DummyFileSystem : public vfs::FileSystem {
  int FSID;   // used to produce UniqueIDs
  int FileID; // used to produce UniqueIDs
  std::map<std::string, vfs::Status> FilesAndDirs;

  static int getNextFSID() {
    static int Count = 0;
    return Count++;
  }

public:
  DummyFileSystem() : FSID(getNextFSID()), FileID(0) {}

  ErrorOr<vfs::Status> status(const Twine &Path) {
    std::map<std::string, vfs::Status>::iterator I =
        FilesAndDirs.find(Path.str());
    if (I == FilesAndDirs.end())
      return error_code(errc::no_such_file_or_directory, posix_category());
    return I->second;
  }
  error_code openFileForRead(const Twine &Path, OwningPtr<vfs::File> &Result) {
    llvm_unreachable("unimplemented");
  }
  error_code getBufferForFile(const Twine &Name,
                              OwningPtr<MemoryBuffer> &Result,
                              int64_t FileSize = -1,
                              bool RequiresNullTerminator = true) {
    llvm_unreachable("unimplemented");
  }

  void addEntry(StringRef Path, const vfs::Status &Status) {
    FilesAndDirs[Path] = Status;
  }

  void addRegularFile(StringRef Path, sys::fs::perms Perms = sys::fs::all_all) {
    vfs::Status S(Path, Path, UniqueID(FSID, FileID++), sys::TimeValue::now(),
                  0, 0, 1024, sys::fs::file_type::regular_file, Perms);
    addEntry(Path, S);
  }

  void addDirectory(StringRef Path, sys::fs::perms Perms = sys::fs::all_all) {
    vfs::Status S(Path, Path, UniqueID(FSID, FileID++), sys::TimeValue::now(),
                  0, 0, 0, sys::fs::file_type::directory_file, Perms);
    addEntry(Path, S);
  }

  void addSymlink(StringRef Path) {
    vfs::Status S(Path, Path, UniqueID(FSID, FileID++), sys::TimeValue::now(),
                  0, 0, 0, sys::fs::file_type::symlink_file, sys::fs::all_all);
    addEntry(Path, S);
  }
};
} // end anonymous namespace

TEST(VirtualFileSystemTest, StatusQueries) {
  IntrusiveRefCntPtr<DummyFileSystem> D(new DummyFileSystem());
  ErrorOr<vfs::Status> Status((error_code()));

  D->addRegularFile("/foo");
  Status = D->status("/foo");
  ASSERT_EQ(errc::success, Status.getError());
  EXPECT_TRUE(Status->isStatusKnown());
  EXPECT_FALSE(Status->isDirectory());
  EXPECT_TRUE(Status->isRegularFile());
  EXPECT_FALSE(Status->isSymlink());
  EXPECT_FALSE(Status->isOther());
  EXPECT_TRUE(Status->exists());

  D->addDirectory("/bar");
  Status = D->status("/bar");
  ASSERT_EQ(errc::success, Status.getError());
  EXPECT_TRUE(Status->isStatusKnown());
  EXPECT_TRUE(Status->isDirectory());
  EXPECT_FALSE(Status->isRegularFile());
  EXPECT_FALSE(Status->isSymlink());
  EXPECT_FALSE(Status->isOther());
  EXPECT_TRUE(Status->exists());

  D->addSymlink("/baz");
  Status = D->status("/baz");
  ASSERT_EQ(errc::success, Status.getError());
  EXPECT_TRUE(Status->isStatusKnown());
  EXPECT_FALSE(Status->isDirectory());
  EXPECT_FALSE(Status->isRegularFile());
  EXPECT_TRUE(Status->isSymlink());
  EXPECT_FALSE(Status->isOther());
  EXPECT_TRUE(Status->exists());

  EXPECT_TRUE(Status->equivalent(*Status));
  ErrorOr<vfs::Status> Status2 = D->status("/foo");
  ASSERT_EQ(errc::success, Status2.getError());
  EXPECT_FALSE(Status->equivalent(*Status2));
}

TEST(VirtualFileSystemTest, BaseOnlyOverlay) {
  IntrusiveRefCntPtr<DummyFileSystem> D(new DummyFileSystem());
  ErrorOr<vfs::Status> Status((error_code()));
  EXPECT_FALSE(Status = D->status("/foo"));

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(new vfs::OverlayFileSystem(D));
  EXPECT_FALSE(Status = O->status("/foo"));

  D->addRegularFile("/foo");
  Status = D->status("/foo");
  EXPECT_EQ(errc::success, Status.getError());

  ErrorOr<vfs::Status> Status2((error_code()));
  Status2 = O->status("/foo");
  EXPECT_EQ(errc::success, Status2.getError());
  EXPECT_TRUE(Status->equivalent(*Status2));
}

TEST(VirtualFileSystemTest, OverlayFiles) {
  IntrusiveRefCntPtr<DummyFileSystem> Base(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Middle(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Top(new DummyFileSystem());
  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Base));
  O->pushOverlay(Middle);
  O->pushOverlay(Top);

  ErrorOr<vfs::Status> Status1((error_code())), Status2((error_code())),
      Status3((error_code())), StatusB((error_code())), StatusM((error_code())),
      StatusT((error_code()));

  Base->addRegularFile("/foo");
  StatusB = Base->status("/foo");
  ASSERT_EQ(errc::success, StatusB.getError());
  Status1 = O->status("/foo");
  ASSERT_EQ(errc::success, Status1.getError());
  Middle->addRegularFile("/foo");
  StatusM = Middle->status("/foo");
  ASSERT_EQ(errc::success, StatusM.getError());
  Status2 = O->status("/foo");
  ASSERT_EQ(errc::success, Status2.getError());
  Top->addRegularFile("/foo");
  StatusT = Top->status("/foo");
  ASSERT_EQ(errc::success, StatusT.getError());
  Status3 = O->status("/foo");
  ASSERT_EQ(errc::success, Status3.getError());

  EXPECT_TRUE(Status1->equivalent(*StatusB));
  EXPECT_TRUE(Status2->equivalent(*StatusM));
  EXPECT_TRUE(Status3->equivalent(*StatusT));

  EXPECT_FALSE(Status1->equivalent(*Status2));
  EXPECT_FALSE(Status2->equivalent(*Status3));
  EXPECT_FALSE(Status1->equivalent(*Status3));
}

TEST(VirtualFileSystemTest, OverlayDirsNonMerged) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Upper);

  Lower->addDirectory("/lower-only");
  Upper->addDirectory("/upper-only");

  // non-merged paths should be the same
  ErrorOr<vfs::Status> Status1 = Lower->status("/lower-only");
  ASSERT_EQ(errc::success, Status1.getError());
  ErrorOr<vfs::Status> Status2 = O->status("/lower-only");
  ASSERT_EQ(errc::success, Status2.getError());
  EXPECT_TRUE(Status1->equivalent(*Status2));

  Status1 = Upper->status("/upper-only");
  ASSERT_EQ(errc::success, Status1.getError());
  Status2 = O->status("/upper-only");
  ASSERT_EQ(errc::success, Status2.getError());
  EXPECT_TRUE(Status1->equivalent(*Status2));
}

TEST(VirtualFileSystemTest, MergedDirPermissions) {
  // merged directories get the permissions of the upper dir
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Upper);

  ErrorOr<vfs::Status> Status((error_code()));
  Lower->addDirectory("/both", sys::fs::owner_read);
  Upper->addDirectory("/both", sys::fs::owner_all | sys::fs::group_read);
  Status = O->status("/both");
  ASSERT_EQ(errc::success, Status.getError());
  EXPECT_EQ(0740, Status->getPermissions());

  // permissions (as usual) are not recursively applied
  Lower->addRegularFile("/both/foo", sys::fs::owner_read);
  Upper->addRegularFile("/both/bar", sys::fs::owner_write);
  Status = O->status("/both/foo");
  ASSERT_EQ(errc::success, Status.getError());
  EXPECT_EQ(0400, Status->getPermissions());
  Status = O->status("/both/bar");
  ASSERT_EQ(errc::success, Status.getError());
  EXPECT_EQ(0200, Status->getPermissions());
}

class VFSFromYAMLTest : public ::testing::Test {
public:
  int NumDiagnostics;
  void SetUp() {
    NumDiagnostics = 0;
  }

  static void CountingDiagHandler(const SMDiagnostic &, void *Context) {
    VFSFromYAMLTest *Test = static_cast<VFSFromYAMLTest *>(Context);
    ++Test->NumDiagnostics;
  }

  IntrusiveRefCntPtr<vfs::FileSystem>
  getFromYAMLRawString(StringRef Content,
                       IntrusiveRefCntPtr<vfs::FileSystem> ExternalFS) {
    MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(Content);
    return getVFSFromYAML(Buffer, CountingDiagHandler, this, ExternalFS);
  }

  IntrusiveRefCntPtr<vfs::FileSystem> getFromYAMLString(
      StringRef Content,
      IntrusiveRefCntPtr<vfs::FileSystem> ExternalFS = new DummyFileSystem()) {
    std::string VersionPlusContent("{\n  'version':0,\n");
    VersionPlusContent += Content.slice(Content.find('{') + 1, StringRef::npos);
    return getFromYAMLRawString(VersionPlusContent, ExternalFS);
  }

};

TEST_F(VFSFromYAMLTest, BasicVFSFromYAML) {
  IntrusiveRefCntPtr<vfs::FileSystem> FS;
  FS = getFromYAMLString("");
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString("[]");
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString("'string'");
  EXPECT_EQ(NULL, FS.getPtr());
  EXPECT_EQ(3, NumDiagnostics);
}

TEST_F(VFSFromYAMLTest, MappedFiles) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("/foo/bar/a");
  IntrusiveRefCntPtr<vfs::FileSystem> FS =
      getFromYAMLString("{ 'roots': [\n"
                        "{\n"
                        "  'type': 'directory',\n"
                        "  'name': '/',\n"
                        "  'contents': [ {\n"
                        "                  'type': 'file',\n"
                        "                  'name': 'file1',\n"
                        "                  'external-contents': '/foo/bar/a'\n"
                        "                },\n"
                        "                {\n"
                        "                  'type': 'file',\n"
                        "                  'name': 'file2',\n"
                        "                  'external-contents': '/foo/b'\n"
                        "                }\n"
                        "              ]\n"
                        "}\n"
                        "]\n"
                        "}",
                        Lower);
  ASSERT_TRUE(FS.getPtr() != NULL);

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(FS);

  // file
  ErrorOr<vfs::Status> S = O->status("/file1");
  ASSERT_EQ(errc::success, S.getError());
  EXPECT_EQ("/foo/bar/a", S->getName());

  ErrorOr<vfs::Status> SLower = O->status("/foo/bar/a");
  EXPECT_EQ("/foo/bar/a", SLower->getName());
  EXPECT_TRUE(S->equivalent(*SLower));

  // directory
  S = O->status("/");
  ASSERT_EQ(errc::success, S.getError());
  EXPECT_TRUE(S->isDirectory());
  EXPECT_TRUE(S->equivalent(*O->status("/"))); // non-volatile UniqueID

  // broken mapping
  EXPECT_EQ(errc::no_such_file_or_directory, O->status("/file2").getError());
  EXPECT_EQ(0, NumDiagnostics);
}

TEST_F(VFSFromYAMLTest, CaseInsensitive) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("/foo/bar/a");
  IntrusiveRefCntPtr<vfs::FileSystem> FS =
      getFromYAMLString("{ 'case-sensitive': 'false',\n"
                        "  'roots': [\n"
                        "{\n"
                        "  'type': 'directory',\n"
                        "  'name': '/',\n"
                        "  'contents': [ {\n"
                        "                  'type': 'file',\n"
                        "                  'name': 'XX',\n"
                        "                  'external-contents': '/foo/bar/a'\n"
                        "                }\n"
                        "              ]\n"
                        "}]}",
                        Lower);
  ASSERT_TRUE(FS.getPtr() != NULL);

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(FS);

  ErrorOr<vfs::Status> S = O->status("/XX");
  ASSERT_EQ(errc::success, S.getError());

  ErrorOr<vfs::Status> SS = O->status("/xx");
  ASSERT_EQ(errc::success, SS.getError());
  EXPECT_TRUE(S->equivalent(*SS));
  SS = O->status("/xX");
  EXPECT_TRUE(S->equivalent(*SS));
  SS = O->status("/Xx");
  EXPECT_TRUE(S->equivalent(*SS));
  EXPECT_EQ(0, NumDiagnostics);
}

TEST_F(VFSFromYAMLTest, CaseSensitive) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("/foo/bar/a");
  IntrusiveRefCntPtr<vfs::FileSystem> FS =
      getFromYAMLString("{ 'case-sensitive': 'true',\n"
                        "  'roots': [\n"
                        "{\n"
                        "  'type': 'directory',\n"
                        "  'name': '/',\n"
                        "  'contents': [ {\n"
                        "                  'type': 'file',\n"
                        "                  'name': 'XX',\n"
                        "                  'external-contents': '/foo/bar/a'\n"
                        "                }\n"
                        "              ]\n"
                        "}]}",
                        Lower);
  ASSERT_TRUE(FS.getPtr() != NULL);

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(FS);

  ErrorOr<vfs::Status> SS = O->status("/xx");
  EXPECT_EQ(errc::no_such_file_or_directory, SS.getError());
  SS = O->status("/xX");
  EXPECT_EQ(errc::no_such_file_or_directory, SS.getError());
  SS = O->status("/Xx");
  EXPECT_EQ(errc::no_such_file_or_directory, SS.getError());
  EXPECT_EQ(0, NumDiagnostics);
}

TEST_F(VFSFromYAMLTest, IllegalVFSFile) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());

  // invalid YAML at top-level
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString("{]", Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  // invalid YAML in roots
  FS = getFromYAMLString("{ 'roots':[}", Lower);
  // invalid YAML in directory
  FS = getFromYAMLString(
      "{ 'roots':[ { 'name': 'foo', 'type': 'directory', 'contents': [}",
      Lower);
  EXPECT_EQ(NULL, FS.getPtr());

  // invalid configuration
  FS = getFromYAMLString("{ 'knobular': 'true', 'roots':[] }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString("{ 'case-sensitive': 'maybe', 'roots':[] }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());

  // invalid roots
  FS = getFromYAMLString("{ 'roots':'' }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString("{ 'roots':{} }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());

  // invalid entries
  FS = getFromYAMLString(
      "{ 'roots':[ { 'type': 'other', 'name': 'me', 'contents': '' }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString("{ 'roots':[ { 'type': 'file', 'name': [], "
                         "'external-contents': 'other' }",
                         Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString(
      "{ 'roots':[ { 'type': 'file', 'name': 'me', 'external-contents': [] }",
      Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString(
      "{ 'roots':[ { 'type': 'file', 'name': 'me', 'external-contents': {} }",
      Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString(
      "{ 'roots':[ { 'type': 'directory', 'name': 'me', 'contents': {} }",
      Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString(
      "{ 'roots':[ { 'type': 'directory', 'name': 'me', 'contents': '' }",
      Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString(
      "{ 'roots':[ { 'thingy': 'directory', 'name': 'me', 'contents': [] }",
      Lower);
  EXPECT_EQ(NULL, FS.getPtr());

  // missing mandatory fields
  FS = getFromYAMLString("{ 'roots':[ { 'type': 'file', 'name': 'me' }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString(
      "{ 'roots':[ { 'type': 'file', 'external-contents': 'other' }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString("{ 'roots':[ { 'name': 'me', 'contents': [] }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());

  // duplicate keys
  FS = getFromYAMLString("{ 'roots':[], 'roots':[] }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLString(
      "{ 'case-sensitive':'true', 'case-sensitive':'true', 'roots':[] }",
      Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS =
      getFromYAMLString("{ 'roots':[{'name':'me', 'name':'you', 'type':'file', "
                        "'external-contents':'blah' } ] }",
                        Lower);
  EXPECT_EQ(NULL, FS.getPtr());

  // missing version
  FS = getFromYAMLRawString("{ 'roots':[] }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());

  // bad version number
  FS = getFromYAMLRawString("{ 'version':'foo', 'roots':[] }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLRawString("{ 'version':-1, 'roots':[] }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  FS = getFromYAMLRawString("{ 'version':100000, 'roots':[] }", Lower);
  EXPECT_EQ(NULL, FS.getPtr());
  EXPECT_EQ(24, NumDiagnostics);
}

TEST_F(VFSFromYAMLTest, UseExternalName) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("/external/file");

  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'roots': [\n"
      "  { 'type': 'file', 'name': '/A',\n"
      "    'external-contents': '/external/file'\n"
      "  },\n"
      "  { 'type': 'file', 'name': '/B',\n"
      "    'use-external-name': true,\n"
      "    'external-contents': '/external/file'\n"
      "  },\n"
      "  { 'type': 'file', 'name': '/C',\n"
      "    'use-external-name': false,\n"
      "    'external-contents': '/external/file'\n"
      "  }\n"
      "] }", Lower);
  ASSERT_TRUE(NULL != FS.getPtr());

  // default true
  EXPECT_EQ("/external/file", FS->status("/A")->getName());
  // explicit
  EXPECT_EQ("/external/file", FS->status("/B")->getName());
  EXPECT_EQ("/C", FS->status("/C")->getName());

  // global configuration
  FS = getFromYAMLString(
      "{ 'use-external-names': false,\n"
      "  'roots': [\n"
      "  { 'type': 'file', 'name': '/A',\n"
      "    'external-contents': '/external/file'\n"
      "  },\n"
      "  { 'type': 'file', 'name': '/B',\n"
      "    'use-external-name': true,\n"
      "    'external-contents': '/external/file'\n"
      "  },\n"
      "  { 'type': 'file', 'name': '/C',\n"
      "    'use-external-name': false,\n"
      "    'external-contents': '/external/file'\n"
      "  }\n"
      "] }", Lower);
  ASSERT_TRUE(NULL != FS.getPtr());

  // default
  EXPECT_EQ("/A", FS->status("/A")->getName());
  // explicit
  EXPECT_EQ("/external/file", FS->status("/B")->getName());
  EXPECT_EQ("/C", FS->status("/C")->getName());
}

TEST_F(VFSFromYAMLTest, MultiComponentPath) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("/other");

  // file in roots
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'roots': [\n"
      "  { 'type': 'file', 'name': '/path/to/file',\n"
      "    'external-contents': '/other' }]\n"
      "}", Lower);
  ASSERT_TRUE(NULL != FS.getPtr());
  EXPECT_EQ(errc::success, FS->status("/path/to/file").getError());
  EXPECT_EQ(errc::success, FS->status("/path/to").getError());
  EXPECT_EQ(errc::success, FS->status("/path").getError());
  EXPECT_EQ(errc::success, FS->status("/").getError());

  // at the start
  FS = getFromYAMLString(
      "{ 'roots': [\n"
      "  { 'type': 'directory', 'name': '/path/to',\n"
      "    'contents': [ { 'type': 'file', 'name': 'file',\n"
      "                    'external-contents': '/other' }]}]\n"
      "}", Lower);
  ASSERT_TRUE(NULL != FS.getPtr());
  EXPECT_EQ(errc::success, FS->status("/path/to/file").getError());
  EXPECT_EQ(errc::success, FS->status("/path/to").getError());
  EXPECT_EQ(errc::success, FS->status("/path").getError());
  EXPECT_EQ(errc::success, FS->status("/").getError());

  // at the end
  FS = getFromYAMLString(
      "{ 'roots': [\n"
      "  { 'type': 'directory', 'name': '/',\n"
      "    'contents': [ { 'type': 'file', 'name': 'path/to/file',\n"
      "                    'external-contents': '/other' }]}]\n"
      "}", Lower);
  ASSERT_TRUE(NULL != FS.getPtr());
  EXPECT_EQ(errc::success, FS->status("/path/to/file").getError());
  EXPECT_EQ(errc::success, FS->status("/path/to").getError());
  EXPECT_EQ(errc::success, FS->status("/path").getError());
  EXPECT_EQ(errc::success, FS->status("/").getError());
}

TEST_F(VFSFromYAMLTest, TrailingSlashes) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("/other");

  // file in roots
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'roots': [\n"
      "  { 'type': 'directory', 'name': '/path/to////',\n"
      "    'contents': [ { 'type': 'file', 'name': 'file',\n"
      "                    'external-contents': '/other' }]}]\n"
      "}", Lower);
  ASSERT_TRUE(NULL != FS.getPtr());
  EXPECT_EQ(errc::success, FS->status("/path/to/file").getError());
  EXPECT_EQ(errc::success, FS->status("/path/to").getError());
  EXPECT_EQ(errc::success, FS->status("/path").getError());
  EXPECT_EQ(errc::success, FS->status("/").getError());
}
@


