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