1 // Copyright (C) 2022 Google LLC 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #ifndef ICING_FILE_DESTRUCTIBLE_DIRECTORY_H_ 16 #define ICING_FILE_DESTRUCTIBLE_DIRECTORY_H_ 17 18 #include "icing/file/filesystem.h" 19 #include "icing/util/logging.h" 20 21 namespace icing { 22 namespace lib { 23 24 // A convenient RAII class which will recursively create the directory at the 25 // specified file path and delete it upon destruction. 26 class DestructibleDirectory { 27 public: DestructibleDirectory(const Filesystem * filesystem,std::string dir)28 explicit DestructibleDirectory(const Filesystem* filesystem, std::string dir) 29 : filesystem_(filesystem), dir_(std::move(dir)) { 30 is_valid_ = filesystem_->CreateDirectoryRecursively(dir_.c_str()); 31 } 32 33 DestructibleDirectory(const DestructibleDirectory&) = delete; 34 DestructibleDirectory& operator=(const DestructibleDirectory&) = delete; 35 DestructibleDirectory(DestructibleDirectory && rhs)36 DestructibleDirectory(DestructibleDirectory&& rhs) 37 : filesystem_(nullptr), is_valid_(false) { 38 Swap(rhs); 39 } 40 41 DestructibleDirectory& operator=(DestructibleDirectory&& rhs) { 42 Swap(rhs); 43 return *this; 44 } 45 ~DestructibleDirectory()46 ~DestructibleDirectory() { 47 if (filesystem_ != nullptr && 48 !filesystem_->DeleteDirectoryRecursively(dir_.c_str())) { 49 // Swallow deletion failures as there's nothing actionable to do about 50 // them. 51 ICING_LOG(WARNING) << "Unable to delete temporary directory: " << dir_; 52 } 53 } 54 dir()55 const std::string& dir() const { return dir_; } 56 is_valid()57 bool is_valid() const { return is_valid_; } 58 59 private: Swap(DestructibleDirectory & other)60 void Swap(DestructibleDirectory& other) { 61 std::swap(filesystem_, other.filesystem_); 62 std::swap(dir_, other.dir_); 63 std::swap(is_valid_, other.is_valid_); 64 } 65 66 const Filesystem* filesystem_; 67 std::string dir_; 68 bool is_valid_; 69 }; 70 71 } // namespace lib 72 } // namespace icing 73 74 #endif // ICING_FILE_DESTRUCTIBLE_DIRECTORY_H_ 75