f1341e683f50f197122882ce781c2094fd8a2ddc
[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 <application/windoze_helper.h>
19 #include <basis/astring.h>
20 #include <basis/contracts.h>
21 #include <basis/functions.h>
22 #include <basis/utf_conversion.h>
23 #include <loggers/program_wide_logger.h>
24 #include <structures/string_array.h>
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <sys/stat.h>
29
30 #include "../algorithms/sorts.h"
31 #if defined(__UNIX__) || defined(__GNU_WINDOWS__)
32   #include <dirent.h>
33   #include <fnmatch.h>
34   #include <string.h>
35   #include <unistd.h>
36 #endif
37 #ifdef _MSC_VER
38   #include <direct.h>
39 #endif
40
41 /*
42 #ifdef __WIN32__
43   const int MAX_ABS_PATH = 2048;
44 #elif defined(__APPLE__)
45   const int MAX_ABS_PATH = 2048;
46 #else
47   const int MAX_ABS_PATH = MAX_ABS_PATH;
48 #endif
49 */
50
51 //#define DEBUG_DIRECTORY
52   // uncomment for noisier runs.
53
54 #undef LOG
55 #define LOG(s) CLASS_EMERGENCY_LOG(program_wide_logger::get(), s)
56
57 using namespace algorithms;
58 using namespace basis;
59 using namespace loggers;
60 using namespace structures;
61
62 namespace filesystem {
63
64 directory::directory(const astring &path, const char *pattern)
65 : _scanned_okay(false),
66   _path(new astring),
67   _files(new string_array),
68   _folders(new string_array),
69   _pattern(new astring(pattern))
70 { reset(path, pattern); }
71
72 directory::directory(const directory &to_copy)
73 : _scanned_okay(false),
74   _path(new astring),
75   _files(new string_array),
76   _folders(new string_array),
77   _pattern(new astring)
78 { reset(*to_copy._path, to_copy._pattern->observe()); }
79
80 directory::~directory()
81 {
82   _scanned_okay = false;
83   WHACK(_path);
84   WHACK(_files);
85   WHACK(_folders);
86   WHACK(_pattern);
87 }
88
89 const astring &directory::path() const { return *_path; }
90
91 const astring &directory::pattern() const { return *_pattern; }
92
93 directory &directory::operator =(const directory &to_copy)
94 {
95   if (this == &to_copy) return *this;  // oops.
96   _scanned_okay = false;
97   reset(*to_copy._path, to_copy._pattern->observe());
98   return *this;
99 }
100
101 astring directory::absolute_path(const astring &rel_path)
102 {
103   char abs_path[MAX_ABS_PATH + 1];
104   abs_path[0] = '\0';
105 #ifdef _MSC_VER
106   if (!_fullpath(abs_path, rel_path.s(), MAX_ABS_PATH)) return "";
107   return abs_path;
108 #else
109   if (!realpath(rel_path.s(), abs_path)) return "";
110   return abs_path;
111 #endif
112 }
113
114 astring directory::current()
115 {
116   astring to_return(".");  // failure result.
117 #ifdef _MSC_VER
118   flexichar buffer[MAX_ABS_PATH + 1] = { '\0' };
119   GetCurrentDirectory(MAX_ABS_PATH, buffer);
120   to_return = from_unicode_temp(buffer);
121 #else
122   char buffer[MAX_ABS_PATH + 1] = { '\0' };
123   if (realpath(".", buffer)) to_return = buffer;
124 #endif
125   return to_return;
126 }
127
128 bool directory::reset(const astring &path, const char *pattern)
129 { *_path = path; *_pattern = pattern; return rescan(); }
130
131 bool directory::move_up(const char *pattern)
132 {
133   astring currdir = current();
134   return reset(currdir + "/..", pattern);
135 }
136
137 bool directory::move_down(const astring &subdir, const char *pattern)
138 {
139   astring currdir = current();
140   return reset(currdir + "/" + subdir, pattern);
141 }
142
143 const string_array &directory::files() const { return *_files; }
144
145 const string_array &directory::directories() const { return *_folders; }
146
147 bool directory::rescan()
148 {
149   FUNCDEF("rescan");
150   _scanned_okay = false;
151   _files->reset();
152   _folders->reset();
153   astring cur_dir = ".";
154   astring par_dir = "..";
155 #ifdef _MSC_VER
156   // start reading the directory.
157   WIN32_FIND_DATA wfd;
158   astring real_path_spec = *_path + "/" + *_pattern;
159   HANDLE search_handle = FindFirstFile(to_unicode_temp(real_path_spec), &wfd);
160   if (search_handle == INVALID_HANDLE_VALUE) return false;  // bad path.
161   do {
162     // ignore the two standard directory entries.
163     astring filename_transcoded(from_unicode_temp(wfd.cFileName));
164     if (!strcmp(filename_transcoded.s(), cur_dir.s())) continue;
165     if (!strcmp(filename_transcoded.s(), par_dir.s())) continue;
166
167 #ifdef UNICODE
168   #ifdef DEBUG_DIRECTORY
169     to_unicode_persist(kludgemart, filename_transcoded);
170     if (memcmp((wchar_t*)kludgemart, wfd.cFileName, wcslen(wfd.cFileName)*2))
171       printf("failed to compare the string before and after transcoding\n");
172   #endif
173 #endif
174
175 //wprintf(to_unicode_temp("file is %ls\n"), (wchar_t*)to_unicode_temp(filename_transcoded));
176     
177     filename temp_name(*_path, filename_transcoded.s());
178
179     // add this to the appropriate list.
180     if (temp_name.is_directory()) {
181       _folders->concatenate(filename_transcoded);
182     } else {
183       _files->concatenate(filename_transcoded);
184
185 #ifdef UNICODE
186   #ifdef DEBUG_DIRECTORY
187       to_unicode_persist(kludgemart2, temp_name.raw());
188       FILE *fpjunk = _wfopen(kludgemart2, to_unicode_temp("rb"));
189       if (!fpjunk)
190         LOG(astring("failed to open the file for testing: ") + temp_name.raw() + "\n");
191       if (fpjunk) fclose(fpjunk);
192   #endif
193 #endif
194
195         }
196   } while (FindNextFile(search_handle, &wfd));
197   FindClose(search_handle);
198 #else
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 #if defined(__UNIX__) || defined(__GNU_WINDOWS__)
238   int mk_ret = mkdir(path.s(), 0777);
239 #else
240   int mk_ret = mkdir(path.s());
241 #endif
242   return !mk_ret;
243 }
244
245 bool directory::remove_directory(const astring &path)
246 {
247 #if defined(__UNIX__) || defined(__GNU_WINDOWS__)
248   int rm_ret = rmdir(path.s());
249 #else
250   int rm_ret = rmdir(path.s());
251 #endif
252   return !rm_ret;
253 }
254
255 bool directory::recursive_create(const astring &directory_name)
256 {
257   FUNCDEF("recursive_create");
258   filename dir(directory_name);
259   string_array pieces;
260   bool rooted;
261   dir.separate(rooted, pieces);
262   for (int i = 0; i < pieces.length(); i++) {
263     // check each location along the way.
264     string_array partial = pieces.subarray(0, i);
265     filename curr;
266     curr.join(rooted, partial);  // this is our current location.
267     // make sure, if we see a drive letter component, that we call it
268     // a proper directory name.
269     if (curr.raw()[curr.raw().end()] == ':')
270       curr = curr.raw() + "/";
271     if (curr.exists()) {
272       if (curr.is_directory()) {
273         continue;  // that's good.
274       }
275       return false;  // if it's an existing file, we're hosed.
276     }
277     // the directory at this place doesn't exist yet.  let's create it.
278     if (!directory::make_directory(curr.raw())) return false;
279   }
280   return true;
281 }
282
283 } // namespace.
284