Fix files.cc.

PiperOrigin-RevId: 764926334
This commit is contained in:
Francis Tsui
2025-05-29 16:17:09 -07:00
committed by Copybara-Service
parent 20fcca4e95
commit 09cdc14fb6
21 changed files with 193 additions and 203 deletions
+1
View File
@@ -120,6 +120,7 @@ cc_test(
"files_test.cc",
],
deps = [
":file_path",
":files",
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_googletest//:gtest_main",
+2
View File
@@ -77,6 +77,8 @@ class FilePath {
private:
std::filesystem::path path_;
friend class Files;
};
} // namespace nearby
+33 -33
View File
@@ -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<uintmax_t> GetFileSize(const std::filesystem::path& path) {
std::optional<uintmax_t> 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<uintmax_t>(-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<FilePath> 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<size_t> GetAvailableDiskSpaceInBytes(const FilePath& path) {
std::optional<size_t> 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
+44 -38
View File
@@ -17,60 +17,66 @@
#include <cstddef>
#include <cstdint>
#include <filesystem> // NOLINT(build/c++17)
#include <optional>
#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<uintmax_t> 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<uintmax_t> 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<FilePath> 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<size_t> 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<size_t> GetAvailableDiskSpaceInBytes(
const FilePath& path);
};
} // namespace nearby::sharing
} // namespace nearby
#endif // THIRD_PARTY_NEARBY_INTERNAL_BASE_FILES_H_
+16 -13
View File
@@ -21,28 +21,31 @@
#include <optional>
#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<uintmax_t> size = GetFileSize(target);
std::optional<uintmax_t> 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
+7 -10
View File
@@ -18,16 +18,16 @@
#include <functional>
#include <optional>
#include <string>
#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<std::string> device_name =
device_info_impl_->GetOsDeviceName();
std::optional<std::string> 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<size_t> DeviceInfoImpl::GetAvailableDiskSpaceInBytes(
const FilePath& path) const {
return nearby::sharing::GetAvailableDiskSpaceInBytes(path);
return Files::GetAvailableDiskSpaceInBytes(path);
}
bool DeviceInfoImpl::IsScreenLocked() const {
@@ -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",
@@ -45,13 +45,13 @@ class DeviceInfo : public api::DeviceInfo {
}
std::optional<FilePath> GetDownloadPath() const override {
return nearby::sharing::GetTemporaryDirectory();
return Files::GetTemporaryDirectory();
}
std::optional<FilePath> 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<FilePath> GetCommonAppDataPath() const override {
return nearby::sharing::GetTemporaryDirectory();
return Files::GetTemporaryDirectory();
}
std::optional<FilePath> GetTemporaryPath() const override {
return nearby::sharing::GetTemporaryDirectory();
return Files::GetTemporaryDirectory();
}
std::optional<FilePath> GetLogPath() const override {
return nearby::sharing::GetTemporaryDirectory();
return Files::GetTemporaryDirectory();
}
std::optional<FilePath> GetCrashDumpPath() const override {
return nearby::sharing::GetTemporaryDirectory();
return Files::GetTemporaryDirectory();
}
bool IsScreenLocked() const override { return false; }
@@ -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<OutputFile> ImplementationPlatform::CreateOutputFile(
std::unique_ptr<OutputFile> 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;
}
}
@@ -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<FilePath> DeviceInfo::GetCommonAppDataPath() const {
}
std::optional<FilePath> DeviceInfo::GetTemporaryPath() const {
return nearby::sharing::GetTemporaryDirectory();
return Files::GetTemporaryDirectory();
}
std::optional<FilePath> DeviceInfo::GetLogPath() const {
@@ -186,5 +185,4 @@ bool DeviceInfo::AllowSleep() {
return session_manager_.AllowSleep();
}
} // namespace windows
} // namespace nearby
} // namespace nearby::windows
@@ -220,8 +220,8 @@ std::unique_ptr<OutputFile> 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;
@@ -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<T> PreferencesManager::GetArrayValue(
return result;
}
} // namespace windows
} // namespace nearby
} // namespace nearby::windows
@@ -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<json> 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<json> 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.";
}
+3 -6
View File
@@ -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<std::wstring, size_t> available_space_map_;
absl::flat_hash_map<std::string,
std::function<void(api::DeviceInfo::ScreenStatus)>>
+12 -16
View File
@@ -15,7 +15,6 @@
#include "internal/test/fake_device_info.h"
#include <functional>
#include <optional>
#include "gtest/gtest.h"
#include "internal/base/file_path.h"
@@ -25,12 +24,6 @@
namespace nearby {
namespace {
FilePath GetTempDir() {
std::optional<FilePath> 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) {
+12 -12
View File
@@ -388,7 +388,7 @@ class NearbyConnectionsManagerImplTest : public testing::Test {
const std::vector<uint8_t> 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<uint8_t> 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<testing::NiceMock<MockPayloadStatusListener>>();
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<FilePath> unknown_file_paths =
+2 -2
View File
@@ -413,7 +413,7 @@ struct Payload {
id = std::hash<std::string>()(file.path.ToString());
content.type = PayloadContent::Type::kFile;
std::optional<uintmax_t> size = GetFileSize(file.path.GetPath());
std::optional<uintmax_t> 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<uintmax_t> size = GetFileSize(file.path.GetPath());
std::optional<uintmax_t> size = Files::GetFileSize(file.path);
if (size.has_value()) {
content.file_payload.size = *size;
}
+4 -4
View File
@@ -42,7 +42,7 @@ std::vector<NearbyFileHandler::FileInfo> DoOpenFiles(
absl::Span<const FilePath> file_paths) {
std::vector<NearbyFileHandler::FileInfo> files;
for (const auto& file_path : file_paths) {
std::optional<uintmax_t> size = GetFileSize(file_path.GetPath());
std::optional<uintmax_t> 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();
+23 -23
View File
@@ -45,8 +45,8 @@ TEST(NearbyFileHandler, OpenFiles) {
NearbyFileHandler nearby_file_handler(mock_platform);
absl::Notification notification;
std::vector<NearbyFileHandler::FileInfo> 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<FilePath> 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<FilePath> 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<FilePath> 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
+6 -11
View File
@@ -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<FilePath> 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<Payload> 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<Payload>(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<uint8_t>& 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) {
+1 -1
View File
@@ -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();