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