Consistency in namespace-closing comments
[folly.git] / folly / experimental / TestUtil.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <folly/experimental/TestUtil.h>
18
19 #include <sys/stat.h>
20 #include <sys/types.h>
21
22 #include <boost/regex.hpp>
23
24 #include <folly/Exception.h>
25 #include <folly/File.h>
26 #include <folly/FileUtil.h>
27 #include <folly/Memory.h>
28 #include <folly/String.h>
29 #include <folly/portability/Fcntl.h>
30
31 #ifdef _WIN32
32 #include <crtdbg.h> // @manual
33 #endif
34
35 namespace folly {
36 namespace test {
37
38 namespace {
39
40 fs::path generateUniquePath(fs::path path, StringPiece namePrefix) {
41   if (path.empty()) {
42     path = fs::temp_directory_path();
43   }
44   if (namePrefix.empty()) {
45     path /= fs::unique_path();
46   } else {
47     path /= fs::unique_path(
48         to<std::string>(namePrefix, ".%%%%-%%%%-%%%%-%%%%"));
49   }
50   return path;
51 }
52
53 } // namespace
54
55 TemporaryFile::TemporaryFile(StringPiece namePrefix,
56                              fs::path dir,
57                              Scope scope,
58                              bool closeOnDestruction)
59   : scope_(scope),
60     closeOnDestruction_(closeOnDestruction),
61     fd_(-1),
62     path_(generateUniquePath(std::move(dir), namePrefix)) {
63   fd_ = open(path_.string().c_str(), O_RDWR | O_CREAT | O_EXCL, 0666);
64   checkUnixError(fd_, "open failed");
65
66   if (scope_ == Scope::UNLINK_IMMEDIATELY) {
67     boost::system::error_code ec;
68     fs::remove(path_, ec);
69     if (ec) {
70       LOG(WARNING) << "unlink on construction failed: " << ec;
71     } else {
72       path_.clear();
73     }
74   }
75 }
76
77 void TemporaryFile::close() {
78   if (::close(fd_) == -1) {
79     PLOG(ERROR) << "close failed";
80   }
81   fd_ = -1;
82 }
83
84 const fs::path& TemporaryFile::path() const {
85   CHECK(scope_ != Scope::UNLINK_IMMEDIATELY);
86   DCHECK(!path_.empty());
87   return path_;
88 }
89
90 TemporaryFile::~TemporaryFile() {
91   if (fd_ != -1 && closeOnDestruction_) {
92     if (::close(fd_) == -1) {
93       PLOG(ERROR) << "close failed";
94     }
95   }
96
97   // If we previously failed to unlink() (UNLINK_IMMEDIATELY), we'll
98   // try again here.
99   if (scope_ != Scope::PERMANENT && !path_.empty()) {
100     boost::system::error_code ec;
101     fs::remove(path_, ec);
102     if (ec) {
103       LOG(WARNING) << "unlink on destruction failed: " << ec;
104     }
105   }
106 }
107
108 TemporaryDirectory::TemporaryDirectory(
109     StringPiece namePrefix,
110     fs::path dir,
111     Scope scope)
112     : scope_(scope),
113       path_(std::make_unique<fs::path>(
114           generateUniquePath(std::move(dir), namePrefix))) {
115   fs::create_directory(path());
116 }
117
118 TemporaryDirectory::~TemporaryDirectory() {
119   if (scope_ == Scope::DELETE_ON_DESTRUCTION && path_ != nullptr) {
120     boost::system::error_code ec;
121     fs::remove_all(path(), ec);
122     if (ec) {
123       LOG(WARNING) << "recursive delete on destruction failed: " << ec;
124     }
125   }
126 }
127
128 ChangeToTempDir::ChangeToTempDir() : initialPath_(fs::current_path()) {
129   std::string p = dir_.path().string();
130   ::chdir(p.c_str());
131 }
132
133 ChangeToTempDir::~ChangeToTempDir() {
134   std::string p = initialPath_.string();
135   ::chdir(p.c_str());
136 }
137
138 namespace detail {
139
140 SavedState disableInvalidParameters() {
141 #ifdef _WIN32
142   SavedState ret;
143   ret.previousThreadLocalHandler = _set_thread_local_invalid_parameter_handler(
144       [](const wchar_t*,
145          const wchar_t*,
146          const wchar_t*,
147          unsigned int,
148          uintptr_t) {});
149   ret.previousCrtReportMode = _CrtSetReportMode(_CRT_ASSERT, 0);
150   return ret;
151 #else
152   return SavedState();
153 #endif
154 }
155
156 #ifdef _WIN32
157 void enableInvalidParameters(SavedState state) {
158   _set_thread_local_invalid_parameter_handler(
159       (_invalid_parameter_handler)state.previousThreadLocalHandler);
160   _CrtSetReportMode(_CRT_ASSERT, state.previousCrtReportMode);
161 }
162 #else
163 void enableInvalidParameters(SavedState) {}
164 #endif
165
166 bool hasPCREPatternMatch(StringPiece pattern, StringPiece target) {
167   return boost::regex_match(
168     target.begin(),
169     target.end(),
170     boost::regex(pattern.begin(), pattern.end())
171   );
172 }
173
174 bool hasNoPCREPatternMatch(StringPiece pattern, StringPiece target) {
175   return !hasPCREPatternMatch(pattern, target);
176 }
177
178 } // namespace detail
179
180 CaptureFD::CaptureFD(int fd, ChunkCob chunk_cob)
181     : chunkCob_(std::move(chunk_cob)), fd_(fd), readOffset_(0) {
182   oldFDCopy_ = dup(fd_);
183   PCHECK(oldFDCopy_ != -1) << "Could not copy FD " << fd_;
184
185   int file_fd = open(file_.path().string().c_str(), O_WRONLY|O_CREAT, 0600);
186   PCHECK(dup2(file_fd, fd_) != -1) << "Could not replace FD " << fd_
187     << " with " << file_fd;
188   PCHECK(close(file_fd) != -1) << "Could not close " << file_fd;
189 }
190
191 void CaptureFD::release() {
192   if (oldFDCopy_ != fd_) {
193     readIncremental();  // Feed chunkCob_
194     PCHECK(dup2(oldFDCopy_, fd_) != -1) << "Could not restore old FD "
195       << oldFDCopy_ << " into " << fd_;
196     PCHECK(close(oldFDCopy_) != -1) << "Could not close " << oldFDCopy_;
197     oldFDCopy_ = fd_;  // Make this call idempotent
198   }
199 }
200
201 CaptureFD::~CaptureFD() {
202   release();
203 }
204
205 std::string CaptureFD::read() const {
206   std::string contents;
207   std::string filename = file_.path().string();
208   PCHECK(folly::readFile(filename.c_str(), contents));
209   return contents;
210 }
211
212 std::string CaptureFD::readIncremental() {
213   std::string filename = file_.path().string();
214   // Yes, I know that I could just keep the file open instead. So sue me.
215   folly::File f(openNoInt(filename.c_str(), O_RDONLY), true);
216   auto size = size_t(lseek(f.fd(), 0, SEEK_END) - readOffset_);
217   std::unique_ptr<char[]> buf(new char[size]);
218   auto bytes_read = folly::preadFull(f.fd(), buf.get(), size, readOffset_);
219   PCHECK(ssize_t(size) == bytes_read);
220   readOffset_ += off_t(size);
221   chunkCob_(StringPiece(buf.get(), buf.get() + size));
222   return std::string(buf.get(), size);
223 }
224
225 } // namespace test
226 } // namespace folly