]> git.mxchange.org Git - simgear.git/blob - simgear/misc/sg_dir.cxx
SGPath/Dir extensions to ease file handling in TerraGear. Also a unit-test, shocking.
[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
22 #include <simgear/misc/sg_dir.hxx>
23
24 #ifdef _WIN32
25 #  define WIN32_LEAN_AND_MEAN
26 #  include <windows.h>
27 #  include <direct.h>
28 #else
29 #  include <sys/types.h>
30 #  include <dirent.h>
31 #  include <sys/stat.h>
32 #  include <unistd.h>
33 #  include <errno.h>
34 #endif
35
36 #include <simgear/debug/logstream.hxx>
37 #include <boost/foreach.hpp>
38
39 #include <cstring>
40 #include <iostream>
41
42 using std::string;
43
44 namespace simgear
45 {
46
47 Dir::Dir(const SGPath& path) :
48   _path(path)
49 {
50     _path.set_cached(false); // disable caching, so create/remove work
51 }
52
53 Dir::Dir(const Dir& rel, const SGPath& relPath) :
54   _path(rel.file(relPath.str()))
55 {
56     _path.set_cached(false); // disable caching, so create/remove work
57 }
58
59 Dir Dir::current()
60 {
61 #ifdef _WIN32
62     char* buf = _getcwd(NULL, 0);
63 #else
64     char* buf = ::getcwd(NULL, 0);
65 #endif
66     SGPath p(buf);
67     free(buf);
68     return Dir(p);
69 }
70
71 Dir Dir::tempDir(const std::string& templ)
72 {
73     SGPath p(tempnam(0, templ.c_str()));
74     Dir t(p);
75     if (!t.create(0700)) {
76         SG_LOG(SG_IO, SG_WARN, "failed to create temporary directory at " << p.str());
77     }
78     
79     return t;
80 }
81
82 PathList Dir::children(int types, const std::string& nameFilter) const
83 {
84   PathList result;
85   if (types == 0) {
86     types = TYPE_FILE | TYPE_DIR | NO_DOT_OR_DOTDOT;
87   }
88   
89 #ifdef _WIN32
90   std::string search(_path.str());
91   if (nameFilter.empty()) {
92     search += "\\*"; // everything
93   } else {
94     search += "\\*" + nameFilter;
95   }
96   
97   WIN32_FIND_DATA fData;
98   HANDLE find = FindFirstFile(search.c_str(), &fData);
99   if (find == INVALID_HANDLE_VALUE) {
100     SG_LOG(SG_GENERAL, SG_WARN, "Dir::children: FindFirstFile failed:" << _path.str());
101     return result;
102   }
103   
104   bool done = false;
105   for (bool done = false; !done; done = (FindNextFile(find, &fData) == 0)) {
106     if (fData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
107       if (!(types & INCLUDE_HIDDEN)) {
108         continue;
109       }
110     }
111     
112     if (fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
113           if (types & NO_DOT_OR_DOTDOT) {
114                 if (!strcmp(fData.cFileName,".") || !strcmp(fData.cFileName,"..")) {
115                   continue;
116                 }
117           }
118
119       if (!(types & TYPE_DIR)) {
120         continue;
121       }
122         } else if ((fData.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) ||
123                                 (fData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
124         {
125                 continue; // always ignore device files
126     } else if (!(types & TYPE_FILE)) {
127        continue;
128     }
129
130     result.push_back(file(fData.cFileName));
131   }
132
133   FindClose(find);
134 #else
135   DIR* dp = opendir(_path.c_str());
136   if (!dp) {
137     SG_LOG(SG_GENERAL, SG_WARN, "Dir::children: opendir failed:" << _path.str());
138     return result;
139   }
140   
141   int filterLen = nameFilter.size();
142   
143   while (true) {
144     struct dirent* entry = readdir(dp);
145     if (!entry) {
146       break; // done iteration
147     }
148     
149     // skip hidden files (names beginning with '.') unless requested
150     if (!(types & INCLUDE_HIDDEN) && (entry->d_name[0] == '.') &&
151          strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")) {
152       continue;
153     }
154     
155     SGPath f = file(entry->d_name);
156     if (!f.exists()) {
157       continue; // stat() failed
158     }
159     
160     if (f.isDir()) {
161       // directory handling
162       if (!(types & TYPE_DIR)) {
163         continue;
164       }
165       
166       if (types & NO_DOT_OR_DOTDOT) {
167         if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
168           continue;
169         }
170       }
171     } else if (f.isFile()) {
172       // regular file handling
173       if (!(types & TYPE_FILE)) {
174         continue;
175       }
176     } else {
177       // block device /fifo/char file, ignore
178       continue;
179     }
180
181     if (!nameFilter.empty()) {
182       int nameLen = strlen(entry->d_name);
183       if (nameLen < filterLen) {
184         continue; // name is shorter than the filter
185       }
186     
187       char* nameSuffix = entry->d_name + (nameLen - filterLen);
188       if (strcmp(nameSuffix, nameFilter.c_str())) {
189         continue;
190       }
191     }
192     
193   // passed all criteria, add to our result vector
194     result.push_back(file(entry->d_name));
195   }
196   
197   closedir(dp);
198 #endif
199   return result;
200 }
201
202 bool Dir::exists() const
203 {
204   return _path.isDir();
205 }
206
207 SGPath Dir::file(const std::string& name) const
208 {
209   SGPath childPath = _path;
210   childPath.set_cached(true);
211   childPath.append(name);
212   return childPath;  
213 }
214
215 #ifdef _WIN32
216 #  define sgMkDir(d,m)       _mkdir(d)
217 #else
218 #  define sgMkDir(d,m)       mkdir(d,m)
219 #endif
220
221 bool Dir::create(mode_t mode)
222 {
223     if (exists()) {
224         return false; // already exists
225     }
226     
227 // recursively create parent directories
228     Dir pr(parent());
229     if (!pr.exists()) {
230         bool ok = pr.create(mode);
231         if (!ok) {
232             return false;
233         }
234     }
235     
236 // finally, create ourselves
237     int err = sgMkDir(_path.c_str(), mode);
238     if (err) {
239         SG_LOG(SG_IO, SG_WARN,  "directory creation failed: (" << _path.str() << ") " << strerror(errno) );
240     }
241     
242     return (err == 0);
243 }
244
245 bool Dir::remove(bool recursive)
246 {
247     if (!exists()) {
248         SG_LOG(SG_IO, SG_WARN, "attempt to remove non-existant dir:" << _path.str());
249         return false;
250     }
251     
252     if (recursive) {
253         bool ok;
254         PathList cs = children(NO_DOT_OR_DOTDOT | INCLUDE_HIDDEN | TYPE_FILE | TYPE_DIR);
255         BOOST_FOREACH(SGPath path, cs) {
256             if (path.isDir()) {
257                 Dir childDir(path);
258                 ok = childDir.remove(true);
259             } else {
260                 ok = path.remove();
261             }
262             
263             if (!ok) {
264                 return false;
265             }
266         } // of child iteration
267     } // of recursive deletion
268     
269 #ifdef _WIN32
270     int err = _rmdir(_path.c_str());
271 #else
272     int err = rmdir(_path.c_str());
273 #endif
274     if (err) {
275         SG_LOG(SG_IO, SG_WARN, "rmdir failed:" << _path.str() << ":" << strerror(errno));
276     }
277     return (err == 0);
278 }
279
280 Dir Dir::parent() const
281 {
282     return Dir(_path.dir());
283 }
284
285 } // of namespace simgear