first check-in of feisty meow codebase. many things broken still due to recent
[feisty_meow.git] / core / library / filesystem / directory.cpp
1 /*****************************************************************************\
2 *                                                                             *
3 *  Name   : directory                                                         *
4 *  Author : Chris Koeritz                                                     *
5 *                                                                             *
6 *******************************************************************************
7 * Copyright (c) 2001-$now By Author.  This program is free software; you can  *
8 * redistribute it and/or modify it under the terms of the GNU General Public  *
9 * License as published by the Free Software Foundation; either version 2 of   *
10 * the License or (at your option) any later version.  This is online at:      *
11 *     http://www.fsf.org/copyleft/gpl.html                                    *
12 * Please send any updates to: fred@gruntose.com                               *
13 \*****************************************************************************/
14
15 #include "directory.h"
16 #include "filename.h"
17
18 #include <algorithms/shell_sort.h>
19 #include <application/windoze_helper.h>
20 #include <basis/astring.h>
21 #include <basis/contracts.h>
22 #include <basis/functions.h>
23 #include <basis/utf_conversion.h>
24 #include <loggers/program_wide_logger.h>
25 #include <structures/string_array.h>
26
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <sys/stat.h>
30 #ifdef __UNIX__
31   #include <dirent.h>
32   #include <fnmatch.h>
33   #include <string.h>
34   #include <unistd.h>
35 #endif
36 #ifdef __WIN32__
37   #include <direct.h>
38 #endif
39
40 /*
41 #ifdef __WIN32__
42   const int MAX_ABS_PATH = 2048;
43 #elif defined(__APPLE__)
44   const int MAX_ABS_PATH = 2048;
45 #else
46   const int MAX_ABS_PATH = MAX_ABS_PATH;
47 #endif
48 */
49
50 #undef LOG
51 #define LOG(s) CLASS_EMERGENCY_LOG(program_wide_logger::get(), s)
52
53 using namespace algorithms;
54 using namespace basis;
55 using namespace loggers;
56 using namespace structures;
57
58 namespace filesystem {
59
60 directory::directory(const astring &path, const char *pattern)
61 : _scanned_okay(false),
62   _path(new astring),
63   _files(new string_array),
64   _folders(new string_array),
65   _pattern(new astring(pattern))
66 { reset(path, pattern); }
67
68 directory::directory(const directory &to_copy)
69 : _scanned_okay(false),
70   _path(new astring),
71   _files(new string_array),
72   _folders(new string_array),
73   _pattern(new astring)
74 { reset(*to_copy._path, to_copy._pattern->observe()); }
75
76 directory::~directory()
77 {
78   _scanned_okay = false;
79   WHACK(_path);
80   WHACK(_files);
81   WHACK(_folders);
82   WHACK(_pattern);
83 }
84
85 const astring &directory::path() const { return *_path; }
86
87 const astring &directory::pattern() const { return *_pattern; }
88
89 directory &directory::operator =(const directory &to_copy)
90 {
91   if (this == &to_copy) return *this;  // oops.
92   _scanned_okay = false;
93   reset(*to_copy._path, to_copy._pattern->observe());
94   return *this;
95 }
96
97 astring directory::absolute_path(const astring &rel_path)
98 {
99   char abs_path[MAX_ABS_PATH + 1];
100   abs_path[0] = '\0';
101 #ifdef __WIN32__
102   if (!_fullpath(abs_path, rel_path.s(), MAX_ABS_PATH)) return "";
103   return abs_path;
104 #else
105   if (!realpath(rel_path.s(), abs_path)) return "";
106   return abs_path;
107 #endif
108 }
109
110 astring directory::current()
111 {
112   astring to_return(".");  // failure result.
113 #ifdef __WIN32__
114   flexichar buffer[MAX_ABS_PATH + 1] = { '\0' };
115   GetCurrentDirectory(MAX_ABS_PATH, buffer);
116   to_return = from_unicode_temp(buffer);
117 #else
118   char buffer[MAX_ABS_PATH + 1] = { '\0' };
119   if (realpath(".", buffer)) to_return = buffer;
120 #endif
121   return to_return;
122 }
123
124 bool directory::reset(const astring &path, const char *pattern)
125 { *_path = path; *_pattern = pattern; return rescan(); }
126
127 bool directory::move_up(const char *pattern)
128 {
129   astring currdir = current();
130   return reset(currdir + "/..", pattern);
131 }
132
133 bool directory::move_down(const astring &subdir, const char *pattern)
134 {
135   astring currdir = current();
136   return reset(currdir + "/" + subdir, pattern);
137 }
138
139 const string_array &directory::files() const { return *_files; }
140
141 const string_array &directory::directories() const { return *_folders; }
142
143 bool directory::rescan()
144 {
145   FUNCDEF("rescan");
146   _scanned_okay = false;
147   _files->reset();
148   _folders->reset();
149   astring cur_dir = ".";
150   astring par_dir = "..";
151 #ifdef __WIN32__
152   // start reading the directory.
153   WIN32_FIND_DATA wfd;
154   astring real_path_spec = *_path + "/" + *_pattern;
155   HANDLE search_handle = FindFirstFile(to_unicode_temp(real_path_spec), &wfd);
156   if (search_handle == INVALID_HANDLE_VALUE) return false;  // bad path.
157   do {
158     // ignore the two standard directory entries.
159     astring filename_transcoded(from_unicode_temp(wfd.cFileName));
160     if (!strcmp(filename_transcoded.s(), cur_dir.s())) continue;
161     if (!strcmp(filename_transcoded.s(), par_dir.s())) continue;
162
163 #ifdef UNICODE
164 //temp
165     to_unicode_persist(fudgemart, filename_transcoded);
166     if (memcmp((wchar_t*)fudgemart, wfd.cFileName, wcslen(wfd.cFileName)*2))
167       printf("failed to compare the string before and after transcoding\n");
168 #endif
169
170 //wprintf(to_unicode_temp("file is %ls\n"), (wchar_t*)to_unicode_temp(filename_transcoded));
171     
172     filename temp_name(*_path, filename_transcoded.s());
173
174     // add this to the appropriate list.
175     if (temp_name.is_directory()) {
176       _folders->concatenate(filename_transcoded);
177     } else {
178       _files->concatenate(filename_transcoded);
179
180 #ifdef UNICODE
181       to_unicode_persist(fudgemart2, temp_name.raw());
182       FILE *fpjunk = _wfopen(fudgemart2, to_unicode_temp("rb"));
183       if (!fpjunk)
184         LOG(astring("failed to open the file for testing: ") + temp_name.raw() + "\n");
185       if (fpjunk) fclose(fpjunk);
186 #endif
187
188         }
189   } while (FindNextFile(search_handle, &wfd));
190   FindClose(search_handle);
191 #endif
192 #ifdef __UNIX__
193   DIR *dir = opendir(_path->s());
194 //hmmm: could check errno to determine what caused the problem.
195   if (!dir) return false;
196   dirent *entry = readdir(dir);
197   while (entry) {
198     char *file = entry->d_name;
199     bool add_it = true;
200     if (!strcmp(file, cur_dir.s())) add_it = false;
201     if (!strcmp(file, par_dir.s())) add_it = false;
202     // make sure that the filename matches the pattern also.
203     if (add_it && !fnmatch(_pattern->s(), file, 0)) {
204       filename temp_name(*_path, file);
205       // add this to the appropriate list.
206       if (temp_name.is_directory())
207         _folders->concatenate(file);
208       else 
209         _files->concatenate(file);
210     }
211     entry = readdir(dir);
212   }
213   closedir(dir);
214 #endif
215   shell_sort(_files->access(), _files->length());
216   shell_sort(_folders->access(), _folders->length());
217
218   _scanned_okay = true;
219   return true;
220 }
221
222 bool directory::make_directory(const astring &path)
223 {
224 #ifdef __UNIX__
225   int mk_ret = mkdir(path.s(), 0777);
226 #endif
227 #ifdef __WIN32__
228   int mk_ret = mkdir(path.s());
229 #endif
230   return !mk_ret;
231 }
232
233 bool directory::remove_directory(const astring &path)
234 {
235 #ifdef __UNIX__
236   int rm_ret = rmdir(path.s());
237 #endif
238 #ifdef __WIN32__
239   int rm_ret = rmdir(path.s());
240 #endif
241   return !rm_ret;
242 }
243
244 bool directory::recursive_create(const astring &directory_name)
245 {
246 //  FUNCDEF("recursive_create");
247   filename dir(directory_name);
248   string_array pieces;
249   dir.separate(pieces);
250   for (int i = 0; i < pieces.length(); i++) {
251     // check each location along the way.
252     string_array partial = pieces.subarray(0, i);
253     filename curr;
254     curr.join(partial);  // this is our current location.
255     // make sure, if we see a drive letter component, that we call it
256     // a proper directory name.
257     if (curr.raw()[curr.raw().end()] == ':')
258       curr = curr.raw() + "/";
259     if (curr.exists()) {
260       if (curr.is_directory()) {
261         continue;  // that's good.
262       }
263       return false;  // if it's an existing file, we're hosed.
264     }
265     // the directory at this place doesn't exist yet.  let's create it.
266     if (!directory::make_directory(curr.raw())) return false;
267   }
268   return true;
269 }
270
271 } // namespace.