Debian Codegraph @

src/dmlc-core/include/dmlc/filesystem.h

raw symbols SCIP
1 /*!
2 * Copyright (c) 2018 by Contributors
3 * \file filesystem.h
4 * \brief Utilities to manipulate files
5 * \author Hyunsu Philip Cho
6 */
7 #ifndef DMLC_FILESYSTEM_H_
8 #define DMLC_FILESYSTEM_H_
9
10 #include <algorithm>
11 #include <random>
12 #include <string>
13 #include <vector>
14
15 #include <dmlc/io.h>
16 #include <dmlc/logging.h>
17
18 /* platform specific headers */
19 #ifdef _WIN32
20 #define NOMINMAX
21 #include <shlwapi.h>
22 #include <windows.h>
23 #pragma comment(lib, "shlwapi.lib")
24 #else // _WIN32
25 #include <sys/stat.h>
26 #include <sys/types.h>
27 #include <unistd.h>
28 #endif // _WIN32
29
30 namespace dmlc {
31
32 /*!
33 * \brief Manager class for temporary directories. Whenever a new
34 * TemporaryDirectory object is constructed, a temporary directory is
35 * created. The directory is deleted when the object is deleted or goes
36 * out of scope. Note: no symbolic links are allowed inside the
37 * temporary directory.
38 *
39 * Usage example:
40 * \code
41 *
42 * void foo() {
43 * dmlc::TemporaryDirectory tempdir;
44 * // Create a file my_file.txt inside the temporary directory
45 * std::ofstream of(tempdir.path + "/my_file.txt");
46 * // ... write to my_file.txt ...
47 *
48 * // ... use my_file.txt
49 *
50 * // When tempdir goes out of scope, the temporary directory is deleted
51 * }
52 *
53 * \endcode
54 */
55 class TemporaryDirectory {
56 public:
57 /*!
58 * \brief Default constructor.
59 * Creates a new temporary directory with a unique name.
60 * \param verbose whether to emit extra messages
61 */
62 explicit TemporaryDirectory(bool verbose = false) : verbose_(verbose) {
63 #if _WIN32
64 /* locate the root directory of temporary area */
65 char tmproot[MAX_PATH] = {0};
66 const DWORD dw_retval = GetTempPathA(MAX_PATH, tmproot);
67 if (dw_retval > MAX_PATH || dw_retval == 0) {
68 LOG(FATAL) << "TemporaryDirectory(): "
69 << "Could not create temporary directory";
70 }
71 /* generate a unique 8-letter alphanumeric string */
72 const std::string letters = "abcdefghijklmnopqrstuvwxyz0123456789_";
73 std::string uniqstr(8, '\0');
74 std::random_device rd;
75 std::mt19937 gen(rd());
76 std::uniform_int_distribution<int> dis(0, letters.length() - 1);
77 std::generate(uniqstr.begin(), uniqstr.end(),
78 [&dis, &gen, &letters]() -> char { return letters[dis(gen)]; });
79 /* combine paths to get the name of the temporary directory */
80 char tmpdir[MAX_PATH] = {0};
81 PathCombineA(tmpdir, tmproot, uniqstr.c_str());
82 if (!CreateDirectoryA(tmpdir, NULL)) {
83 LOG(FATAL) << "TemporaryDirectory(): "
84 << "Could not create temporary directory";
85 }
86 path = std::string(tmpdir);
87 #else // _WIN32
88 std::string tmproot; /* root directory of temporary area */
89 std::string dirtemplate; /* template for temporary directory name */
90 /* Get TMPDIR env variable or fall back to /tmp/ */
91 {
92 const char *tmpenv = getenv("TMPDIR");
93 if (tmpenv) {
94 tmproot = std::string(tmpenv);
95 // strip trailing forward slashes
96 while (tmproot.length() != 0 && tmproot[tmproot.length() - 1] == '/') {
97 tmproot.resize(tmproot.length() - 1);
98 }
99 } else {
100 tmproot = "/tmp";
101 }
102 }
103 dirtemplate = tmproot + "/tmpdir.XXXXXX";
104 std::vector<char> dirtemplate_buf(dirtemplate.begin(), dirtemplate.end());
105 dirtemplate_buf.push_back('\0');
106 char *tmpdir = mkdtemp(&dirtemplate_buf[0]);
107 if (!tmpdir) {
108 LOG(FATAL) << "TemporaryDirectory(): "
109 << "Could not create temporary directory";
110 }
111 path = std::string(tmpdir);
112 #endif // _WIN32
113 if (verbose_) {
114 LOG(INFO) << "Created temporary directory " << path;
115 }
116 }
117
118 /*! \brief Destructor. Will perform recursive deletion via RecursiveDelete() */
119 ~TemporaryDirectory() {
120 RecursiveDelete(path);
121 }
122
123 /*! \brief Full path of the temporary directory */
124 std::string path;
125
126 private:
127 /*! \brief Whether to emit extra messages */
128 bool verbose_;
129
130 /*!
131 * \brief Determine whether a given path is a symbolic link
132 * \param path String representation of path
133 */
134 inline bool IsSymlink(const std::string &path) {
135 #ifdef _WIN32
136 DWORD attr = GetFileAttributesA(path.c_str());
137 CHECK_NE(attr, INVALID_FILE_ATTRIBUTES)
138 << "dmlc::TemporaryDirectory::IsSymlink(): Unable to read file attributes";
139 return attr & FILE_ATTRIBUTE_REPARSE_POINT;
140 #else // _WIN32
141 struct stat sb;
142 CHECK_EQ(lstat(path.c_str(), &sb), 0)
143 << "dmlc::TemporaryDirectory::IsSymlink(): Unable to read file attributes";
144 return S_ISLNK(sb.st_mode);
145 #endif // _WIN32
146 }
147
148 /*!
149 * \brief Delete a directory recursively, along with sub-directories and files.
150 * \param path String representation of path. It must refer to a directory.
151 */
152 void RecursiveDelete(const std::string &path);
153 };
154
155 } // namespace dmlc
156 #endif // DMLC_FILESYSTEM_H_