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