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 #ifndef BASE_FILES_SCOPED_TEMP_DIR_H_ 6 #define BASE_FILES_SCOPED_TEMP_DIR_H_ 7 8 // An object representing a temporary / scratch directory that should be 9 // cleaned up (recursively) when this object goes out of scope. Since deletion 10 // occurs during the destructor, no further error handling is possible if the 11 // directory fails to be deleted. As a result, deletion is not guaranteed by 12 // this class. (However note that, whenever possible, by default 13 // CreateUniqueTempDir creates the directory in a location that is 14 // automatically cleaned up on reboot, or at other appropriate times.) 15 // 16 // Multiple calls to the methods which establish a temporary directory 17 // (CreateUniqueTempDir, CreateUniqueTempDirUnderPath, and Set) must have 18 // intervening calls to Delete or Take, or the calls will fail. 19 20 #include "base/base_export.h" 21 #include "base/compiler_specific.h" 22 #include "base/files/file_path.h" 23 24 namespace base { 25 26 class BASE_EXPORT ScopedTempDir { 27 public: 28 // No directory is owned/created initially. 29 ScopedTempDir(); 30 31 ScopedTempDir(ScopedTempDir&&) noexcept; 32 ScopedTempDir& operator=(ScopedTempDir&&); 33 34 // Recursively delete path. 35 ~ScopedTempDir(); 36 37 // Creates a unique directory in TempPath, and takes ownership of it. 38 // See file_util::CreateNewTemporaryDirectory. 39 [[nodiscard]] bool CreateUniqueTempDir(); 40 41 // Creates a unique directory under a given path, and takes ownership of it. 42 [[nodiscard]] bool CreateUniqueTempDirUnderPath(const FilePath& path); 43 44 // Takes ownership of directory at |path|, creating it if necessary. 45 // Don't call multiple times unless Take() has been called first. 46 [[nodiscard]] bool Set(const FilePath& path); 47 48 // Deletes the temporary directory wrapped by this object. 49 [[nodiscard]] bool Delete(); 50 51 // Caller takes ownership of the temporary directory so it won't be destroyed 52 // when this object goes out of scope. 53 FilePath Take(); 54 55 // Returns the path to the created directory. Call one of the 56 // CreateUniqueTempDir* methods before getting the path. 57 const FilePath& GetPath() const LIFETIME_BOUND; 58 59 // Returns true if path_ is non-empty and exists. 60 bool IsValid() const; 61 62 // Returns the prefix used for temp directory names generated by 63 // ScopedTempDirs. 64 static const FilePath::CharType* GetTempDirPrefix(); 65 66 private: 67 FilePath path_; 68 }; 69 70 } // namespace base 71 72 #endif // BASE_FILES_SCOPED_TEMP_DIR_H_ 73