• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021 The Android Open Source Project
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 "src/base/test/tmp_dir_tree.h"
18 
19 #include "perfetto/ext/base/file_utils.h"
20 #include "perfetto/ext/base/scoped_file.h"
21 
22 namespace perfetto {
23 namespace base {
24 
TmpDirTree()25 TmpDirTree::TmpDirTree() : tmp_dir_(base::TempDir::Create()) {}
26 
~TmpDirTree()27 TmpDirTree::~TmpDirTree() {
28   for (; !files_to_remove_.empty(); files_to_remove_.pop()) {
29     PERFETTO_CHECK(remove(AbsolutePath(files_to_remove_.top()).c_str()) == 0);
30   }
31   for (; !dirs_to_remove_.empty(); dirs_to_remove_.pop()) {
32     base::Rmdir(AbsolutePath(dirs_to_remove_.top()));
33   }
34 }
35 
AbsolutePath(const std::string & relative_path) const36 std::string TmpDirTree::AbsolutePath(const std::string& relative_path) const {
37   return path() + "/" + relative_path;
38 }
39 
AddDir(const std::string & relative_path)40 void TmpDirTree::AddDir(const std::string& relative_path) {
41   dirs_to_remove_.push(relative_path);
42   PERFETTO_CHECK(base::Mkdir(AbsolutePath(relative_path)));
43 }
44 
AddFile(const std::string & relative_path,const std::string & content)45 void TmpDirTree::AddFile(const std::string& relative_path,
46                          const std::string& content) {
47   TrackFile(relative_path);
48   base::ScopedFile fd(base::OpenFile(AbsolutePath(relative_path),
49                                      O_WRONLY | O_CREAT | O_TRUNC, 0600));
50   PERFETTO_CHECK(base::WriteAll(fd.get(), content.c_str(), content.size()) ==
51                  static_cast<ssize_t>(content.size()));
52 }
53 
TrackFile(const std::string & relative_path)54 void TmpDirTree::TrackFile(const std::string& relative_path) {
55   files_to_remove_.push(relative_path);
56 }
57 
58 }  // namespace base
59 }  // namespace perfetto
60