diff --git a/src/lib/object_store/File.cpp b/src/lib/object_store/File.cpp index 74f1adfb2..63d05dcae 100644 --- a/src/lib/object_store/File.cpp +++ b/src/lib/object_store/File.cpp @@ -143,6 +143,20 @@ File::~File() } } +// Check if a file exists without trying to open it +// May be used when a routine just wants to check file existence, +// and does not want to throw an error by trying to open it. +bool File::exists(const std::string& path) +{ +#ifndef _WIN32 + struct stat buf; + return stat(path.c_str(), &buf) == 0; +#else + return _access(path.c_str(), 0) == 0; +#endif +} + + // Check if the file is valid bool File::isValid() { diff --git a/src/lib/object_store/File.h b/src/lib/object_store/File.h index 433ee58cc..2c38ddc68 100644 --- a/src/lib/object_store/File.h +++ b/src/lib/object_store/File.h @@ -47,6 +47,11 @@ class File // Destructor virtual ~File(); + // Check if a file exists without trying to open it + // May be used when a routine just wants to check file existence, + // and does not want to throw an error by trying to open it. + static bool exists(const std::string& path); + // Check if the file is valid bool isValid(); diff --git a/src/lib/object_store/Generation.cpp b/src/lib/object_store/Generation.cpp index cb858796c..f79b8cb97 100644 --- a/src/lib/object_store/Generation.cpp +++ b/src/lib/object_store/Generation.cpp @@ -88,6 +88,13 @@ bool Generation::sync(File &objectFile) // Check if the target was updated bool Generation::wasUpdated() { + + // Check if path file exists before anything + if (!File::exists(path)) + { + return true; + } + if (isToken) { MutexLocker lock(genMutex); diff --git a/src/lib/object_store/test/FileTests.cpp b/src/lib/object_store/test/FileTests.cpp index c725d812b..d87f8966b 100644 --- a/src/lib/object_store/test/FileTests.cpp +++ b/src/lib/object_store/test/FileTests.cpp @@ -74,16 +74,18 @@ void FileTests::testExistNotExist() // Test pre-condition CPPUNIT_ASSERT(!exists("nonExistentFile")); - // Attempt to open a file known not to exist + // Check the 'exists' static routine, then attempt to open a file known not to exist #ifndef _WIN32 + CPPUNIT_ASSERT(!File::exists("testdir/nonExistentFile")); File doesntExist("testdir/nonExistentFile", DEFAULT_UMASK); #else + CPPUNIT_ASSERT(!File::exists("testdir\\nonExistentFile")); File doesntExist("testdir\\nonExistentFile", DEFAULT_UMASK); #endif CPPUNIT_ASSERT(!doesntExist.isValid()); - // Attempt to open a file known to exist + // Check the 'exists' static routine, then attempt to open a file known to exist #ifndef _WIN32 CPPUNIT_ASSERT(!system("echo someStuff > testdir/existingFile")); #else @@ -92,8 +94,10 @@ void FileTests::testExistNotExist() CPPUNIT_ASSERT(exists("existingFile")); #ifndef _WIN32 + CPPUNIT_ASSERT(File::exists("testdir/existingFile")); File exists("testdir/existingFile", DEFAULT_UMASK); #else + CPPUNIT_ASSERT(File::exists("testdir\\existingFile")); File exists("testdir\\existingFile", DEFAULT_UMASK); #endif