scoped_temp_dir.cc revision ddb351dbec246cf1fab5ec20d2d5520909041de1
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/memory/scoped_temp_dir.h"
6
7#include "base/file_util.h"
8#include "base/logging.h"
9
10ScopedTempDir::ScopedTempDir() {
11}
12
13ScopedTempDir::~ScopedTempDir() {
14  if (!path_.empty() && !Delete())
15    LOG(WARNING) << "Could not delete temp dir in dtor.";
16}
17
18bool ScopedTempDir::CreateUniqueTempDir() {
19  if (!path_.empty())
20    return false;
21
22  // This "scoped_dir" prefix is only used on Windows and serves as a template
23  // for the unique name.
24  if (!file_util::CreateNewTempDirectory(FILE_PATH_LITERAL("scoped_dir"),
25                                         &path_))
26    return false;
27
28  return true;
29}
30
31bool ScopedTempDir::CreateUniqueTempDirUnderPath(const FilePath& base_path) {
32  if (!path_.empty())
33    return false;
34
35  // If |base_path| does not exist, create it.
36  if (!file_util::CreateDirectory(base_path))
37    return false;
38
39  // Create a new, uniquely named directory under |base_path|.
40  if (!file_util::CreateTemporaryDirInDir(
41          base_path,
42          FILE_PATH_LITERAL("scoped_dir_"),
43          &path_))
44    return false;
45
46  return true;
47}
48
49bool ScopedTempDir::Set(const FilePath& path) {
50  if (!path_.empty())
51    return false;
52
53  if (!file_util::DirectoryExists(path) &&
54      !file_util::CreateDirectory(path))
55    return false;
56
57  path_ = path;
58  return true;
59}
60
61bool ScopedTempDir::Delete() {
62  if (path_.empty())
63    return false;
64
65  bool ret = file_util::Delete(path_, true);
66  if (ret) {
67    // We only clear the path if deleted the directory.
68    path_.clear();
69  } else {
70    LOG(ERROR) << "ScopedTempDir unable to delete " << path_.value();
71  }
72
73  return ret;
74}
75
76FilePath ScopedTempDir::Take() {
77  FilePath ret = path_;
78  path_ = FilePath();
79  return ret;
80}
81
82bool ScopedTempDir::IsValid() const {
83  return !path_.empty() && file_util::DirectoryExists(path_);
84}
85