• 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 #ifndef SRC_BASE_TEST_TMP_DIR_TREE_H_
18 #define SRC_BASE_TEST_TMP_DIR_TREE_H_
19 
20 #include <stack>
21 #include <string>
22 
23 #include "perfetto/ext/base/temp_file.h"
24 
25 namespace perfetto {
26 namespace base {
27 
28 // Helper to construct and automatically destroy temporary file hierarchies in
29 // tests.
30 class TmpDirTree {
31  public:
32   TmpDirTree();
33   virtual ~TmpDirTree();
34 
35   // Returns the absolute path where the temporary hierarchy is located.
path()36   const std::string& path() const { return tmp_dir_.path(); }
37 
38   // Prepends `path()` to `relative_path` (making it an absolute path).
39   std::string AbsolutePath(const std::string& relative_path) const;
40 
41   // Creates a directory at `relative_path`. All the parent directories should
42   // have been created. PERFETTO_CHECK()s that the operation succeeds.
43   void AddDir(const std::string& relative_path);
44 
45   // Creates a file at `relative_path` which contains `content`. All the parent
46   // directories should have been created. PERFETTO_CHECK()s that the operation
47   // succeeds.
48   void AddFile(const std::string& relative_path, const std::string& content);
49 
50   // Tells this object to remove `relative_path` on destruction. This is used
51   // for files created by the caller that still need to be removed on cleanup by
52   // this object.
53   void TrackFile(const std::string& relative_path);
54 
55  private:
56   TmpDirTree(const TmpDirTree&) = delete;
57   TmpDirTree& operator=(const TmpDirTree&) = delete;
58 
59   base::TempDir tmp_dir_;
60   std::stack<std::string> dirs_to_remove_;
61   std::stack<std::string> files_to_remove_;
62 };
63 
64 }  // namespace base
65 }  // namespace perfetto
66 
67 #endif  // SRC_BASE_TEST_TMP_DIR_TREE_H_
68