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