]> git.mxchange.org Git - simgear.git/blob - simgear/misc/sg_path.cxx
Slightly rearrange the buffer removing code. This should make sure the source is...
[simgear.git] / simgear / misc / sg_path.cxx
1 // sg_path.cxx -- routines to abstract out path separator differences
2 //               between MacOS and the rest of the world
3 //
4 // Written by Curtis L. Olson, started April 1999.
5 //
6 // Copyright (C) 1999  Curtis L. Olson - http://www.flightgear.org/~curt
7 //
8 // This library is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU Library General Public
10 // License as published by the Free Software Foundation; either
11 // version 2 of the License, or (at your option) any later version.
12 //
13 // This library is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // Library General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 //
22 // $Id$
23
24
25 #include <simgear/compiler.h>
26
27 #include <simgear_config.h>
28 #include <simgear/debug/logstream.hxx>
29 #include <stdio.h>
30 #include <sys/stat.h>
31 #include <errno.h>
32
33 #ifdef _WIN32
34 #  include <direct.h>
35 #endif
36 #include "sg_path.hxx"
37
38 #include <boost/algorithm/string/case_conv.hpp>
39
40 using std::string;
41
42 /**
43  * define directory path separators
44  */
45
46 static const char sgDirPathSep = '/';
47 static const char sgDirPathSepBad = '\\';
48
49 #ifdef _WIN32
50 static const char sgSearchPathSep = ';';
51 #else
52 static const char sgSearchPathSep = ':';
53 #endif
54
55
56 // If Unix, replace all ":" with "/".  In windoze, allow the
57 // second character to be a ":" for things like c:\foo\bar
58
59 void
60 SGPath::fix()
61 {
62     for ( string::size_type i = 0; i < path.size(); ++i ) {
63 #if defined( WIN32 )
64     // for windoze, don't replace the ":" for the second character
65     if ( i == 1 ) {
66         continue;
67     }
68 #endif
69     if ( path[i] == sgDirPathSepBad ) {
70         path[i] = sgDirPathSep;
71     }
72     }
73 }
74
75
76 // default constructor
77 SGPath::SGPath()
78     : path(""),
79     _cached(false),
80     _cacheEnabled(true)
81 {
82 }
83
84
85 // create a path based on "path"
86 SGPath::SGPath( const std::string& p )
87     : path(p),
88     _cached(false),
89     _cacheEnabled(true)
90 {
91     fix();
92 }
93
94 // create a path based on "path" and a "subpath"
95 SGPath::SGPath( const SGPath& p, const std::string& r )
96     : path(p.path),
97     _cached(false),
98     _cacheEnabled(p._cacheEnabled)
99 {
100     append(r);
101     fix();
102 }
103
104 SGPath::SGPath(const SGPath& p) :
105   path(p.path),
106   _cached(p._cached),
107   _cacheEnabled(p._cacheEnabled),
108   _exists(p._exists),
109   _isDir(p._isDir),
110   _isFile(p._isFile),
111   _modTime(p._modTime)
112 {
113 }
114     
115 SGPath& SGPath::operator=(const SGPath& p)
116 {
117   path = p.path;
118   _cached = p._cached;
119   _cacheEnabled = p._cacheEnabled;
120   _exists = p._exists;
121   _isDir = p._isDir;
122   _isFile = p._isFile;
123   _modTime = p._modTime;
124   return *this;
125 }
126
127 // destructor
128 SGPath::~SGPath() {
129 }
130
131
132 // set path
133 void SGPath::set( const string& p ) {
134     path = p;
135     fix();
136     _cached = false;
137 }
138
139 void SGPath::set_cached(bool cached)
140 {
141     _cacheEnabled = cached;
142 }
143
144 // append another piece to the existing path
145 void SGPath::append( const string& p ) {
146     if ( path.size() == 0 ) {
147     path = p;
148     } else {
149     if ( p[0] != sgDirPathSep ) {
150         path += sgDirPathSep;
151     }
152     path += p;
153     }
154     fix();
155     _cached = false;
156 }
157
158 //add a new path component to the existing path string
159 void SGPath::add( const string& p ) {
160     append( sgSearchPathSep+p );
161 }
162
163
164 // concatenate a string to the end of the path without inserting a
165 // path separator
166 void SGPath::concat( const string& p ) {
167     if ( path.size() == 0 ) {
168     path = p;
169     } else {
170     path += p;
171     }
172     fix();
173     _cached = false;
174 }
175
176
177 // Get the file part of the path (everything after the last path sep)
178 string SGPath::file() const
179 {
180     string::size_type index = path.rfind(sgDirPathSep);
181     if (index != string::npos) {
182         return path.substr(index + 1);
183     } else {
184         return path;
185     }
186 }
187   
188
189 // get the directory part of the path.
190 string SGPath::dir() const {
191     int index = path.rfind(sgDirPathSep);
192     if (index >= 0) {
193         return path.substr(0, index);
194     } else {
195         return "";
196     }
197 }
198
199 // get the base part of the path (everything but the extension.)
200 string SGPath::base() const
201 {
202     string::size_type index = path.rfind(".");
203     string::size_type lastSep = path.rfind(sgDirPathSep);
204     
205 // tolerate dots inside directory names
206     if ((lastSep != string::npos) && (index < lastSep)) {
207         return path;
208     }
209     
210     if (index != string::npos) {
211         return path.substr(0, index);
212     } else {
213         return path;
214     }
215 }
216
217 string SGPath::file_base() const
218 {
219     string::size_type index = path.rfind(sgDirPathSep);
220     if (index == string::npos) {
221         index = 0; // no separator in the name
222     } else {
223         ++index; // skip past the separator
224     }
225     
226     string::size_type firstDot = path.find(".", index);
227     if (firstDot == string::npos) {
228         return path.substr(index); // no extensions
229     }
230     
231     return path.substr(index, firstDot - index);
232 }
233
234 // get the extension (everything after the final ".")
235 // but make sure no "/" follows the "." character (otherwise it
236 // is has to be a directory name containing a ".").
237 string SGPath::extension() const {
238     int index = path.rfind(".");
239     if ((index >= 0)  && (path.find("/", index) == string::npos)) {
240         return path.substr(index + 1);
241     } else {
242         return "";
243     }
244 }
245
246 string SGPath::lower_extension() const {
247     return boost::to_lower_copy(extension());
248 }
249
250 string SGPath::complete_lower_extension() const
251 {
252     string::size_type index = path.rfind(sgDirPathSep);
253     if (index == string::npos) {
254         index = 0; // no separator in the name
255     } else {
256         ++index; // skip past the separator
257     }
258     
259     string::size_type firstDot = path.find(".", index);
260     if ((firstDot != string::npos)  && (path.find(sgDirPathSep, firstDot) == string::npos)) {
261         return boost::to_lower_copy(path.substr(firstDot + 1));
262     } else {
263         return "";
264     }
265 }
266
267 void SGPath::validate() const
268 {
269   if (_cached && _cacheEnabled) {
270     return;
271   }
272   
273 #ifdef _WIN32
274   struct _stat buf ;
275
276   bool remove_trailing = false;
277   if ( path.length() > 1 && path[path.length()-1] == '/' )
278       remove_trailing=true;
279   if (_stat (path.substr(0,remove_trailing?path.length()-1:path.length()).c_str(), &buf ) < 0) {
280     _exists = false;
281   } else {
282     _exists = true;
283     _isFile = ((S_IFREG & buf.st_mode ) !=0);
284     _isDir = ((S_IFDIR & buf.st_mode ) !=0);
285     _modTime = buf.st_mtime;
286   }
287
288 #else
289   struct stat buf ;
290
291   if (stat(path.c_str(), &buf ) < 0) {
292     _exists = false;
293   } else {
294     _exists = true;
295     _isFile = ((S_ISREG(buf.st_mode )) != 0);
296     _isDir = ((S_ISDIR(buf.st_mode )) != 0);
297     _modTime = buf.st_mtime;
298   }
299   
300 #endif
301   _cached = true;
302 }
303
304 bool SGPath::exists() const
305 {
306   validate();
307   return _exists;
308 }
309
310 bool SGPath::isDir() const
311 {
312   validate();
313   return _exists && _isDir;
314 }
315
316 bool SGPath::isFile() const
317 {
318   validate();
319   return _exists && _isFile;
320 }
321
322 #ifdef _WIN32
323 #  define sgMkDir(d,m)       _mkdir(d)
324 #else
325 #  define sgMkDir(d,m)       mkdir(d,m)
326 #endif
327
328
329 int SGPath::create_dir( mode_t mode ) {
330     string_list dirlist = sgPathSplit(dir());
331     if ( dirlist.empty() )
332         return -1;
333     string path = dirlist[0];
334     string_list path_elements = sgPathBranchSplit(path);
335     bool absolute = !path.empty() && path[0] == sgDirPathSep;
336
337     unsigned int i = 1;
338     SGPath dir = absolute ? string( 1, sgDirPathSep ) : "";
339     dir.concat( path_elements[0] );
340 #ifdef _WIN32
341     if ( dir.str().find(':') != string::npos && path_elements.size() >= 2 ) {
342         dir.append( path_elements[1] );
343         i = 2;
344     }
345 #endif
346     struct stat info;
347     int r;
348     for(; ( r = stat( dir.c_str(), &info ) ) == 0 && i < path_elements.size(); i++) {
349         dir.append(path_elements[i]);
350     }
351     if ( r == 0 ) {
352         return 0; // Directory already exists
353     }
354     if ( sgMkDir( dir.c_str(), mode) ) {
355         SG_LOG( SG_IO, SG_ALERT, "Error creating directory: " + dir.str() );
356         return -2;
357     }
358     for(; i < path_elements.size(); i++) {
359         dir.append(path_elements[i]);
360         if ( sgMkDir( dir.c_str(), mode) ) {
361             SG_LOG( SG_IO, SG_ALERT, "Error creating directory: " + dir.str() );
362             return -2;
363         }
364     }
365
366     return 0;
367 }
368
369 string_list sgPathBranchSplit( const string &dirpath ) {
370     string_list path_elements;
371     string element, path = dirpath;
372     while ( path.size() ) {
373         size_t p = path.find( sgDirPathSep );
374         if ( p != string::npos ) {
375             element = path.substr( 0, p );
376             path.erase( 0, p + 1 );
377         } else {
378             element = path;
379             path = "";
380         }
381         if ( element.size() )
382             path_elements.push_back( element );
383     }
384     return path_elements;
385 }
386
387
388 string_list sgPathSplit( const string &search_path ) {
389     string tmp = search_path;
390     string_list result;
391     result.clear();
392
393     bool done = false;
394
395     while ( !done ) {
396         int index = tmp.find(sgSearchPathSep);
397         if (index >= 0) {
398             result.push_back( tmp.substr(0, index) );
399             tmp = tmp.substr( index + 1 );
400         } else {
401             if ( !tmp.empty() )
402                 result.push_back( tmp );
403             done = true;
404         }
405     }
406
407     return result;
408 }
409
410 bool SGPath::isAbsolute() const
411 {
412   if (path.empty()) {
413     return false;
414   }
415   
416 #ifdef _WIN32
417   // detect '[A-Za-z]:/'
418   if (path.size() > 2) {
419     if (isalpha(path[0]) && (path[1] == ':') && (path[2] == sgDirPathSep)) {
420       return true;
421     }
422   }
423 #endif
424   
425   return (path[0] == sgDirPathSep);
426 }
427
428 bool SGPath::isNull() const
429 {
430   return path.empty() || (path == "");
431 }
432
433 std::string SGPath::str_native() const
434 {
435 #ifdef _WIN32
436     std::string s = str();
437     std::string::size_type pos;
438     std::string nativeSeparator;
439     nativeSeparator = sgDirPathSepBad;
440
441     while( (pos=s.find( sgDirPathSep )) != std::string::npos ) {
442         s.replace( pos, 1, nativeSeparator );
443     }
444     return s;
445 #else
446     return str();
447 #endif
448 }
449
450 bool SGPath::remove()
451 {
452     int err = ::unlink(c_str());
453     if (err) {
454         SG_LOG(SG_IO, SG_WARN,  "file remove failed: (" << str() << ") " << strerror(errno));
455     }
456     return (err == 0);
457 }
458
459 time_t SGPath::modTime() const
460 {
461     validate();
462     return _modTime;
463 }
464
465 bool SGPath::operator==(const SGPath& other) const
466 {
467     return (path == other.path);
468 }
469
470 bool SGPath::operator!=(const SGPath& other) const
471 {
472     return (path != other.path);
473 }
474
475 bool SGPath::rename(const SGPath& newName)
476 {
477     if (::rename(c_str(), newName.c_str()) != 0) {
478         SG_LOG(SG_IO, SG_WARN, "renamed failed: from " << str() << " to " << newName.str()
479             << " reason: " << strerror(errno));
480         return false;
481     }
482     
483     path = newName.path;
484     _cached = false;
485     return true;
486 }
487