scoped_temp_dir.h 2.5 KB

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