Debian Codegraph @

Frameworks/OpenVanilla/Headers/OVFileHelper.h

raw symbols SCIP
1 //
2 // OVFileHelper.h
3 //
4 // Copyright (c) 2004-2008 The OpenVanilla Project (http://openvanilla.org)
5 // All rights reserved.
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
9 // are met:
10 //
11 // 1. Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
13 // 2. Redistributions in binary form must reproduce the above copyright
14 // notice, this list of conditions and the following disclaimer in the
15 // documentation and/or other materials provided with the distribution.
16 // 3. Neither the name of OpenVanilla nor the names of its contributors
17 // may be used to endorse or promote products derived from this software
18 // without specific prior written permission.
19 //
20 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
24 // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 // POSSIBILITY OF SUCH DAMAGE.
31
32 #ifndef OVFileHelper_h
33 #define OVFileHelper_h
34
35 #if defined(__APPLE__)
36 #include <dirent.h>
37 #include <stdio.h>
38 #else
39 #include <windows.h>
40 #include <shlobj.h>
41 #include <stdio.h>
42 #endif
43
44 #include <sys/stat.h>
45
46 #include <fstream>
47 #include <algorithm>
48 #include <vector>
49 #include "OVWildcard.h"
50 #include "OVUTF8Helper.h"
51
52 namespace OpenVanilla {
53 using namespace std;
54
55 class OVFileHelper {
56 public:
57 static FILE* OpenStream(const string& filename, const string& mode = "rb")
58 {
59 #ifndef WIN32
60 return fopen(filename.c_str(), mode.c_str());
61 #else
62 FILE* stream = NULL;
63 errno_t err = _wfopen_s(&stream, OVUTF16::FromUTF8(filename).c_str(), OVUTF16::FromUTF8(mode).c_str());
64 return err ? 0 : stream;
65 #endif
66 }
67
68 static void OpenOFStream(ofstream& stream, const string& filename, ios_base::openmode openMode)
69 {
70 #ifndef WIN32
71 stream.open(filename.c_str(), openMode);
72 #else
73 stream.open(OVUTF16::FromUTF8(filename).c_str(), openMode);
74 #endif
75 }
76
77
78 static void OpenIFStream(ifstream& stream, const string& filename, ios_base::openmode openMode)
79 {
80 #ifndef WIN32
81 stream.open(filename.c_str(), openMode);
82 #else
83 stream.open(OVUTF16::FromUTF8(filename).c_str(), openMode);
84 #endif
85 }
86
87 // use free(), not delete[], to free the block allocated
88 static pair<char*, size_t> SlurpFile(const string& filename)
89 {
90 FILE* stream = OpenStream(filename);
91 char* buf = 0;
92 size_t size = 0;
93 if (stream) {
94 if (!fseek(stream, 0, SEEK_END)) {
95 long lsize = ftell(stream);
96 if (lsize) {
97 size = (size_t)lsize;
98 if (!fseek(stream, 0, SEEK_SET)) {
99 buf = (char*)calloc(1, (size_t)size);
100 if (buf) {
101 if (fread(buf, size, 1, stream) != 1) {
102 free(buf);
103 buf = 0;
104 size = 0;
105 }
106 }
107 else {
108 size = 0;
109 }
110 }
111 else {
112 size = 0;
113 }
114 }
115 }
116
117 fclose(stream);
118 }
119
120 return pair<char*, size_t>(buf, size);
121 }
122 };
123
124 class OVFileTimestamp {
125 public:
126 #if defined(__APPLE__)
127 OVFileTimestamp(__darwin_time_t timestamp = 0, long subtimestamp = 0)
128 #elif defined(WIN32)
129 OVFileTimestamp(time_t timestamp = 0, time_t subtimestamp = 0)
130 #else
131 #error We don't know about Linux yet, sorry.
132 #endif
133 : m_timestamp(timestamp)
134 , m_subtimestamp(subtimestamp)
135 {
136 }
137
138 OVFileTimestamp(const OVFileTimestamp& timestamp)
139 : m_timestamp(timestamp.m_timestamp)
140 , m_subtimestamp(timestamp.m_subtimestamp)
141 {
142 }
143
144 OVFileTimestamp& operator=(const OVFileTimestamp& timestamp)
145 {
146 m_timestamp = timestamp.m_timestamp;
147 m_subtimestamp = timestamp.m_subtimestamp;
148 return *this;
149 }
150
151
152 bool operator==(OVFileTimestamp& another)
153 {
154 return (m_timestamp == another.m_timestamp) && (m_subtimestamp == another.m_subtimestamp);
155 }
156
157 bool operator!=(OVFileTimestamp& another)
158 {
159 return (m_timestamp != another.m_timestamp) || (m_subtimestamp != another.m_subtimestamp);
160 }
161
162 bool operator<(OVFileTimestamp& another)
163 {
164 return (m_timestamp < another.m_timestamp) || ((m_timestamp == another.m_timestamp) && m_subtimestamp < another.m_subtimestamp);
165 }
166
167 bool operator>(OVFileTimestamp& another)
168 {
169 return (m_timestamp > another.m_timestamp) || ((m_timestamp == another.m_timestamp) && m_subtimestamp > another.m_subtimestamp);
170 }
171
172
173 protected:
174 #if defined(__APPLE__)
175 __darwin_time_t m_timestamp;
176 long m_subtimestamp;
177 #elif defined(WIN32)
178 time_t m_timestamp;
179 time_t m_subtimestamp;
180 #else
181 #error We don't know about Linux yet, sorry.
182 #endif
183 };
184
185
186 class OVPathHelper {
187 public:
188 static char Separator()
189 {
190 #ifndef WIN32
191 return '/';
192 #else
193 return '\\';
194 #endif
195 }
196
197
198 static const string DirectoryFromPath(const string& path)
199 {
200 string realPath = OVPathHelper::NormalizeByExpandingTilde(path);
201 if (OVPathHelper::PathExists(realPath) && OVPathHelper::IsDirectory(realPath))
202 return realPath;
203
204 char separator = OVPathHelper::Separator();
205
206 if (!realPath.length())
207 return string(".");
208
209 for (size_t index = realPath.length() - 1; index >= 0 ; index--) {
210 if (realPath[index] == separator) {
211 if (index) {
212 // reserve the \\ on Windows
213 if (realPath[index-1] == '\\')
214 return realPath.substr(0, index + 1);
215 else
216 return realPath.substr(0, index);
217 }
218 else
219 return realPath.substr(0, 1);
220 }
221
222 // if we run into : (like C:) on Windows
223 if (realPath[index] == ':')
224 return realPath.substr(0, index + 1) + Separator();
225
226 if (!index) break;
227 }
228
229 return string(".");
230 }
231
232 static const string FilenameWithoutPath(const string &path)
233 {
234 char separator = OVPathHelper::Separator();
235
236 if (!path.length())
237 return string();
238
239 for (size_t index = path.length() - 1; index >= 0 ; index--) {
240 if (path[index] == separator)
241 return path.substr(index + 1, path.length() - (index + 1));
242
243 if (!index) break;
244 }
245
246 return path;
247 }
248
249 static const string FilenameWithoutExtension(const string &path)
250 {
251 char separator = OVPathHelper::Separator();
252 if (!path.length())
253 return string();
254
255 for (size_t index = path.length() - 1; index >= 0 ; index--) {
256 if (path[index] == separator)
257 break;
258
259 if (path[index] == '.')
260 return path.substr(0, index);
261
262 if (!index) break;
263 }
264
265 return path;
266 }
267
268 static const string ChopTrailingSeparator(const string& path)
269 {
270 if (path.length() == 1 && path[0] == Separator())
271 return path;
272
273 string result;
274
275 if (path.length()) {
276 if (path[path.length() - 1] == Separator())
277 result = path.substr(0, path.length() - 1);
278 else
279 result = path;
280 }
281
282 return result;
283 }
284
285 static const string ChopLeadingSeparator(const string& path)
286 {
287 if (path.length() == 1 && path[0] == Separator())
288 return path;
289
290 string result;
291 if (path.length()) {
292 if (path[0] == Separator()) {
293 result = path.substr(1, path.length() - 1);
294 }
295 else {
296 result = path;
297 }
298 }
299 return result;
300 }
301
302 static const string PathCat(const string& s1, const string& s2)
303 {
304 if (s2.length())
305 return ChopTrailingSeparator(s1) + Separator() + ChopLeadingSeparator(s2);
306 else
307 return s1;
308 }
309
310 static const string Normalize(const string& path)
311 {
312 string newPath;
313 size_t length = path.length();
314 for (size_t index = 0; index < length; index++) {
315 if (path[index] == '/' || path[index] == '\\') {
316 if (index < length - 1) {
317 if (path[index+1] == '/' || path[index+1] == '\\')
318 index++;
319 }
320
321 newPath += Separator();
322 }
323 else
324 newPath += path[index];
325 }
326
327 return ChopTrailingSeparator(newPath);
328 }
329
330 static const bool PathExists(const string& path)
331 {
332 #ifndef WIN32
333 struct stat buf;
334 return !stat(path.c_str(), &buf);
335 #else
336 struct _stat buf;
337 wstring wpath = OVUTF16::FromUTF8(path);
338 return !_wstat(wpath.c_str(), &buf);
339 #endif
340 }
341
342 static const bool IsDirectory(const string& path)
343 {
344 #ifndef WIN32
345 struct stat buf;
346 if (!stat(path.c_str(), &buf))
347 {
348 if (buf.st_mode & S_IFDIR)
349 return true;
350 }
351 #else
352 struct _stat buf;
353 wstring wpath = OVUTF16::FromUTF8(path);
354 if (!_wstat(wpath.c_str(), &buf))
355 {
356 if (buf.st_mode & S_IFDIR)
357 return true;
358 }
359 #endif
360 return false;
361 }
362
363 static const OVFileTimestamp TimestampForPath(const string& path)
364 {
365 OVFileTimestamp timestamp;
366 #if defined(__APPLE__)
367 struct stat buf;
368 if (!stat(path.c_str(), &buf))
369 {
370 timestamp = OVFileTimestamp(buf.st_mtimespec.tv_sec, buf.st_mtimespec.tv_nsec);
371 }
372 #elif defined(WIN32)
373 struct _stat buf;
374 wstring wpath = OVUTF16::FromUTF8(path);
375 if (!_wstat(wpath.c_str(), &buf))
376 {
377 timestamp = OVFileTimestamp(buf.st_mtime);
378 }
379 #else
380 #error Sorry, no idea for Linux yet.
381 #endif
382 return timestamp;
383 }
384
385 static bool RemoveEverythingAtPath(const string& path);
386 static const string NormalizeByExpandingTilde(const string& path);
387 };
388
389 class OVDirectoryHelper {
390 public:
391 static bool MakeDirectory(const string& path)
392 {
393 #ifndef WIN32
394 return !mkdir(path.c_str(), S_IRWXU);
395 #else
396 wstring wpath = OVUTF16::FromUTF8(path);
397 return CreateDirectoryW(wpath.c_str(), NULL) == TRUE;
398 #endif
399 }
400
401 static bool MakeDirectoryWithImmediates(const string& path)
402 {
403 string realPath = OVPathHelper::NormalizeByExpandingTilde(path);
404
405 if (OVPathHelper::PathExists(realPath) && OVPathHelper::IsDirectory(realPath)) {
406 return true;
407 }
408
409 string lastPart = OVPathHelper::DirectoryFromPath(realPath);
410
411 if (lastPart != realPath && !OVPathHelper::PathExists(lastPart)) {
412 if (!MakeDirectoryWithImmediates(lastPart))
413 return false;
414 }
415
416 return MakeDirectory(realPath);
417 }
418
419 static bool CheckDirectory(const string& path)
420 {
421 string realPath = OVPathHelper::NormalizeByExpandingTilde(path);
422 if (OVPathHelper::PathExists(realPath))
423 return OVPathHelper::IsDirectory(realPath);
424
425 return MakeDirectoryWithImmediates(realPath);
426 }
427
428 static const vector<string> Glob(const string& directory, const string& pattern = "*", const string& excludePattern = "", size_t depth = 1)
429 {
430 string sanitizedDirectory = OVPathHelper::NormalizeByExpandingTilde(directory);
431
432 OVWildcard expression(pattern);
433 OVWildcard negativeExpression(excludePattern);
434 vector<string> dirResult;
435 vector<string> fileResult;
436 struct dirent** namelist = NULL;
437
438 #ifndef WIN32
439 int count = scandir(sanitizedDirectory.c_str(), &namelist, NULL, NULL);
440 for (int index = 0; index < count; index++) {
441 struct dirent* entry = namelist[index];
442 bool isDir = entry->d_type == DT_DIR;
443 string name = entry->d_name;
444 #else
445 vector<pair<string, bool> > foundFiles;
446 WIN32_FIND_DATAW findData;
447 HANDLE findHandle = FindFirstFileW(OVUTF16::FromUTF8(OVPathHelper::PathCat(sanitizedDirectory, "*.*")).c_str(), &findData);
448 if (findHandle != INVALID_HANDLE_VALUE) {
449 foundFiles.push_back(pair<string, bool>(OVUTF8::FromUTF16(findData.cFileName), (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0));
450
451 while (FindNextFileW(findHandle, &findData))
452 {
453 foundFiles.push_back(pair<string, bool>(OVUTF8::FromUTF16(findData.cFileName), (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0));
454 }
455 FindClose(findHandle);
456 }
457
458 size_t count = foundFiles.size();
459 for (size_t index = 0; index < count; index++) {
460 string name = foundFiles[index].first;
461 bool isDir = foundFiles[index].second;
462 #endif
463
464 if ((!depth || depth > 1) && isDir && name != "." && name != "..") {
465 vector<string> subResult = Glob(OVPathHelper::PathCat(sanitizedDirectory, name), pattern, excludePattern, depth ? depth - 1 : 0);
466 vector<string>::iterator iter = subResult.begin();
467 for ( ; iter != subResult.end() ; iter++)
468 dirResult.push_back(*iter);
469 }
470
471 if (name != "." && name != ".." && expression.match(name) && !negativeExpression.match(name)) {
472 fileResult.push_back(OVPathHelper::PathCat(sanitizedDirectory, name));
473 }
474
475 #ifndef WIN32
476 free(entry);
477 #endif
478 }
479
480 #ifndef WIN32
481 if (count != -1)
482 free(namelist);
483 #endif
484
485 sort(dirResult.begin(), dirResult.end());
486 sort(fileResult.begin(), fileResult.end());
487 for (vector<string>::iterator iter = dirResult.begin() ; iter != dirResult.end(); iter++)
488 fileResult.push_back(*iter);
489
490 return fileResult;
491 }
492
493 static const string TempDirectory()
494 {
495 #ifndef WIN32
496 return string("/tmp");
497 #else
498 WCHAR path[MAX_PATH + 1];
499 GetTempPathW(MAX_PATH, path);
500 return OVUTF8::FromUTF16(path);
501 #endif
502 }
503
504 static const string UserHomeDirectory()
505 {
506 #ifndef WIN32
507 const char* homePath = getenv("HOME");
508 if (homePath)
509 return string(homePath);
510 return TempDirectory();
511 #else
512 WCHAR path[MAX_PATH + 1];
513 HRESULT error = SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, SHGFP_TYPE_CURRENT, path);
514 if (!error) {
515 return OVUTF8::FromUTF16(path);
516 }
517 return TempDirectory();
518 #endif
519 }
520
521 static const string UserApplicationDataDirectory(const string& applicationName)
522 {
523 #if defined(__APPLE__)
524 return OVPathHelper::PathCat(UserHomeDirectory(), OVPathHelper::PathCat("/Library/", applicationName));
525 #elif defined(WIN32)
526 WCHAR path[MAX_PATH + 1];
527 HRESULT error = SHGetFolderPathW(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, path);
528 if (!error) {
529 return OVPathHelper::PathCat(OVUTF8::FromUTF16(path), applicationName);
530 }
531 return OVPathHelper::PathCat(TempDirectory(), applicationName);
532 #else
533 return OVPathHelper::PathCat(UserHomeDirectory(), string(".") + applicationName);
534 #endif
535 }
536
537 static const string UserApplicationSupportDataDirectory(const string& applicationName)
538 {
539 #ifdef __APPLE__
540 return OVPathHelper::PathCat(UserHomeDirectory(), OVPathHelper::PathCat("/Library/Application Support", applicationName));
541 #else
542 return UserApplicationDataDirectory(applicationName);
543 #endif
544 }
545
546 static const string UserPreferencesDirectory(const string& applicationName)
547 {
548 #ifdef __APPLE__
549 return OVPathHelper::NormalizeByExpandingTilde("~/Library/Preferences");
550 #else
551 return UserApplicationDataDirectory(applicationName);
552 #endif
553 }
554
555 };
556
557 inline const string OVPathHelper::NormalizeByExpandingTilde(const string& path)
558 {
559 string newPath = Normalize(path);
560
561 if (newPath.length()) {
562 if (newPath[0] == '~') {
563 newPath = OVPathHelper::PathCat(OVDirectoryHelper::UserHomeDirectory(), newPath.substr(1, newPath.length()));
564 }
565 }
566
567 return newPath;
568 }
569
570 inline bool OVPathHelper::RemoveEverythingAtPath(const string& path)
571 {
572 if (!PathExists(path)) return false;
573
574 if (IsDirectory(path)) {
575 vector<string> files = OVDirectoryHelper::Glob(path, "*", "", 0);
576 vector<string>::iterator iter = files.begin();
577 for ( ; iter != files.end(); iter++) {
578 if (!RemoveEverythingAtPath(*iter))
579 return false;
580 }
581
582 #ifndef WIN32
583 return !rmdir(path.c_str());
584 #else
585 wstring wpath = OVUTF16::FromUTF8(path);
586 return RemoveDirectoryW(wpath.c_str()) == TRUE;
587 #endif
588 }
589 else {
590 #ifndef WIN32
591 return !unlink(path.c_str());
592 #else
593 wstring wpath = OVUTF16::FromUTF8(path);
594 return DeleteFileW(wpath.c_str()) == TRUE;
595 #endif
596 }
597 }
598 };
599
600 #endif