From 09cdc14fb6584840a2586d730ea637a252c6c365 Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Thu, 29 May 2025 16:15:33 -0700 Subject: [PATCH] Fix files.cc. PiperOrigin-RevId: 764926334 --- internal/base/BUILD | 1 + internal/base/file_path.h | 2 + internal/base/files.cc | 66 +++++++-------- internal/base/files.h | 82 ++++++++++--------- internal/base/files_test.cc | 29 ++++--- internal/platform/device_info_impl.cc | 17 ++-- internal/platform/implementation/g3/BUILD | 1 + .../platform/implementation/g3/device_info.h | 12 +-- .../platform/implementation/g3/platform.cc | 11 +-- .../implementation/windows/device_info.cc | 8 +- .../implementation/windows/platform.cc | 4 +- .../windows/preferences_manager.cc | 9 +- .../windows/preferences_repository.cc | 16 ++-- internal/test/fake_device_info.h | 9 +- internal/test/fake_device_info_test.cc | 28 +++---- .../nearby_connections_manager_impl_test.cc | 24 +++--- sharing/nearby_connections_types.h | 4 +- sharing/nearby_file_handler.cc | 8 +- sharing/nearby_file_handler_test.cc | 46 +++++------ sharing/nearby_sharing_service_impl_test.cc | 17 ++-- sharing/nearby_sharing_settings_test.cc | 2 +- 21 files changed, 193 insertions(+), 203 deletions(-) diff --git a/internal/base/BUILD b/internal/base/BUILD index 84075b65..1b364491 100644 --- a/internal/base/BUILD +++ b/internal/base/BUILD @@ -120,6 +120,7 @@ cc_test( "files_test.cc", ], deps = [ + ":file_path", ":files", "@com_github_protobuf_matchers//protobuf-matchers", "@com_google_googletest//:gtest_main", diff --git a/internal/base/file_path.h b/internal/base/file_path.h index 7ee4040b..09cadbd2 100644 --- a/internal/base/file_path.h +++ b/internal/base/file_path.h @@ -77,6 +77,8 @@ class FilePath { private: std::filesystem::path path_; + + friend class Files; }; } // namespace nearby diff --git a/internal/base/files.cc b/internal/base/files.cc index 1685597d..1c4d94bd 100644 --- a/internal/base/files.cc +++ b/internal/base/files.cc @@ -23,75 +23,76 @@ #include "internal/base/file_path.h" #include "internal/platform/logging.h" -namespace nearby::sharing { +namespace nearby { -bool FileExists(const std::filesystem::path& path) { +bool Files::FileExists(const FilePath& path) { std::error_code error_code; - if (std::filesystem::exists(path, error_code) && - !std::filesystem::is_directory(path, error_code)) { + if (std::filesystem::exists(path.path_, error_code) && + !std::filesystem::is_directory(path.path_, error_code)) { // is_directory returns false on error. return (!error_code); } return false; } -std::optional GetFileSize(const std::filesystem::path& path) { +std::optional Files::GetFileSize(const FilePath& path) { if (!FileExists(path)) { return std::nullopt; } std::error_code error_code; - uintmax_t size = std::filesystem::file_size(path, error_code); + uintmax_t size = std::filesystem::file_size(path.path_, error_code); if (size == static_cast(-1)) { return std::nullopt; } return size; } -bool DirectoryExists(const std::filesystem::path& path) { +bool Files::DirectoryExists(const FilePath& path) { std::error_code error_code; - if (std::filesystem::exists(path, error_code) && - std::filesystem::is_directory(path, error_code)) { + if (std::filesystem::exists(path.path_, error_code) && + std::filesystem::is_directory(path.path_, error_code)) { return true; } return false; } -bool RemoveFile(const std::filesystem::path& path) { +bool Files::RemoveFile(const FilePath& path) { if (!FileExists(path)) { return false; } std::error_code error_code; - return std::filesystem::remove(path, error_code); + return std::filesystem::remove(path.path_, error_code); } -bool RemoveDirectory(const FilePath& path) { - if (!DirectoryExists(path.GetPath())) { +bool Files::RemoveDirectory(const FilePath& path) { + // TODO: b/418255947 - Should return false if path is not a directory, and + // true if path does not exist. + if (!DirectoryExists(path)) { return false; } std::error_code error_code; - return std::filesystem::remove_all(path.GetPath(), error_code) != -1; + return std::filesystem::remove_all(path.path_, error_code) != -1; } -std::optional GetTemporaryDirectory() { +FilePath Files::GetTemporaryDirectory() { std::error_code error_code; std::filesystem::path temp_dir = std::filesystem::temp_directory_path(error_code); if (temp_dir.empty()) { - return std::nullopt; + return CurrentDirectory(); } - return FilePath::FromPath(temp_dir); + return FilePath{temp_dir.wstring()}; } -FilePath CurrentDirectory() { +FilePath Files::CurrentDirectory() { // temp_directory_path() returns empty path on error. std::error_code error_code; - return FilePath::FromPath(std::filesystem::current_path(error_code)); + return FilePath{std::filesystem::current_path(error_code).wstring()}; } -bool Rename(const std::filesystem::path& old_path, - const std::filesystem::path& new_path) { +bool Files::Rename(const FilePath& old_path, const FilePath& new_path) { std::error_code error_code; - std::filesystem::rename(old_path, new_path, error_code); + std::filesystem::rename(old_path.path_, new_path.path_, error_code); if (error_code) { VLOG(1) << "Failed to rename file: " << error_code.message(); return false; @@ -99,9 +100,9 @@ bool Rename(const std::filesystem::path& old_path, return true; } -bool CreateDirectories(const std::filesystem::path& path) { +bool Files::CreateDirectories(const FilePath& path) { std::error_code error_code; - std::filesystem::create_directories(path, error_code); + std::filesystem::create_directories(path.path_, error_code); if (error_code) { VLOG(1) << "Failed to create directories: " << error_code.message(); return false; @@ -109,10 +110,9 @@ bool CreateDirectories(const std::filesystem::path& path) { return true; } -bool CreateHardLink(const std::filesystem::path& target, - const std::filesystem::path& link_path) { +bool Files::CreateHardLink(const FilePath& target, const FilePath& link_path) { std::error_code error_code; - std::filesystem::create_hard_link(target, link_path, error_code); + std::filesystem::create_hard_link(target.path_, link_path.path_, error_code); if (error_code) { VLOG(1) << "Failed to create hard link: " << error_code.message(); return false; @@ -120,10 +120,9 @@ bool CreateHardLink(const std::filesystem::path& target, return true; } -bool CopyFileSafely(const std::filesystem::path& old_path, - const std::filesystem::path& new_path) { +bool Files::CopyFileSafely(const FilePath& old_path, const FilePath& new_path) { std::error_code error_code; - std::filesystem::copy(old_path, new_path, error_code); + std::filesystem::copy(old_path.path_, new_path.path_, error_code); if (error_code) { VLOG(1) << "Failed to copy file: " << error_code.message(); return false; @@ -131,14 +130,15 @@ bool CopyFileSafely(const std::filesystem::path& old_path, return true; } -std::optional GetAvailableDiskSpaceInBytes(const FilePath& path) { +std::optional Files::GetAvailableDiskSpaceInBytes( + const FilePath& path) { std::error_code error_code; std::filesystem::space_info space_info = - std::filesystem::space(path.GetPath(), error_code); + std::filesystem::space(path.path_, error_code); if (error_code.value() == 0) { return space_info.available; } return std::nullopt; } -} // namespace nearby::sharing +} // namespace nearby diff --git a/internal/base/files.h b/internal/base/files.h index 62fe4093..bf708786 100644 --- a/internal/base/files.h +++ b/internal/base/files.h @@ -17,60 +17,66 @@ #include #include -#include // NOLINT(build/c++17) #include #include "internal/base/file_path.h" -// This file contains exception safe wrappers to access common std::filesystem -// functions. -namespace nearby::sharing { +namespace nearby { -// Returns true if path exists and is not a directory. -bool FileExists(const std::filesystem::path& path); +// Utility functions for file operations.. +class Files { + public: + // Returns true if path exists and is not a directory. + static bool FileExists(const FilePath& path); -// Returns the size of the file at path, or nullopt if not found or not a file. -std::optional GetFileSize(const std::filesystem::path& path); + // Returns the size of the file at path, or nullopt if not found or not a + // file. + static std::optional GetFileSize(const FilePath& path); -// Returns true if path exists and is a directory. -bool DirectoryExists(const std::filesystem::path& path); + // Returns true if path exists and is a directory. + static bool DirectoryExists(const FilePath& path); -// Removes the file at path and returns true. -// Returns false if path does not exist, is not a file or cannot be removed. -bool RemoveFile(const std::filesystem::path& path); + // Removes the file at path and returns true. + // Returns false if path does not exist, is not a file or cannot be removed. + static bool RemoveFile(const FilePath& path); -bool RemoveDirectory(const FilePath& path); + // Recursively removes the directory at path and returns true. + // Returns false if path does not exist, is not a directory or cannot be + // removed. + static bool RemoveDirectory(const FilePath& path); -// Returns path to a temporary directory if available. -std::optional GetTemporaryDirectory(); + // Returns path to a temporary directory if available. + // If system defined temporary directory is not available, returns the current + // directory. + static FilePath GetTemporaryDirectory(); -// Returns path to the current directory. On failure returns an empty path. -FilePath CurrentDirectory(); + // Returns path to the current directory. On failure returns an empty path. + static FilePath CurrentDirectory(); -// Renames the file at old_path to new_path. -// Returns true on success. -bool Rename(const std::filesystem::path& old_path, - const std::filesystem::path& new_path); + // Renames the file at old_path to new_path. + // Returns true on success. + static bool Rename(const FilePath& old_path, const FilePath& new_path); -// Creates all directory leading to path. -// Returns true on success. -bool CreateDirectories(const std::filesystem::path& path); + // Creates all directory leading to path. + // Returns true on success. + static bool CreateDirectories(const FilePath& path); -// Creates a hard link to target at link_path. -// Returns true on success. -bool CreateHardLink(const std::filesystem::path& target, - const std::filesystem::path& link_path); + // Creates a hard link to target at link_path. + // Returns true on success. + static bool CreateHardLink(const FilePath& target, const FilePath& link_path); -// Copies the file at old_path to new_path. -// Returns true on success. -bool CopyFileSafely(const std::filesystem::path& old_path, - const std::filesystem::path& new_path); + // Copies the file at old_path to new_path. + // Returns true on success. + static bool CopyFileSafely(const FilePath& old_path, + const FilePath& new_path); -// Returns the available disk space in bytes for the given path. -// Returns nullopt if the path does not exist or if the space cannot be -// determined. -std::optional GetAvailableDiskSpaceInBytes(const FilePath& path); + // Returns the available disk space in bytes for the given path. + // Returns nullopt if the path does not exist or if the space cannot be + // determined. + static std::optional GetAvailableDiskSpaceInBytes( + const FilePath& path); +}; -} // namespace nearby::sharing +} // namespace nearby #endif // THIRD_PARTY_NEARBY_INTERNAL_BASE_FILES_H_ diff --git a/internal/base/files_test.cc b/internal/base/files_test.cc index 7a8e1530..2810038f 100644 --- a/internal/base/files_test.cc +++ b/internal/base/files_test.cc @@ -21,28 +21,31 @@ #include #include "gtest/gtest.h" +#include "internal/base/file_path.h" -namespace nearby::sharing { +namespace nearby { namespace { TEST(FilesTest, CreateHardLinkSuccess) { - std::filesystem::path temp_dir = testing::TempDir(); - std::filesystem::path target = temp_dir / "target"; - RemoveFile(target); - std::ofstream ofstream(target, std::ios::app); + FilePath temp_dir{testing::TempDir()}; + FilePath target = temp_dir; + target.append(FilePath("target")); + Files::RemoveFile(target); + std::ofstream ofstream(target.GetPath(), std::ios::app); ASSERT_EQ(ofstream.rdstate(), std::ios_base::goodbit); ofstream << "Hello world"; ofstream.flush(); - std::optional size = GetFileSize(target); + std::optional size = Files::GetFileSize(target); ASSERT_TRUE(size.has_value()); EXPECT_EQ(size.value(), 11); - std::filesystem::path link_path = temp_dir / "link_path"; - EXPECT_TRUE(CreateHardLink(target, link_path)); - EXPECT_TRUE(FileExists(link_path)); - EXPECT_EQ(GetFileSize(link_path), 11); - RemoveFile(link_path); - RemoveFile(target); + FilePath link_path = temp_dir; + link_path.append(FilePath("link_path")); + EXPECT_TRUE(Files::CreateHardLink(target, link_path)); + EXPECT_TRUE(Files::FileExists(link_path)); + EXPECT_EQ(Files::GetFileSize(link_path), 11); + Files::RemoveFile(link_path); + Files::RemoveFile(target); } } // namespace -} // namespace nearby::sharing +} // namespace nearby diff --git a/internal/platform/device_info_impl.cc b/internal/platform/device_info_impl.cc index d62711a7..79d5be7f 100644 --- a/internal/platform/device_info_impl.cc +++ b/internal/platform/device_info_impl.cc @@ -18,16 +18,16 @@ #include #include #include + #include "absl/strings/string_view.h" -#include "internal/base/files.h" #include "internal/base/file_path.h" +#include "internal/base/files.h" #include "internal/platform/implementation/device_info.h" namespace nearby { std::string DeviceInfoImpl::GetOsDeviceName() const { - std::optional device_name = - device_info_impl_->GetOsDeviceName(); + std::optional device_name = device_info_impl_->GetOsDeviceName(); if (device_name.has_value()) { return *device_name; } @@ -48,8 +48,7 @@ FilePath DeviceInfoImpl::GetDownloadPath() const { if (path.has_value()) { return *path; } - return nearby::sharing::GetTemporaryDirectory().value_or( - nearby::sharing::CurrentDirectory()); + return Files::GetTemporaryDirectory(); } FilePath DeviceInfoImpl::GetAppDataPath() const { @@ -57,8 +56,7 @@ FilePath DeviceInfoImpl::GetAppDataPath() const { if (path.has_value()) { return *path; } - return nearby::sharing::GetTemporaryDirectory().value_or( - nearby::sharing::CurrentDirectory()); + return Files::GetTemporaryDirectory(); } FilePath DeviceInfoImpl::GetTemporaryPath() const { @@ -66,8 +64,7 @@ FilePath DeviceInfoImpl::GetTemporaryPath() const { if (path.has_value()) { return *path; } - return nearby::sharing::GetTemporaryDirectory().value_or( - nearby::sharing::CurrentDirectory()); + return Files::GetTemporaryDirectory(); } FilePath DeviceInfoImpl::GetLogPath() const { @@ -77,7 +74,7 @@ FilePath DeviceInfoImpl::GetLogPath() const { std::optional DeviceInfoImpl::GetAvailableDiskSpaceInBytes( const FilePath& path) const { - return nearby::sharing::GetAvailableDiskSpaceInBytes(path); + return Files::GetAvailableDiskSpaceInBytes(path); } bool DeviceInfoImpl::IsScreenLocked() const { diff --git a/internal/platform/implementation/g3/BUILD b/internal/platform/implementation/g3/BUILD index 7d075edf..4e7a2b8a 100644 --- a/internal/platform/implementation/g3/BUILD +++ b/internal/platform/implementation/g3/BUILD @@ -160,6 +160,7 @@ cc_library( ":comm", ":crypto", # build_cleaner: keep ":types", + "//internal/base:file_path", "//internal/base:files", "//internal/platform:base", "//internal/platform:logging", diff --git a/internal/platform/implementation/g3/device_info.h b/internal/platform/implementation/g3/device_info.h index c8888e49..85c306aa 100644 --- a/internal/platform/implementation/g3/device_info.h +++ b/internal/platform/implementation/g3/device_info.h @@ -45,13 +45,13 @@ class DeviceInfo : public api::DeviceInfo { } std::optional GetDownloadPath() const override { - return nearby::sharing::GetTemporaryDirectory(); + return Files::GetTemporaryDirectory(); } std::optional GetLocalAppDataPath() const override { const char* home_dir = getenv("HOME"); if (home_dir == nullptr) { - return nearby::sharing::GetTemporaryDirectory(); + return Files::GetTemporaryDirectory(); } // Yhis matches the .NET LocalAppData directory on Linux. return FilePath(home_dir) @@ -60,19 +60,19 @@ class DeviceInfo : public api::DeviceInfo { } std::optional GetCommonAppDataPath() const override { - return nearby::sharing::GetTemporaryDirectory(); + return Files::GetTemporaryDirectory(); } std::optional GetTemporaryPath() const override { - return nearby::sharing::GetTemporaryDirectory(); + return Files::GetTemporaryDirectory(); } std::optional GetLogPath() const override { - return nearby::sharing::GetTemporaryDirectory(); + return Files::GetTemporaryDirectory(); } std::optional GetCrashDumpPath() const override { - return nearby::sharing::GetTemporaryDirectory(); + return Files::GetTemporaryDirectory(); } bool IsScreenLocked() const override { return false; } diff --git a/internal/platform/implementation/g3/platform.cc b/internal/platform/implementation/g3/platform.cc index 9de46713..0f0de685 100644 --- a/internal/platform/implementation/g3/platform.cc +++ b/internal/platform/implementation/g3/platform.cc @@ -25,6 +25,7 @@ #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" +#include "internal/base/file_path.h" #include "internal/base/files.h" #include "internal/platform/implementation/atomic_boolean.h" #include "internal/platform/implementation/atomic_reference.h" @@ -164,12 +165,12 @@ std::unique_ptr ImplementationPlatform::CreateOutputFile( std::unique_ptr ImplementationPlatform::CreateOutputFile( const std::string& file_path) { - std::filesystem::path path = std::filesystem::u8path(file_path); - std::filesystem::path folder_path = path.parent_path(); + FilePath path(file_path); + FilePath folder_path = path.GetParentPath(); // Verifies that a path is a valid directory. - if (!sharing::DirectoryExists(folder_path)) { - if (!sharing::CreateDirectories(folder_path)) { - LOG(ERROR) << "Failed to create directory: " << folder_path.string(); + if (!Files::DirectoryExists(folder_path)) { + if (!Files::CreateDirectories(folder_path)) { + LOG(ERROR) << "Failed to create directory: " << folder_path.ToString(); return nullptr; } } diff --git a/internal/platform/implementation/windows/device_info.cc b/internal/platform/implementation/windows/device_info.cc index 48a95f4e..857eb648 100644 --- a/internal/platform/implementation/windows/device_info.cc +++ b/internal/platform/implementation/windows/device_info.cc @@ -33,8 +33,7 @@ #include "winrt/Windows.Foundation.h" #include "winrt/Windows.System.h" -namespace nearby { -namespace windows { +namespace nearby::windows { using IInspectable = winrt::Windows::Foundation::IInspectable; using KnownUserProperties = winrt::Windows::System::KnownUserProperties; @@ -131,7 +130,7 @@ std::optional DeviceInfo::GetCommonAppDataPath() const { } std::optional DeviceInfo::GetTemporaryPath() const { - return nearby::sharing::GetTemporaryDirectory(); + return Files::GetTemporaryDirectory(); } std::optional DeviceInfo::GetLogPath() const { @@ -186,5 +185,4 @@ bool DeviceInfo::AllowSleep() { return session_manager_.AllowSleep(); } -} // namespace windows -} // namespace nearby +} // namespace nearby::windows diff --git a/internal/platform/implementation/windows/platform.cc b/internal/platform/implementation/windows/platform.cc index 5f1b3d59..6bdbc19e 100644 --- a/internal/platform/implementation/windows/platform.cc +++ b/internal/platform/implementation/windows/platform.cc @@ -220,8 +220,8 @@ std::unique_ptr ImplementationPlatform::CreateOutputFile( FilePath path{file_path}; FilePath folder_path = path.GetParentPath(); // Verifies that a path is a valid directory. - if (!sharing::DirectoryExists(folder_path.GetPath())) { - if (!sharing::CreateDirectories(folder_path.GetPath())) { + if (!Files::DirectoryExists(folder_path)) { + if (!Files::CreateDirectories(folder_path)) { LOG(ERROR) << "Failed to create directory: " << folder_path.ToString(); return nullptr; diff --git a/internal/platform/implementation/windows/preferences_manager.cc b/internal/platform/implementation/windows/preferences_manager.cc index 35b48bbd..b1e4b265 100644 --- a/internal/platform/implementation/windows/preferences_manager.cc +++ b/internal/platform/implementation/windows/preferences_manager.cc @@ -35,8 +35,7 @@ #include "internal/platform/implementation/windows/preferences_repository.h" #include "internal/platform/logging.h" -namespace nearby { -namespace windows { +namespace nearby::windows { namespace { using json = ::nlohmann::json; } // namespace @@ -47,8 +46,7 @@ PreferencesManager::PreferencesManager(absl::string_view file_path) nearby::api::ImplementationPlatform::CreateDeviceInfo() ->GetLocalAppDataPath(); if (!path.has_value()) { - path = nearby::sharing::GetTemporaryDirectory().value_or( - nearby::sharing::CurrentDirectory()); + path = Files::GetTemporaryDirectory(); } path->append(FilePath(file_path)); @@ -287,5 +285,4 @@ std::vector PreferencesManager::GetArrayValue( return result; } -} // namespace windows -} // namespace nearby +} // namespace nearby::windows diff --git a/internal/platform/implementation/windows/preferences_repository.cc b/internal/platform/implementation/windows/preferences_repository.cc index 4ab7d2cb..b7ce4d1f 100644 --- a/internal/platform/implementation/windows/preferences_repository.cc +++ b/internal/platform/implementation/windows/preferences_repository.cc @@ -70,8 +70,7 @@ bool PreferencesRepository::SavePreferences(json preferences) { absl::MutexLock lock(&mutex_); try { FilePath path{path_}; - if (!nearby::sharing::FileExists(path.GetPath()) && - !nearby::sharing::CreateDirectories(path.GetPath())) { + if (!Files::FileExists(path) && !Files::CreateDirectories(path)) { LOG(ERROR) << "Failed to create preferences path."; return false; } @@ -82,10 +81,9 @@ bool PreferencesRepository::SavePreferences(json preferences) { full_name_backup.append(FilePath(kPreferencesBackupFileName)); // Create a backup without moving the bytes on disk - if (nearby::sharing::FileExists(full_name.GetPath())) { + if (Files::FileExists(full_name)) { LOG(INFO) << "Making backup of preferences file."; - if (!nearby::sharing::Rename(full_name.GetPath(), - full_name_backup.GetPath())) { + if (!Files::Rename(full_name, full_name_backup)) { LOG(ERROR) << "Failed to rename preferences backup file."; } } @@ -119,8 +117,7 @@ std::optional PreferencesRepository::AttemptLoad() { FilePath path{path_}; FilePath full_name = path; full_name.append(FilePath(kPreferencesFileName)); - if (!nearby::sharing::DirectoryExists(path.GetPath()) || - !nearby::sharing::FileExists(full_name.GetPath())) { + if (!Files::DirectoryExists(path) || !Files::FileExists(full_name)) { return std::nullopt; } @@ -155,13 +152,12 @@ std::optional PreferencesRepository::RestoreFromBackup() { FilePath full_name_backup = path; full_name_backup.append(FilePath(kPreferencesBackupFileName)); - if (!nearby::sharing::FileExists(full_name_backup.GetPath())) { + if (!Files::FileExists(full_name_backup)) { LOG(WARNING) << "Backup requested but no backup preferences file found."; return std::nullopt; } - if (!nearby::sharing::Rename(full_name_backup.GetPath(), - full_name.GetPath())) { + if (!Files::Rename(full_name_backup, full_name)) { LOG(ERROR) << "Failed to rename preferences backup file."; } diff --git a/internal/test/fake_device_info.h b/internal/test/fake_device_info.h index 34630a89..22d491da 100644 --- a/internal/test/fake_device_info.h +++ b/internal/test/fake_device_info.h @@ -123,12 +123,9 @@ class FakeDeviceInfo : public DeviceInfo { api::DeviceInfo::DeviceType device_type_ = api::DeviceInfo::DeviceType::kLaptop; api::DeviceInfo::OsType os_type_ = api::DeviceInfo::OsType::kWindows; - FilePath download_path_ = nearby::sharing::GetTemporaryDirectory().value_or( - nearby::sharing::CurrentDirectory()); - FilePath app_data_path_ = nearby::sharing::GetTemporaryDirectory().value_or( - nearby::sharing::CurrentDirectory()); - FilePath temp_path_ = nearby::sharing::GetTemporaryDirectory().value_or( - nearby::sharing::CurrentDirectory()); + FilePath download_path_ = Files::GetTemporaryDirectory(); + FilePath app_data_path_ = Files::GetTemporaryDirectory(); + FilePath temp_path_ = Files::GetTemporaryDirectory(); absl::flat_hash_map available_space_map_; absl::flat_hash_map> diff --git a/internal/test/fake_device_info_test.cc b/internal/test/fake_device_info_test.cc index 47b7f51d..4e7c936e 100644 --- a/internal/test/fake_device_info_test.cc +++ b/internal/test/fake_device_info_test.cc @@ -15,7 +15,6 @@ #include "internal/test/fake_device_info.h" #include -#include #include "gtest/gtest.h" #include "internal/base/file_path.h" @@ -25,12 +24,6 @@ namespace nearby { namespace { -FilePath GetTempDir() { - std::optional temp_dir = nearby::sharing::GetTemporaryDirectory(); - EXPECT_TRUE(temp_dir.has_value()); - return temp_dir.value(); -} - TEST(FakeDeviceInfo, DeviceName) { FakeDeviceInfo device_info; device_info.SetOsDeviceName("windows"); @@ -51,26 +44,29 @@ TEST(FakeDeviceInfo, OsType) { TEST(FakeDeviceInfo, GetDownloadPath) { FakeDeviceInfo device_info; - EXPECT_EQ(device_info.GetDownloadPath(), GetTempDir()); - device_info.SetDownloadPath(GetTempDir().append(FilePath("test"))); + EXPECT_EQ(device_info.GetDownloadPath(), Files::GetTemporaryDirectory()); + device_info.SetDownloadPath( + Files::GetTemporaryDirectory().append(FilePath("test"))); EXPECT_EQ(device_info.GetDownloadPath(), - GetTempDir().append(FilePath("test"))); + Files::GetTemporaryDirectory().append(FilePath("test"))); } TEST(FakeDeviceInfo, GetAppDataPath) { FakeDeviceInfo device_info; - EXPECT_EQ(device_info.GetAppDataPath(), GetTempDir()); - device_info.SetAppDataPath(GetTempDir().append(FilePath("test"))); + EXPECT_EQ(device_info.GetAppDataPath(), Files::GetTemporaryDirectory()); + device_info.SetAppDataPath( + Files::GetTemporaryDirectory().append(FilePath("test"))); EXPECT_EQ(device_info.GetAppDataPath(), - GetTempDir().append(FilePath("test"))); + Files::GetTemporaryDirectory().append(FilePath("test"))); } TEST(FakeDeviceInfo, GetTemporaryPath) { FakeDeviceInfo device_info; - EXPECT_EQ(device_info.GetTemporaryPath(), GetTempDir()); - device_info.SetTemporaryPath(GetTempDir().append(FilePath("test"))); + EXPECT_EQ(device_info.GetTemporaryPath(), Files::GetTemporaryDirectory()); + device_info.SetTemporaryPath( + Files::GetTemporaryDirectory().append(FilePath("test"))); EXPECT_EQ(device_info.GetTemporaryPath(), - GetTempDir().append(FilePath("test"))); + Files::GetTemporaryDirectory().append(FilePath("test"))); } TEST(FakeDeviceInfo, GetAvailableDiskSpaceInBytes) { diff --git a/sharing/nearby_connections_manager_impl_test.cc b/sharing/nearby_connections_manager_impl_test.cc index a7937e5c..140734b5 100644 --- a/sharing/nearby_connections_manager_impl_test.cc +++ b/sharing/nearby_connections_manager_impl_test.cc @@ -388,7 +388,7 @@ class NearbyConnectionsManagerImplTest : public testing::Test { const std::vector expected_payload(std::begin(kPayload), std::end(kPayload)); - FilePath file = GetTemporaryDirectory()->append(FilePath("file.jpg")); + FilePath file = Files::GetTemporaryDirectory().append(FilePath("file.jpg")); InitializeTemporaryFile(file); absl::Notification notification; @@ -1403,8 +1403,8 @@ TEST_F(NearbyConnectionsManagerImplTest, nearby_connections_manager_->RegisterPayloadStatusListener( kPayloadId3, payload_listener->GetWeakPtr()); - FilePath file1 = GetTemporaryDirectory()->append(FilePath("file1.jpg")); - FilePath file2 = GetTemporaryDirectory()->append(FilePath("file2.jpg")); + FilePath file1 = Files::GetTemporaryDirectory().append(FilePath("file1.jpg")); + FilePath file2 = Files::GetTemporaryDirectory().append(FilePath("file2.jpg")); InitializeTemporaryFile(file1); InitializeTemporaryFile(file2); @@ -1519,7 +1519,7 @@ TEST_F(NearbyConnectionsManagerImplTest, IncomingFilePayload) { const std::vector expected_payload(std::begin(kPayload), std::end(kPayload)); - FilePath file = GetTemporaryDirectory()->append(FilePath("file.jpg")); + FilePath file = Files::GetTemporaryDirectory().append(FilePath("file.jpg")); InitializeTemporaryFile(file); payload_listener_remote.payload_cb( @@ -1569,7 +1569,7 @@ TEST_F(NearbyConnectionsManagerImplTest, ClearIncomingPayloads) { nearby_connections_manager_->RegisterPayloadStatusListener( kPayloadId, payload_listener->GetWeakPtr()); - FilePath file = GetTemporaryDirectory()->append(FilePath("file.jpg")); + FilePath file = Files::GetTemporaryDirectory().append(FilePath("file.jpg")); InitializeTemporaryFile(file); payload_listener_remote.payload_cb( @@ -1848,7 +1848,7 @@ TEST_F(NearbyConnectionsManagerImplTest, ASSERT_TRUE(OnIncomingConnection(connection_listener_remote, incoming_connection_listener, payload_listener_remote) != nullptr); - FilePath file = GetTemporaryDirectory()->append(FilePath("file.jpg")); + FilePath file = Files::GetTemporaryDirectory().append(FilePath("file.jpg")); payload_listener_remote.payload_cb( kRemoteEndpointId, Payload(kPayloadId, InputFile(file.ToString()))); @@ -1881,7 +1881,7 @@ TEST_F(NearbyConnectionsManagerImplTest, OnPayloadReceivedForUnknownFile) { ASSERT_TRUE(OnIncomingConnection(connection_listener_remote, incoming_connection_listener, payload_listener_remote) != nullptr); - FilePath file = GetTemporaryDirectory()->append(FilePath("file.jpg")); + FilePath file = Files::GetTemporaryDirectory().append(FilePath("file.jpg")); payload_listener_remote.payload_cb( kRemoteEndpointId, Payload(kPayloadId, InputFile(file.ToString()))); @@ -1895,7 +1895,7 @@ TEST_F(NearbyConnectionsManagerImplTest, OnPayloadReceivedForUnknownFile) { nearby_connections_manager_->OnPayloadReceivedForTesting(kRemoteEndpointId, payload); - FilePath file2 = GetTemporaryDirectory()->append(FilePath("file2.jpg")); + FilePath file2 = Files::GetTemporaryDirectory().append(FilePath("file2.jpg")); Payload payload2(kPayloadId, InputFile(file2.ToString())); nearby_connections_manager_->OnPayloadReceivedForTesting(kRemoteEndpointId, payload2); @@ -1908,7 +1908,7 @@ TEST_F(NearbyConnectionsManagerImplTest, OnPayloadReceivedForUnknownFile) { std::make_shared>(); nearby_connections_manager_->RegisterPayloadStatusListener( kPayloadId, payload_listener->GetWeakPtr()); - FilePath file3 = GetTemporaryDirectory()->append(FilePath("file3.jpg")); + FilePath file3 = Files::GetTemporaryDirectory().append(FilePath("file3.jpg")); Payload payload3(kPayloadId, InputFile(file3.ToString())); nearby_connections_manager_->OnPayloadReceivedForTesting(kRemoteEndpointId, payload3); @@ -1939,7 +1939,7 @@ TEST_F(NearbyConnectionsManagerImplTest, nearby_connections_manager_->RegisterPayloadStatusListener( kPayloadId, payload_listener->GetWeakPtr()); - FilePath file = GetTemporaryDirectory()->append(FilePath("file.jpg")); + FilePath file = Files::GetTemporaryDirectory().append(FilePath("file.jpg")); Payload payload(kPayloadId, InputFile(file.ToString())); nearby_connections_manager_->OnPayloadReceivedForTesting(kRemoteEndpointId, @@ -1970,7 +1970,7 @@ TEST_F(NearbyConnectionsManagerImplTest, payload_notification.Notify(); }); - FilePath file2 = GetTemporaryDirectory()->append(FilePath("file2.jpg")); + FilePath file2 = Files::GetTemporaryDirectory().append(FilePath("file2.jpg")); Payload payload2(kPayloadId, InputFile(file2.ToString())); nearby_connections_manager_->OnPayloadReceivedForTesting(kRemoteEndpointId, payload2); @@ -1985,7 +1985,7 @@ TEST_F(NearbyConnectionsManagerImplTest, } TEST_F(NearbyConnectionsManagerImplTest, ProcessUnknownFilePathsToDelete) { - FilePath file = GetTemporaryDirectory()->append(FilePath("file.jpg")); + FilePath file = Files::GetTemporaryDirectory().append(FilePath("file.jpg")); nearby_connections_manager_->ProcessUnknownFilePathsToDeleteForTesting( PayloadStatus::kCanceled, PayloadContent::Type::kFile, file); absl::flat_hash_set unknown_file_paths = diff --git a/sharing/nearby_connections_types.h b/sharing/nearby_connections_types.h index fd431e6b..71145f5c 100644 --- a/sharing/nearby_connections_types.h +++ b/sharing/nearby_connections_types.h @@ -413,7 +413,7 @@ struct Payload { id = std::hash()(file.path.ToString()); content.type = PayloadContent::Type::kFile; - std::optional size = GetFileSize(file.path.GetPath()); + std::optional size = Files::GetFileSize(file.path); if (size.has_value()) { content.file_payload.size = *size; } @@ -431,7 +431,7 @@ struct Payload { absl::string_view parent_folder = absl::string_view()) : id(id) { content.type = PayloadContent::Type::kFile; - std::optional size = GetFileSize(file.path.GetPath()); + std::optional size = Files::GetFileSize(file.path); if (size.has_value()) { content.file_payload.size = *size; } diff --git a/sharing/nearby_file_handler.cc b/sharing/nearby_file_handler.cc index da3afd35..fa682488 100644 --- a/sharing/nearby_file_handler.cc +++ b/sharing/nearby_file_handler.cc @@ -42,7 +42,7 @@ std::vector DoOpenFiles( absl::Span file_paths) { std::vector files; for (const auto& file_path : file_paths) { - std::optional size = GetFileSize(file_path.GetPath()); + std::optional size = Files::GetFileSize(file_path); if (!size.has_value()) { LOG(ERROR) << __func__ << ": Failed to open file. File=" << file_path.ToString(); @@ -78,16 +78,16 @@ void NearbyFileHandler::DeleteFilesFromDisk( // wait 1 second to make the file being released from another process. absl::SleepFor(absl::Seconds(1)); for (const auto& file_path : file_paths) { - if (!FileExists(file_path.GetPath())) { + if (!Files::FileExists(file_path)) { continue; } - if (RemoveFile(file_path.GetPath())) { + if (Files::RemoveFile(file_path)) { VLOG(1) << __func__ << ": Removed partial file. File=" << file_path.ToString(); } else { // Try once more after 3 seconds. absl::SleepFor(absl::Seconds(3)); - if (RemoveFile(file_path.GetPath())) { + if (Files::RemoveFile(file_path)) { VLOG(1) << __func__ << ": Removed partial file after additional delay. File=" << file_path.ToString(); diff --git a/sharing/nearby_file_handler_test.cc b/sharing/nearby_file_handler_test.cc index 5305433b..d431e074 100644 --- a/sharing/nearby_file_handler_test.cc +++ b/sharing/nearby_file_handler_test.cc @@ -45,8 +45,8 @@ TEST(NearbyFileHandler, OpenFiles) { NearbyFileHandler nearby_file_handler(mock_platform); absl::Notification notification; std::vector result; - FilePath test_file = - GetTemporaryDirectory()->append(FilePath("nearby_nfh_test_abc.jpg")); + FilePath test_file = Files::GetTemporaryDirectory().append( + FilePath("nearby_nfh_test_abc.jpg")); ASSERT_TRUE(CreateFile(test_file)); nearby_file_handler.OpenFiles( @@ -58,61 +58,61 @@ TEST(NearbyFileHandler, OpenFiles) { notification.WaitForNotificationWithTimeout(absl::Seconds(1)); EXPECT_EQ(result.size(), 1); - ASSERT_TRUE(RemoveFile(test_file.GetPath())); + ASSERT_TRUE(Files::RemoveFile(test_file)); } TEST(NearbyFileHandler, DeleteAFileFromDisk) { MockSharingPlatform mock_platform; NearbyFileHandler nearby_file_handler(mock_platform); - FilePath test_file = - GetTemporaryDirectory()->append(FilePath("nearby_nfh_test_abc.jpg")); + FilePath test_file = Files::GetTemporaryDirectory().append( + FilePath("nearby_nfh_test_abc.jpg")); ASSERT_TRUE(CreateFile(test_file)); std::vector file_paths; file_paths.push_back(test_file); nearby_file_handler.DeleteFilesFromDisk(file_paths, []() {}); - ASSERT_TRUE(FileExists(test_file.GetPath())); + ASSERT_TRUE(Files::FileExists(test_file)); absl::SleepFor(absl::Seconds(2)); - ASSERT_FALSE(FileExists(test_file.GetPath())); + ASSERT_FALSE(Files::FileExists(test_file)); } TEST(NearbyFileHandler, DeleteMultipleFilesFromDisk) { MockSharingPlatform mock_platform; NearbyFileHandler nearby_file_handler(mock_platform); - FilePath test_file = - GetTemporaryDirectory()->append(FilePath("nearby_nfh_test_abc.jpg")); - FilePath test_file2 = - GetTemporaryDirectory()->append(FilePath("nearby_nfh_test_def.jpg")); - FilePath test_file3 = - GetTemporaryDirectory()->append(FilePath("nearby_nfh_test_ghi.jpg")); + FilePath test_file = Files::GetTemporaryDirectory().append( + FilePath("nearby_nfh_test_abc.jpg")); + FilePath test_file2 = Files::GetTemporaryDirectory().append( + FilePath("nearby_nfh_test_def.jpg")); + FilePath test_file3 = Files::GetTemporaryDirectory().append( + FilePath("nearby_nfh_test_ghi.jpg")); std::vector file_paths; file_paths = {test_file, test_file2, test_file3}; // Check it doesn't throw an exception. nearby_file_handler.DeleteFilesFromDisk(file_paths, []() {}); - ASSERT_FALSE(FileExists(test_file.GetPath())); - ASSERT_FALSE(FileExists(test_file2.GetPath())); - ASSERT_FALSE(FileExists(test_file3.GetPath())); + ASSERT_FALSE(Files::FileExists(test_file)); + ASSERT_FALSE(Files::FileExists(test_file2)); + ASSERT_FALSE(Files::FileExists(test_file3)); absl::SleepFor(absl::Seconds(2)); - ASSERT_FALSE(FileExists(test_file.GetPath())); - ASSERT_FALSE(FileExists(test_file2.GetPath())); - ASSERT_FALSE(FileExists(test_file3.GetPath())); + ASSERT_FALSE(Files::FileExists(test_file)); + ASSERT_FALSE(Files::FileExists(test_file2)); + ASSERT_FALSE(Files::FileExists(test_file3)); } TEST(NearbyFileHandler, TestCallback) { MockSharingPlatform mock_platform; std::atomic_bool received_callback = false; NearbyFileHandler nearby_file_handler(mock_platform); - FilePath test_file = - GetTemporaryDirectory()->append(FilePath("nearby_nfh_test_abc.jpg")); + FilePath test_file = Files::GetTemporaryDirectory().append( + FilePath("nearby_nfh_test_abc.jpg")); ASSERT_TRUE(CreateFile(test_file)); std::vector file_paths; file_paths.push_back(test_file); nearby_file_handler.DeleteFilesFromDisk( file_paths, [&received_callback]() { received_callback = true; }); ASSERT_FALSE(received_callback); - ASSERT_TRUE(FileExists(test_file.GetPath())); + ASSERT_TRUE(Files::FileExists(test_file)); absl::SleepFor(absl::Seconds(2)); ASSERT_TRUE(received_callback); - ASSERT_FALSE(FileExists(test_file.GetPath())); + ASSERT_FALSE(Files::FileExists(test_file)); } } // namespace diff --git a/sharing/nearby_sharing_service_impl_test.cc b/sharing/nearby_sharing_service_impl_test.cc index d44559f1..f52ea277 100644 --- a/sharing/nearby_sharing_service_impl_test.cc +++ b/sharing/nearby_sharing_service_impl_test.cc @@ -128,12 +128,6 @@ using ::testing::UnorderedElementsAre; constexpr absl::Duration kWaitTimeout = absl::Milliseconds(500); constexpr absl::Duration kTaskWaitTimeout = absl::Seconds(2); -FilePath GetTempDir() { - std::optional temp_dir = nearby::sharing::GetTemporaryDirectory(); - EXPECT_TRUE(temp_dir.has_value()); - return temp_dir.value(); -} - class MockTransferUpdateCallback : public TransferUpdateCallback { public: ~MockTransferUpdateCallback() override = default; @@ -270,7 +264,7 @@ constexpr absl::Duration kCertificateDownloadDuringDiscoveryPeriod = std::unique_ptr GetFilePayload(int64_t payload_id) { FilePath path = - GetTemporaryDirectory()->append(FilePath(absl::StrCat(payload_id))); + Files::GetTemporaryDirectory().append(FilePath(absl::StrCat(payload_id))); InputFile input_file{path.ToString()}; return std::make_unique(input_file); } @@ -1230,7 +1224,7 @@ class NearbySharingServiceImplTest : public testing::Test { EXPECT_FALSE(fake_nearby_connections_manager_->has_incoming_payloads()); // Remove test file. - RemoveFile(file_path.GetPath()); + Files::RemoveFile(file_path); } void FlushTesting() { @@ -1240,7 +1234,8 @@ class NearbySharingServiceImplTest : public testing::Test { } void SetDiskSpace(size_t size) { - fake_device_info_.SetAvailableDiskSpaceInBytes(GetTempDir(), size); + fake_device_info_.SetAvailableDiskSpaceInBytes( + Files::GetTemporaryDirectory(), size); } void ResetDiskSpace() { fake_device_info_.ResetDiskSpace(); } @@ -1260,7 +1255,7 @@ class NearbySharingServiceImplTest : public testing::Test { FilePath CreateTestFile(absl::string_view name, const std::vector& content) { - FilePath path = GetTemporaryDirectory()->append(FilePath(name)); + FilePath path = Files::GetTemporaryDirectory().append(FilePath(name)); std::FILE* file = std::fopen(path.GetPath().c_str(), "w+"); std::fwrite(content.data(), 1, content.size(), file); std::fclose(file); @@ -3673,7 +3668,7 @@ TEST_F(NearbySharingServiceImplTest, SendFilesSuccess) { PayloadInfo info = GetWrittenPayload(); ASSERT_TRUE(info.payload->content.is_file()); FilePath file = info.payload->content.file_payload.file.path; - ASSERT_TRUE(FileExists(file.GetPath())); + ASSERT_TRUE(Files::FileExists(file)); } TEST_F(NearbySharingServiceImplTest, SendWifiCredentialsSuccess) { diff --git a/sharing/nearby_sharing_settings_test.cc b/sharing/nearby_sharing_settings_test.cc index 6b56cbb7..422c662e 100644 --- a/sharing/nearby_sharing_settings_test.cc +++ b/sharing/nearby_sharing_settings_test.cc @@ -169,7 +169,7 @@ class NearbyShareSettingsTest : public ::testing::Test { TEST_F(NearbyShareSettingsTest, GetAndSetCustomSavePath) { absl::Notification notification; - std::string save_path = GetTemporaryDirectory()->ToString(); + std::string save_path = Files::GetTemporaryDirectory().ToString(); settings()->SetCustomSavePathAsync(save_path, [&]() { notification.Notify(); }); Flush();