Home | History | Annotate | Download | only in files
      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/file_util.h"
      8 #include "base/logging.h"
      9 
     10 namespace base {
     11 
     12 ScopedTempDir::ScopedTempDir() {
     13 }
     14 
     15 ScopedTempDir::~ScopedTempDir() {
     16   if (!path_.empty() && !Delete())
     17     DLOG(WARNING) << "Could not delete temp dir in dtor.";
     18 }
     19 
     20 bool 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 (!file_util::CreateNewTempDirectory(FILE_PATH_LITERAL("scoped_dir"),
     27                                          &path_))
     28     return false;
     29 
     30   return true;
     31 }
     32 
     33 bool ScopedTempDir::CreateUniqueTempDirUnderPath(const FilePath& base_path) {
     34   if (!path_.empty())
     35     return false;
     36 
     37   // If |base_path| does not exist, create it.
     38   if (!file_util::CreateDirectory(base_path))
     39     return false;
     40 
     41   // Create a new, uniquely named directory under |base_path|.
     42   if (!file_util::CreateTemporaryDirInDir(
     43           base_path,
     44           FILE_PATH_LITERAL("scoped_dir_"),
     45           &path_))
     46     return false;
     47 
     48   return true;
     49 }
     50 
     51 bool ScopedTempDir::Set(const FilePath& path) {
     52   if (!path_.empty())
     53     return false;
     54 
     55   if (!DirectoryExists(path) && !file_util::CreateDirectory(path))
     56     return false;
     57 
     58   path_ = path;
     59   return true;
     60 }
     61 
     62 bool ScopedTempDir::Delete() {
     63   if (path_.empty())
     64     return false;
     65 
     66   bool ret = base::DeleteFile(path_, true);
     67   if (ret) {
     68     // We only clear the path if deleted the directory.
     69     path_.clear();
     70   }
     71 
     72   return ret;
     73 }
     74 
     75 FilePath ScopedTempDir::Take() {
     76   FilePath ret = path_;
     77   path_ = FilePath();
     78   return ret;
     79 }
     80 
     81 bool ScopedTempDir::IsValid() const {
     82   return !path_.empty() && DirectoryExists(path_);
     83 }
     84 
     85 }  // namespace base
     86