]> git.mxchange.org Git - simgear.git/blob - simgear/misc/sg_dir.cxx
Missing headers
[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::exists() const
260 {
261   return _path.isDir();
262 }
263
264 SGPath Dir::file(const std::string& name) const
265 {
266   SGPath childPath = _path;
267   childPath.set_cached(true);
268   childPath.append(name);
269   return childPath;  
270 }
271
272 #ifdef _WIN32
273 #  define sgMkDir(d,m)       _mkdir(d)
274 #else
275 #  define sgMkDir(d,m)       mkdir(d,m)
276 #endif
277
278 bool Dir::create(mode_t mode)
279 {
280     if (exists()) {
281         return false; // already exists
282     }
283     
284 // recursively create parent directories
285     Dir pr(parent());
286     if (!pr.path().isNull() && !pr.exists()) {
287         bool ok = pr.create(mode);
288         if (!ok) {
289             return false;
290         }
291     }
292     
293 // finally, create ourselves
294     int err = sgMkDir(_path.c_str(), mode);
295     if (err) {
296         SG_LOG(SG_IO, SG_WARN,  "directory creation failed: (" << _path.str() << ") " << strerror(errno) );
297     }
298     
299     return (err == 0);
300 }
301
302 bool Dir::remove(bool recursive)
303 {
304     if (!exists()) {
305         SG_LOG(SG_IO, SG_WARN, "attempt to remove non-existant dir:" << _path.str());
306         return false;
307     }
308     
309     if (recursive) {
310         bool ok;
311         PathList cs = children(NO_DOT_OR_DOTDOT | INCLUDE_HIDDEN | TYPE_FILE | TYPE_DIR);
312         BOOST_FOREACH(SGPath path, cs) {
313             if (path.isDir()) {
314                 Dir childDir(path);
315                 ok = childDir.remove(true);
316             } else {
317                 ok = path.remove();
318             }
319             
320             if (!ok) {
321                 return false;
322             }
323         } // of child iteration
324     } // of recursive deletion
325     
326 #ifdef _WIN32
327     int err = _rmdir(_path.c_str());
328 #else
329     int err = rmdir(_path.c_str());
330 #endif
331     if (err) {
332         SG_LOG(SG_IO, SG_WARN, "rmdir failed:" << _path.str() << ":" << strerror(errno));
333     }
334     return (err == 0);
335 }
336
337 Dir Dir::parent() const
338 {
339     return Dir(_path.dir());
340 }
341
342 } // of namespace simgear