• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #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()21 ScopedTempDir::~ScopedTempDir() {
22   if (!path_.empty() && !Delete())
23     DLOG(WARNING) << "Could not delete temp dir in dtor.";
24 }
25 
CreateUniqueTempDir()26 bool ScopedTempDir::CreateUniqueTempDir() {
27   if (!path_.empty())
28     return false;
29 
30   // This "scoped_dir" prefix is only used on Windows and serves as a template
31   // for the unique name.
32   if (!base::CreateNewTempDirectory(kScopedDirPrefix, &path_))
33     return false;
34 
35   return true;
36 }
37 
CreateUniqueTempDirUnderPath(const FilePath & base_path)38 bool ScopedTempDir::CreateUniqueTempDirUnderPath(const FilePath& base_path) {
39   if (!path_.empty())
40     return false;
41 
42   // If |base_path| does not exist, create it.
43   if (!base::CreateDirectory(base_path))
44     return false;
45 
46   // Create a new, uniquely named directory under |base_path|.
47   if (!base::CreateTemporaryDirInDir(base_path, kScopedDirPrefix, &path_))
48     return false;
49 
50   return true;
51 }
52 
Set(const FilePath & path)53 bool ScopedTempDir::Set(const FilePath& path) {
54   if (!path_.empty())
55     return false;
56 
57   if (!DirectoryExists(path) && !base::CreateDirectory(path))
58     return false;
59 
60   path_ = path;
61   return true;
62 }
63 
Delete()64 bool ScopedTempDir::Delete() {
65   if (path_.empty())
66     return false;
67 
68   bool ret = base::DeleteFile(path_, true);
69   if (ret) {
70     // We only clear the path if deleted the directory.
71     path_.clear();
72   }
73 
74   return ret;
75 }
76 
Take()77 FilePath ScopedTempDir::Take() {
78   FilePath ret = path_;
79   path_ = FilePath();
80   return ret;
81 }
82 
GetPath() const83 const FilePath& ScopedTempDir::GetPath() const {
84   DCHECK(!path_.empty()) << "Did you call CreateUniqueTempDir* before?";
85   return path_;
86 }
87 
IsValid() const88 bool ScopedTempDir::IsValid() const {
89   return !path_.empty() && DirectoryExists(path_);
90 }
91 
92 // static
GetTempDirPrefix()93 const FilePath::CharType* ScopedTempDir::GetTempDirPrefix() {
94   return kScopedDirPrefix;
95 }
96 
97 }  // namespace base
98