]> git.mxchange.org Git - simgear.git/blob - simgear/misc/sg_dir.cxx
simgear::Dir helpers
[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 #include <math.h>
27 #include <stdlib.h>
28 #include <cstdio>
29
30 #ifdef _WIN32
31 #  define WIN32_LEAN_AND_MEAN
32 #  include <windows.h>
33 #  include <direct.h>
34 #else
35 #  include <sys/types.h>
36 #  include <dirent.h>
37 #  include <sys/stat.h>
38 #  include <unistd.h>
39 #  include <errno.h>
40 #endif
41
42 #include <simgear/debug/logstream.hxx>
43 #include <boost/foreach.hpp>
44
45 #include <cstring>
46 #include <cstdlib>
47 #include <iostream>
48 #include <algorithm> // for std::sort
49
50 using std::string;
51
52 namespace simgear
53 {
54
55 Dir::Dir() :
56     _removeOnDestroy(false)
57 {
58 }
59
60 Dir::Dir(const SGPath& path) :
61   _path(path),
62   _removeOnDestroy(false)
63 {
64     _path.set_cached(false); // disable caching, so create/remove work
65 }
66
67 Dir::Dir(const Dir& rel, const SGPath& relPath) :
68   _path(rel.file(relPath.str())),
69   _removeOnDestroy(false)
70 {
71     _path.set_cached(false); // disable caching, so create/remove work
72 }
73
74 Dir::~Dir()
75 {
76     if (_removeOnDestroy) {
77         remove(true);
78     }
79 }
80
81 void Dir::setRemoveOnDestroy()
82 {
83     _removeOnDestroy = true;
84 }
85
86 Dir Dir::current()
87 {
88 #ifdef _WIN32
89     char* buf = _getcwd(NULL, 0);
90 #else
91     char* buf = ::getcwd(NULL, 0);
92 #endif
93     SGPath p(buf);
94     free(buf);
95     return Dir(p);
96 }
97
98 Dir Dir::tempDir(const std::string& templ)
99 {
100 #ifdef HAVE_MKDTEMP
101     char buf[1024];
102     const char* tempPath = ::getenv("TMPDIR");
103     if (!tempPath) {
104         tempPath = "/tmp";
105     }
106     SGPath p(tempPath);
107     p.append(templ);
108     // Mac OS-X / BSD manual says any number of 'X's, but GLibc manual
109     // says exactly six, so that's what I'm going with
110     p.concat("-XXXXXX");
111     ::snprintf(buf, 1024, "%s", p.c_str());
112     if (!mkdtemp(buf)) {
113         SG_LOG(SG_IO, SG_WARN, "mkdtemp failed:" << strerror(errno));
114         return Dir();
115     }
116     
117     return Dir(SGPath(buf));
118 #else
119     SGPath p(tempnam(0, templ.c_str()));
120     Dir t(p);
121     if (!t.create(0700)) {
122         SG_LOG(SG_IO, SG_WARN, "failed to create temporary directory at " << p.str());
123     }
124     
125     return t;
126 #endif
127 }
128
129 static bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
130 {
131   return p1.file() < p2.file();
132 }
133
134 PathList Dir::children(int types, const std::string& nameFilter) const
135 {
136   PathList result;
137   if (types == 0) {
138     types = TYPE_FILE | TYPE_DIR | NO_DOT_OR_DOTDOT;
139   }
140   
141 #ifdef _WIN32
142   std::string search(_path.str());
143   if (nameFilter.empty()) {
144     search += "\\*"; // everything
145   } else {
146     search += "\\*" + nameFilter;
147   }
148   
149   WIN32_FIND_DATA fData;
150   HANDLE find = FindFirstFile(search.c_str(), &fData);
151   if (find == INVALID_HANDLE_VALUE) {
152     SG_LOG(SG_GENERAL, SG_WARN, "Dir::children: FindFirstFile failed:" << _path.str());
153     return result;
154   }
155   
156   bool done = false;
157   for (bool done = false; !done; done = (FindNextFile(find, &fData) == 0)) {
158     if (fData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
159       if (!(types & INCLUDE_HIDDEN)) {
160         continue;
161       }
162     }
163     
164     if (fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
165           if (types & NO_DOT_OR_DOTDOT) {
166                 if (!strcmp(fData.cFileName,".") || !strcmp(fData.cFileName,"..")) {
167                   continue;
168                 }
169           }
170
171       if (!(types & TYPE_DIR)) {
172         continue;
173       }
174         } else if ((fData.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) ||
175                                 (fData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
176         {
177                 continue; // always ignore device files
178     } else if (!(types & TYPE_FILE)) {
179        continue;
180     }
181
182     result.push_back(file(fData.cFileName));
183   }
184
185   FindClose(find);
186 #else
187   DIR* dp = opendir(_path.c_str());
188   if (!dp) {
189     SG_LOG(SG_GENERAL, SG_WARN, "Dir::children: opendir failed:" << _path.str());
190     return result;
191   }
192   
193   int filterLen = nameFilter.size();
194   
195   while (true) {
196     struct dirent* entry = readdir(dp);
197     if (!entry) {
198       break; // done iteration
199     }
200     
201     // skip hidden files (names beginning with '.') unless requested
202     if (!(types & INCLUDE_HIDDEN) && (entry->d_name[0] == '.') &&
203          strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")) {
204       continue;
205     }
206     
207     SGPath f = file(entry->d_name);
208     if (!f.exists()) {
209       continue; // stat() failed
210     }
211     
212     if (f.isDir()) {
213       // directory handling
214       if (!(types & TYPE_DIR)) {
215         continue;
216       }
217       
218       if (types & NO_DOT_OR_DOTDOT) {
219         if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
220           continue;
221         }
222       }
223     } else if (f.isFile()) {
224       // regular file handling
225       if (!(types & TYPE_FILE)) {
226         continue;
227       }
228     } else {
229       // block device /fifo/char file, ignore
230       continue;
231     }
232
233     if (!nameFilter.empty()) {
234       int nameLen = strlen(entry->d_name);
235       if (nameLen < filterLen) {
236         continue; // name is shorter than the filter
237       }
238     
239       char* nameSuffix = entry->d_name + (nameLen - filterLen);
240       if (strcmp(nameSuffix, nameFilter.c_str())) {
241         continue;
242       }
243     }
244     
245   // passed all criteria, add to our result vector
246     result.push_back(file(entry->d_name));
247   }
248   
249   closedir(dp);
250 #endif
251
252   // File system order is random. Make things deterministic,
253   // so it's the same for every user.
254   std::sort(result.begin(), result.end(), pathSortPredicate);
255
256   return result;
257 }
258
259 bool Dir::isEmpty() const
260 {
261   bool empty= true;
262 #ifdef _WIN32 
263   WIN32_FIND_DATA fData;
264   HANDLE find = FindFirstFile("\\*", &fData);
265   if (find == INVALID_HANDLE_VALUE) {
266     return true;
267   }
268   
269 // since an empty dir will still have . and .. children, we need
270 // watch for those - anything else means the dir is really non-empty
271   bool done = false;
272   for (; !done; done = (FindNextFile(find, &fData) == 0)) {
273     if (fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
274                   if (!strcmp(fData.cFileName,".") || !strcmp(fData.cFileName,"..")) {
275                     continue;
276                   }
277           }
278     
279     empty = false;
280     break;
281   }
282     
283   FindClose(find);
284 #else
285   DIR* dp = opendir(_path.c_str());
286   if (!dp) {
287     return true;
288   }
289     
290   while (true) {
291     struct dirent* entry = readdir(dp);
292     if (!entry) {
293       break; // done iteration
294     }
295     
296     if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
297       continue;
298     }
299       
300     empty = false;
301     break;
302   }
303   closedir(dp);
304 #endif
305   return empty;
306 }
307
308 bool Dir::exists() const
309 {
310   return _path.isDir();
311 }
312
313 SGPath Dir::file(const std::string& name) const
314 {
315   SGPath childPath = _path;
316   childPath.set_cached(true);
317   childPath.append(name);
318   return childPath;  
319 }
320
321 #ifdef _WIN32
322 #  define sgMkDir(d,m)       _mkdir(d)
323 #else
324 #  define sgMkDir(d,m)       mkdir(d,m)
325 #endif
326
327 bool Dir::create(mode_t mode)
328 {
329     if (exists()) {
330         return false; // already exists
331     }
332     
333 // recursively create parent directories
334     Dir pr(parent());
335     if (!pr.path().isNull() && !pr.exists()) {
336         bool ok = pr.create(mode);
337         if (!ok) {
338             return false;
339         }
340     }
341     
342 // finally, create ourselves
343     int err = sgMkDir(_path.c_str(), mode);
344     if (err) {
345         SG_LOG(SG_IO, SG_WARN,  "directory creation failed: (" << _path.str() << ") " << strerror(errno) );
346     }
347     
348     return (err == 0);
349 }
350
351 bool Dir::removeChildren() const
352 {
353     bool ok;
354     PathList cs = children(NO_DOT_OR_DOTDOT | INCLUDE_HIDDEN | TYPE_FILE | TYPE_DIR);
355     BOOST_FOREACH(SGPath path, cs) {
356         if (path.isDir()) {
357             Dir childDir(path);
358             ok = childDir.remove(true);
359         } else {
360             ok = path.remove();
361         }
362         
363         if (!ok) {
364             SG_LOG(SG_IO, SG_WARN, "failed to remove:" << path);
365             return false;
366         }
367     } // of child iteration
368     
369     return true;
370 }
371
372 bool Dir::remove(bool recursive)
373 {
374     if (!exists()) {
375         SG_LOG(SG_IO, SG_WARN, "attempt to remove non-existant dir:" << _path);
376         return false;
377     }
378     
379     if (recursive) {
380         if (!removeChildren()) {
381             return false;
382         }
383     } // of recursive deletion
384     
385 #ifdef _WIN32
386     int err = _rmdir(_path.c_str());
387 #else
388     int err = rmdir(_path.c_str());
389 #endif
390     if (err) {
391         SG_LOG(SG_IO, SG_WARN, "rmdir failed:" << _path.str() << ":" << strerror(errno));
392     }
393     return (err == 0);
394 }
395
396 Dir Dir::parent() const
397 {
398     return Dir(_path.dir());
399 }
400
401 } // of namespace simgear