5a056f7af1f49c17490656f08fc1bcc9df799ad9
[feisty_meow.git] / nucleus / 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 //#define DEBUG_DIRECTORY
51   // uncomment for noisier runs.
52
53 #undef LOG
54 #define LOG(s) CLASS_EMERGENCY_LOG(program_wide_logger::get(), s)
55
56 using namespace algorithms;
57 using namespace basis;
58 using namespace loggers;
59 using namespace structures;
60
61 namespace filesystem {
62
63 directory::directory(const astring &path, const char *pattern)
64 : _scanned_okay(false),
65   _path(new astring),
66   _files(new string_array),
67   _folders(new string_array),
68   _pattern(new astring(pattern))
69 { reset(path, pattern); }
70
71 directory::directory(const directory &to_copy)
72 : _scanned_okay(false),
73   _path(new astring),
74   _files(new string_array),
75   _folders(new string_array),
76   _pattern(new astring)
77 { reset(*to_copy._path, to_copy._pattern->observe()); }
78
79 directory::~directory()
80 {
81   _scanned_okay = false;
82   WHACK(_path);
83   WHACK(_files);
84   WHACK(_folders);
85   WHACK(_pattern);
86 }
87
88 const astring &directory::path() const { return *_path; }
89
90 const astring &directory::pattern() const { return *_pattern; }
91
92 directory &directory::operator =(const directory &to_copy)
93 {
94   if (this == &to_copy) return *this;  // oops.
95   _scanned_okay = false;
96   reset(*to_copy._path, to_copy._pattern->observe());
97   return *this;
98 }
99
100 astring directory::absolute_path(const astring &rel_path)
101 {
102   char abs_path[MAX_ABS_PATH + 1];
103   abs_path[0] = '\0';
104 #ifdef __WIN32__
105   if (!_fullpath(abs_path, rel_path.s(), MAX_ABS_PATH)) return "";
106   return abs_path;
107 #else
108   if (!realpath(rel_path.s(), abs_path)) return "";
109   return abs_path;
110 #endif
111 }
112
113 astring directory::current()
114 {
115   astring to_return(".");  // failure result.
116 #ifdef __WIN32__
117   flexichar buffer[MAX_ABS_PATH + 1] = { '\0' };
118   GetCurrentDirectory(MAX_ABS_PATH, buffer);
119   to_return = from_unicode_temp(buffer);
120 #else
121   char buffer[MAX_ABS_PATH + 1] = { '\0' };
122   if (realpath(".", buffer)) to_return = buffer;
123 #endif
124   return to_return;
125 }
126
127 bool directory::reset(const astring &path, const char *pattern)
128 { *_path = path; *_pattern = pattern; return rescan(); }
129
130 bool directory::move_up(const char *pattern)
131 {
132   astring currdir = current();
133   return reset(currdir + "/..", pattern);
134 }
135
136 bool directory::move_down(const astring &subdir, const char *pattern)
137 {
138   astring currdir = current();
139   return reset(currdir + "/" + subdir, pattern);
140 }
141
142 const string_array &directory::files() const { return *_files; }
143
144 const string_array &directory::directories() const { return *_folders; }
145
146 bool directory::rescan()
147 {
148   FUNCDEF("rescan");
149   _scanned_okay = false;
150   _files->reset();
151   _folders->reset();
152   astring cur_dir = ".";
153   astring par_dir = "..";
154 #ifdef __WIN32__
155   // start reading the directory.
156   WIN32_FIND_DATA wfd;
157   astring real_path_spec = *_path + "/" + *_pattern;
158   HANDLE search_handle = FindFirstFile(to_unicode_temp(real_path_spec), &wfd);
159   if (search_handle == INVALID_HANDLE_VALUE) return false;  // bad path.
160   do {
161     // ignore the two standard directory entries.
162     astring filename_transcoded(from_unicode_temp(wfd.cFileName));
163     if (!strcmp(filename_transcoded.s(), cur_dir.s())) continue;
164     if (!strcmp(filename_transcoded.s(), par_dir.s())) continue;
165
166 #ifdef UNICODE
167   #ifdef DEBUG_DIRECTORY
168     to_unicode_persist(kludgemart, filename_transcoded);
169     if (memcmp((wchar_t*)kludgemart, wfd.cFileName, wcslen(wfd.cFileName)*2))
170       printf("failed to compare the string before and after transcoding\n");
171   #endif
172 #endif
173
174 //wprintf(to_unicode_temp("file is %ls\n"), (wchar_t*)to_unicode_temp(filename_transcoded));
175     
176     filename temp_name(*_path, filename_transcoded.s());
177
178     // add this to the appropriate list.
179     if (temp_name.is_directory()) {
180       _folders->concatenate(filename_transcoded);
181     } else {
182       _files->concatenate(filename_transcoded);
183
184 #ifdef UNICODE
185   #ifdef DEBUG_DIRECTORY
186       to_unicode_persist(kludgemart2, temp_name.raw());
187       FILE *fpjunk = _wfopen(kludgemart2, to_unicode_temp("rb"));
188       if (!fpjunk)
189         LOG(astring("failed to open the file for testing: ") + temp_name.raw() + "\n");
190       if (fpjunk) fclose(fpjunk);
191   #endif
192 #endif
193
194         }
195   } while (FindNextFile(search_handle, &wfd));
196   FindClose(search_handle);
197 #endif
198 #ifdef __UNIX__
199   DIR *dir = opendir(_path->s());
200 //hmmm: could check errno to determine what caused the problem.
201   if (!dir) return false;
202   dirent *entry = readdir(dir);
203   while (entry) {
204     char *file = entry->d_name;
205     bool add_it = true;
206     if (!strcmp(file, cur_dir.s())) add_it = false;
207     if (!strcmp(file, par_dir.s())) add_it = false;
208     // make sure that the filename matches the pattern also.
209     if (add_it && !fnmatch(_pattern->s(), file, 0)) {
210       filename temp_name(*_path, file);
211       if (!temp_name.is_normal()) {
212 #ifdef DEBUG_DIRECTORY
213         LOG(astring("skipping abnormal file:  ") + temp_name);
214 #endif
215         entry = readdir(dir);
216         continue;  // cannot be adding goofy named pipes etc; cannot manage those.
217       }
218       // add this to the appropriate list.
219       if (temp_name.is_directory())
220         _folders->concatenate(file);
221       else 
222         _files->concatenate(file);
223     }
224     entry = readdir(dir);
225   }
226   closedir(dir);
227 #endif
228   shell_sort(_files->access(), _files->length());
229   shell_sort(_folders->access(), _folders->length());
230
231   _scanned_okay = true;
232   return true;
233 }
234
235 bool directory::make_directory(const astring &path)
236 {
237 #ifdef __UNIX__
238   int mk_ret = mkdir(path.s(), 0777);
239 #endif
240 #ifdef __WIN32__
241   int mk_ret = mkdir(path.s());
242 #endif
243   return !mk_ret;
244 }
245
246 bool directory::remove_directory(const astring &path)
247 {
248 #ifdef __UNIX__
249   int rm_ret = rmdir(path.s());
250 #endif
251 #ifdef __WIN32__
252   int rm_ret = rmdir(path.s());
253 #endif
254   return !rm_ret;
255 }
256
257 bool directory::recursive_create(const astring &directory_name)
258 {
259   FUNCDEF("recursive_create");
260   filename dir(directory_name);
261   string_array pieces;
262   bool rooted;
263   dir.separate(rooted, pieces);
264   for (int i = 0; i < pieces.length(); i++) {
265     // check each location along the way.
266     string_array partial = pieces.subarray(0, i);
267     filename curr;
268     curr.join(rooted, partial);  // this is our current location.
269     // make sure, if we see a drive letter component, that we call it
270     // a proper directory name.
271     if (curr.raw()[curr.raw().end()] == ':')
272       curr = curr.raw() + "/";
273     if (curr.exists()) {
274       if (curr.is_directory()) {
275         continue;  // that's good.
276       }
277       return false;  // if it's an existing file, we're hosed.
278     }
279     // the directory at this place doesn't exist yet.  let's create it.
280     if (!directory::make_directory(curr.raw())) return false;
281   }
282   return true;
283 }
284
285 } // namespace.