]> git.mxchange.org Git - simgear.git/blob - simgear/misc/sg_dir.cxx
Remove-on-destroy option for simgear::Dir, to help with cleaning up temporary directo...
[simgear.git] / simgear / misc / sg_dir.cxx
1 // Written by James Turner, started July 2010.
2 //
3 // Copyright (C) 2010  Curtis L. Olson - http://www.flightgear.org/~curt
4 //
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Library General Public
7 // License as published by the Free Software Foundation; either
8 // version 2 of the License, or (at your option) any later version.
9 //
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // Library General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18 //
19 // $Id$
20
21 #ifdef HAVE_CONFIG_H
22 #  include <simgear_config.h>
23 #endif
24
25 #include <simgear/misc/sg_dir.hxx>
26
27 #ifdef _WIN32
28 #  define WIN32_LEAN_AND_MEAN
29 #  include <windows.h>
30 #  include <direct.h>
31 #else
32 #  include <sys/types.h>
33 #  include <dirent.h>
34 #  include <sys/stat.h>
35 #  include <unistd.h>
36 #  include <errno.h>
37 #endif
38
39 #include <simgear/debug/logstream.hxx>
40 #include <boost/foreach.hpp>
41
42 #include <cstring>
43 #include <iostream>
44
45 using std::string;
46
47 namespace simgear
48 {
49
50 Dir::Dir() :
51     _removeOnDestroy(false)
52 {
53 }
54
55 Dir::Dir(const SGPath& path) :
56   _path(path),
57   _removeOnDestroy(false)
58 {
59     _path.set_cached(false); // disable caching, so create/remove work
60 }
61
62 Dir::Dir(const Dir& rel, const SGPath& relPath) :
63   _path(rel.file(relPath.str())),
64   _removeOnDestroy(false)
65 {
66     _path.set_cached(false); // disable caching, so create/remove work
67 }
68
69 Dir::~Dir()
70 {
71     if (_removeOnDestroy) {
72         remove(true);
73     }
74 }
75
76 void Dir::setRemoveOnDestroy()
77 {
78     _removeOnDestroy = true;
79 }
80
81 Dir Dir::current()
82 {
83 #ifdef _WIN32
84     char* buf = _getcwd(NULL, 0);
85 #else
86     char* buf = ::getcwd(NULL, 0);
87 #endif
88     SGPath p(buf);
89     free(buf);
90     return Dir(p);
91 }
92
93 Dir Dir::tempDir(const std::string& templ)
94 {
95 #ifdef HAVE_MKDTEMP
96     char buf[1024];
97     const char* tempPath = ::getenv("TMPDIR");
98     if (!tempPath) {
99         tempPath = "/tmp/";
100     }
101     // Mac OS-X / BSD manual says any number of 'X's, but GLibc manual
102     // says exactly six, so that's what I'm going with
103     ::snprintf(buf, 1024, "%s%s-XXXXXX", tempPath, templ.c_str());
104     if (!mkdtemp(buf)) {
105         SG_LOG(SG_IO, SG_WARN, "mkdtemp failed:" << strerror(errno));
106         return Dir();
107     }
108     
109     return Dir(SGPath(buf));
110 #else
111     SGPath p(tempnam(0, templ.c_str()));
112     Dir t(p);
113     if (!t.create(0700)) {
114         SG_LOG(SG_IO, SG_WARN, "failed to create temporary directory at " << p.str());
115     }
116     
117     return t;
118 #endif
119 }
120
121 PathList Dir::children(int types, const std::string& nameFilter) const
122 {
123   PathList result;
124   if (types == 0) {
125     types = TYPE_FILE | TYPE_DIR | NO_DOT_OR_DOTDOT;
126   }
127   
128 #ifdef _WIN32
129   std::string search(_path.str());
130   if (nameFilter.empty()) {
131     search += "\\*"; // everything
132   } else {
133     search += "\\*" + nameFilter;
134   }
135   
136   WIN32_FIND_DATA fData;
137   HANDLE find = FindFirstFile(search.c_str(), &fData);
138   if (find == INVALID_HANDLE_VALUE) {
139     SG_LOG(SG_GENERAL, SG_WARN, "Dir::children: FindFirstFile failed:" << _path.str());
140     return result;
141   }
142   
143   bool done = false;
144   for (bool done = false; !done; done = (FindNextFile(find, &fData) == 0)) {
145     if (fData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
146       if (!(types & INCLUDE_HIDDEN)) {
147         continue;
148       }
149     }
150     
151     if (fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
152           if (types & NO_DOT_OR_DOTDOT) {
153                 if (!strcmp(fData.cFileName,".") || !strcmp(fData.cFileName,"..")) {
154                   continue;
155                 }
156           }
157
158       if (!(types & TYPE_DIR)) {
159         continue;
160       }
161         } else if ((fData.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) ||
162                                 (fData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
163         {
164                 continue; // always ignore device files
165     } else if (!(types & TYPE_FILE)) {
166        continue;
167     }
168
169     result.push_back(file(fData.cFileName));
170   }
171
172   FindClose(find);
173 #else
174   DIR* dp = opendir(_path.c_str());
175   if (!dp) {
176     SG_LOG(SG_GENERAL, SG_WARN, "Dir::children: opendir failed:" << _path.str());
177     return result;
178   }
179   
180   int filterLen = nameFilter.size();
181   
182   while (true) {
183     struct dirent* entry = readdir(dp);
184     if (!entry) {
185       break; // done iteration
186     }
187     
188     // skip hidden files (names beginning with '.') unless requested
189     if (!(types & INCLUDE_HIDDEN) && (entry->d_name[0] == '.') &&
190          strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")) {
191       continue;
192     }
193     
194     SGPath f = file(entry->d_name);
195     if (!f.exists()) {
196       continue; // stat() failed
197     }
198     
199     if (f.isDir()) {
200       // directory handling
201       if (!(types & TYPE_DIR)) {
202         continue;
203       }
204       
205       if (types & NO_DOT_OR_DOTDOT) {
206         if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
207           continue;
208         }
209       }
210     } else if (f.isFile()) {
211       // regular file handling
212       if (!(types & TYPE_FILE)) {
213         continue;
214       }
215     } else {
216       // block device /fifo/char file, ignore
217       continue;
218     }
219
220     if (!nameFilter.empty()) {
221       int nameLen = strlen(entry->d_name);
222       if (nameLen < filterLen) {
223         continue; // name is shorter than the filter
224       }
225     
226       char* nameSuffix = entry->d_name + (nameLen - filterLen);
227       if (strcmp(nameSuffix, nameFilter.c_str())) {
228         continue;
229       }
230     }
231     
232   // passed all criteria, add to our result vector
233     result.push_back(file(entry->d_name));
234   }
235   
236   closedir(dp);
237 #endif
238   return result;
239 }
240
241 bool Dir::exists() const
242 {
243   return _path.isDir();
244 }
245
246 SGPath Dir::file(const std::string& name) const
247 {
248   SGPath childPath = _path;
249   childPath.set_cached(true);
250   childPath.append(name);
251   return childPath;  
252 }
253
254 #ifdef _WIN32
255 #  define sgMkDir(d,m)       _mkdir(d)
256 #else
257 #  define sgMkDir(d,m)       mkdir(d,m)
258 #endif
259
260 bool Dir::create(mode_t mode)
261 {
262     if (exists()) {
263         return false; // already exists
264     }
265     
266 // recursively create parent directories
267     Dir pr(parent());
268     if (!pr.exists()) {
269         bool ok = pr.create(mode);
270         if (!ok) {
271             return false;
272         }
273     }
274     
275 // finally, create ourselves
276     int err = sgMkDir(_path.c_str(), mode);
277     if (err) {
278         SG_LOG(SG_IO, SG_WARN,  "directory creation failed: (" << _path.str() << ") " << strerror(errno) );
279     }
280     
281     return (err == 0);
282 }
283
284 bool Dir::remove(bool recursive)
285 {
286     if (!exists()) {
287         SG_LOG(SG_IO, SG_WARN, "attempt to remove non-existant dir:" << _path.str());
288         return false;
289     }
290     
291     if (recursive) {
292         bool ok;
293         PathList cs = children(NO_DOT_OR_DOTDOT | INCLUDE_HIDDEN | TYPE_FILE | TYPE_DIR);
294         BOOST_FOREACH(SGPath path, cs) {
295             if (path.isDir()) {
296                 Dir childDir(path);
297                 ok = childDir.remove(true);
298             } else {
299                 ok = path.remove();
300             }
301             
302             if (!ok) {
303                 return false;
304             }
305         } // of child iteration
306     } // of recursive deletion
307     
308 #ifdef _WIN32
309     int err = _rmdir(_path.c_str());
310 #else
311     int err = rmdir(_path.c_str());
312 #endif
313     if (err) {
314         SG_LOG(SG_IO, SG_WARN, "rmdir failed:" << _path.str() << ":" << strerror(errno));
315     }
316     return (err == 0);
317 }
318
319 Dir Dir::parent() const
320 {
321     return Dir(_path.dir());
322 }
323
324 } // of namespace simgear