xref: /aosp_15_r20/external/cronet/base/files/scoped_temp_dir.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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/files/file_path.h"
22 
23 namespace base {
24 
25 class BASE_EXPORT ScopedTempDir {
26  public:
27   // No directory is owned/created initially.
28   ScopedTempDir();
29 
30   ScopedTempDir(ScopedTempDir&&) noexcept;
31   ScopedTempDir& operator=(ScopedTempDir&&);
32 
33   // Recursively delete path.
34   ~ScopedTempDir();
35 
36   // Creates a unique directory in TempPath, and takes ownership of it.
37   // See file_util::CreateNewTemporaryDirectory.
38   [[nodiscard]] bool CreateUniqueTempDir();
39 
40   // Creates a unique directory under a given path, and takes ownership of it.
41   [[nodiscard]] bool CreateUniqueTempDirUnderPath(const FilePath& path);
42 
43   // Takes ownership of directory at |path|, creating it if necessary.
44   // Don't call multiple times unless Take() has been called first.
45   [[nodiscard]] bool Set(const FilePath& path);
46 
47   // Deletes the temporary directory wrapped by this object.
48   [[nodiscard]] bool Delete();
49 
50   // Caller takes ownership of the temporary directory so it won't be destroyed
51   // when this object goes out of scope.
52   FilePath Take();
53 
54   // Returns the path to the created directory. Call one of the
55   // CreateUniqueTempDir* methods before getting the path.
56   const FilePath& GetPath() const;
57 
58   // Returns true if path_ is non-empty and exists.
59   bool IsValid() const;
60 
61   // Returns the prefix used for temp directory names generated by
62   // ScopedTempDirs.
63   static const FilePath::CharType* GetTempDirPrefix();
64 
65  private:
66   FilePath path_;
67 };
68 
69 }  // namespace base
70 
71 #endif  // BASE_FILES_SCOPED_TEMP_DIR_H_
72