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