| 6 |
| 7 | #include "base/files/file_util.h" |
| 8 | #include "base/logging.h" |
| 9 | #include "base/macros.h" |
| 10 |
| 11 | namespace base { |
| 12 |
| 13 | namespace { |
| 14 |
| 15 | constexpr FilePath::CharType kScopedDirPrefix[] = |
| 16 | FILE_PATH_LITERAL("scoped_dir"); |
| 17 |
| 18 | } // namespace |
| 19 |
| 20 | ScopedTempDir::ScopedTempDir() = default; |
| 21 |
| 22 | ScopedTempDir::ScopedTempDir(ScopedTempDir&& other) noexcept |
| 23 | : path_(other.Take()) {} |
| 24 |
| 25 | ScopedTempDir& ScopedTempDir::operator=(ScopedTempDir&& other) { |
| 26 | if (!path_.empty() && !Delete()) |
| 27 | DLOG(WARNING) << "Could not delete temp dir in operator=()."; |
| 28 | path_ = other.Take(); |
| 29 | return *this; |
| 30 | } |
| 31 |
| 32 | ScopedTempDir::~ScopedTempDir() { |
| 33 | if (!path_.empty() && !Delete()) |
| 34 | DLOG(WARNING) << "Could not delete temp dir in dtor."; |
| 35 | } |
| 36 |
| 37 | bool ScopedTempDir::CreateUniqueTempDir() { |
| 38 | if (!path_.empty()) |
| 39 | return false; |
| 40 |
| 41 | // This "scoped_dir" prefix is only used on Windows and serves as a template |
| 42 | // for the unique name. |
| 43 | if (!CreateNewTempDirectory(kScopedDirPrefix, &path_)) |
| 44 | return false; |
| 45 |
| 46 | return true; |
| 47 | } |
| 48 |
| 49 | bool ScopedTempDir::CreateUniqueTempDirUnderPath(const FilePath& base_path) { |
| 50 | if (!path_.empty()) |
| 51 | return false; |
| 52 |
| 53 | // If |base_path| does not exist, create it. |
| 54 | if (!CreateDirectory(base_path)) |
| 55 | return false; |
| 56 |
| 57 | // Create a new, uniquely named directory under |base_path|. |
| 58 | if (!CreateTemporaryDirInDir(base_path, kScopedDirPrefix, &path_)) |
| 59 | return false; |
| 60 |
| 61 | return true; |
| 62 | } |
| 63 |
| 64 | bool ScopedTempDir::Set(const FilePath& path) { |
| 65 | if (!path_.empty()) |
| 66 | return false; |
| 67 |
| 68 | if (!DirectoryExists(path) && !CreateDirectory(path)) |
| 69 | return false; |
| 70 |
| 71 | path_ = path; |
| 72 | return true; |
| 73 | } |
| 74 |
| 75 | bool ScopedTempDir::Delete() { |
| 76 | if (path_.empty()) |
| 77 | return false; |
| 78 |
| 79 | bool ret = DeleteFileRecursively(path_); |
| 80 | if (ret) { |
| 81 | // We only clear the path if deleted the directory. |
| 82 | path_.clear(); |
| 83 | } |
| 84 |
| 85 | return ret; |
| 86 | } |
| 87 |
| 88 | FilePath ScopedTempDir::Take() { |
| 89 | return std::exchange(path_, FilePath()); |
| 90 | } |
| 91 |
| 92 | const FilePath& ScopedTempDir::GetPath() const { |
| 93 | DCHECK(!path_.empty()) << "Did you call CreateUniqueTempDir* before?"; |
| 94 | return path_; |
| 95 | } |
| 96 |
| 97 | bool ScopedTempDir::IsValid() const { |
| 98 | return !path_.empty() && DirectoryExists(path_); |
| 99 | } |
| 100 |
| 101 | // static |
| 102 | const FilePath::CharType* ScopedTempDir::GetTempDirPrefix() { |
| 103 | return kScopedDirPrefix; |
| 104 | } |
| 105 |
| 106 | } // namespace base |
| 107 |