ed7b914aa518d2d1b0c5fb017da2414456d94e22
[feisty_meow.git] / nucleus / library / filesystem / filename.cpp
1 /*****************************************************************************\
2 *                                                                             *
3 *  Name   : filename                                                          *
4 *  Author : Chris Koeritz                                                     *
5 *                                                                             *
6 *******************************************************************************
7 * Copyright (c) 1993-$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 // implementation note: the filename is kept canonicalized.  any constructor
16 // or assignment operator should ensure this (except the blank constructor).
17
18 #include "filename.h"
19
20 #include <basis/byte_array.h>
21 #include <basis/functions.h>
22 #include <textual/parser_bits.h>
23
24 #include <stdio.h>
25 #include <sys/stat.h>
26 #include <sys/types.h>
27 #if defined(__UNIX__) || defined(__GNU_WINDOWS__)
28   #include <unistd.h>
29 #else
30   #include <io.h>
31 #endif
32
33 #undef LOG
34 #define LOG(to_print) printf("%s::%s: %s\n", static_class_name(), func, astring(to_print).s())
35
36 using namespace basis;
37 using namespace structures;
38
39 class status_info : public stat
40 {
41 };
42
43 namespace filesystem {
44
45 #if defined(__WIN32__) || defined(__VMS__)
46   const char DEFAULT_SEPARATOR = '\\';
47 #elif defined(__UNIX__)
48   const char DEFAULT_SEPARATOR = '/';
49 #else
50   #error "We have no idea what the default path separator is."
51 #endif
52
53 const char *NO_PARENT_DEFAULT = ".";
54   // used when no directory name can be popped off.
55
56 filename::filename()
57 : astring(),
58   _had_directory(false)
59 {}
60
61 filename::filename(const astring &name)
62 : astring(name),
63   _had_directory(true)
64 { canonicalize(); }
65
66 filename::filename(const astring &directory, const astring &name_of_file)
67 : astring(directory),
68   _had_directory(true)
69 {
70   // if the directory is empty, use the current directory.
71   if (!directory) {
72     *this = astring(NO_PARENT_DEFAULT);
73     _had_directory = false;
74   }
75   // check for a slash on the end of the directory.  add one if there is none
76   // currently.
77   bool add_slash = false;
78   if ( (directory[directory.end()] != '\\')
79        && (directory[directory.end()] != '/') ) add_slash = true;
80   if (add_slash) *this += DEFAULT_SEPARATOR;
81   *this += name_of_file;
82   canonicalize();
83 }
84
85 filename::filename(const filename &to_copy)
86 : astring(to_copy),
87   _had_directory(to_copy._had_directory)
88 { canonicalize(); }
89
90 filename::~filename() {}
91
92 astring filename::default_separator() { return astring(DEFAULT_SEPARATOR, 1); }
93
94 astring &filename::raw() { return *this; }
95
96 const astring &filename::raw() const { return *this; }
97
98 bool filename::good() const { return exists(); }
99
100 bool filename::unlink() const { return ::unlink(observe()) == 0; }
101
102 void filename::reset(const astring &name) {
103   *this = name;
104   _had_directory = true;  // until we know better.
105   canonicalize();
106 }
107
108 astring filename::null_device()
109 {
110 #ifdef __WIN32__
111   return "null:";
112 #else
113   return "/dev/null";
114 #endif
115 }
116
117 bool filename::separator(char is_it)
118 { return (is_it == pc_separator) || (is_it == unix_separator); }
119
120 filename &filename::operator = (const filename &to_copy)
121 {
122   if (this == &to_copy) return *this;
123   (astring &)(*this) = to_copy;
124   _had_directory = to_copy._had_directory;
125   return *this;
126 }
127
128 filename &filename::operator = (const astring &to_copy)
129 {
130   _had_directory = true;
131   if (this == &to_copy) return *this;
132   (astring &)(*this) = to_copy;
133   canonicalize();
134   return *this;
135 }
136
137 astring filename::pop()
138 {
139   astring to_return = basename();
140   filename parent_dir = parent();
141   if (parent_dir.raw().equal_to(NO_PARENT_DEFAULT)) {
142     // we haven't gone anywhere.
143     return "";  // signal that nothing was removed.
144   }
145   *this = parent_dir;
146   return to_return;
147 }
148
149 filename filename::parent() const { return dirname(); }
150
151 void filename::push(const astring &to_push)
152 {
153   *this = filename(*this, to_push);
154 }
155
156 void filename::canonicalize()
157 {
158   FUNCDEF("canonicalize");
159   // turn all the non-default separators into the default.
160   bool found_sep = false;
161   for (int j = 0; j < length(); j++) {
162     if (separator(get(j))) {
163       found_sep = true;
164       put(j, DEFAULT_SEPARATOR);
165     }
166   }
167
168   // if there wasn't a single directory separator, then they must not have
169   // specified any directory name for this filename (although it could itself
170   // be a directory).
171   if (!found_sep) _had_directory = false;
172
173   // remove all occurrences of double separators except for the first
174   // double set, which could be a UNC filename.  that's why the index below
175   // starts at one rather than zero.
176   bool saw_sep = false;
177   for (int i = 1; i < length(); i++) {
178     if (separator(get(i))) {
179       if (saw_sep) {
180         zap(i, i);
181           // two in a row is no good, except for the first two.
182         i--;  // skip back one and try again.
183         continue;
184       }
185       saw_sep = true;
186     } else saw_sep = false;
187   }
188
189 #ifdef __WIN32__
190   // on windows, we want to translate away from any cygwin or msys format into a more palatable
191   // version that the rest of windows understands.
192   // first, cygwin...
193 //hmmm: make these into statics!
194   const astring CYGDRIVE_SENTINEL = "cygdrive";
195   const astring CYGDRIVE_PATH = astring(astring(DEFAULT_SEPARATOR, 1)
196       + CYGDRIVE_SENTINEL + astring(DEFAULT_SEPARATOR, 1));
197
198   // must be at least as long as the string we're looking for, plus a drive letter afterwards.
199   if ( (length() >= CYGDRIVE_PATH.length() + 1)
200       && separator(get(0))
201       && separator(get(CYGDRIVE_PATH.length() - 1))
202       && compare(CYGDRIVE_SENTINEL, 1, 
203           0, CYGDRIVE_SENTINEL.length(), true) ) {
204     zap(0, CYGDRIVE_PATH.length() - 1);  // whack the cygdrive portion plus two slashes.
205     insert(1, ":");  // add a colon after the imputed drive letter.
206 //LOG(astring("turned cygdrive path string into: ") + *this);
207   } else {
208 //LOG(astring("path didn't match so left as: ") + *this);
209   }
210   // now we convert msys...
211   if ( (length() >= 2) && (get(0) == DEFAULT_SEPARATOR)
212         && textual::parser_bits::is_alpha(get(1)) ) {
213     // we seem reasonably sure now that this is a windows path hiding in msys format, but
214     // the next character needs to be a slash (if there is a next character) for it to be
215     // the windows drive form.  otherwise it could be /tmp, which would obviously not be
216     // intended as a windows path.
217     if ( (length() == 2) || (get(2) == DEFAULT_SEPARATOR) ) {
218       // cool, this should be interpretable as an msys path, except for those wacky types
219       // of folks that might use a top-level single character directory name.  we cannot
220       // help them, because we have made a design decision to support msys-style paths.
221       // note that this would only affect someone if they were referring to their directory on
222       // the current windows partition (c:, d:, etc.) without providing the drive letter,
223       // if they had that single character directory name (e.g., c:\x, d:\q, etc.) and even
224       // then only on the near defunct windows platform.
225       zap(0, 0);  // take off initial slash.
226       insert(1, ":");  // add the obligatory colon.
227 //LOG(astring("turned msys string into: ") + *this);
228     }
229   } 
230 #endif
231
232   // we don't crop the last separator if the name's too small.  for msdos
233   // names, that would be chopping a slash off the c:\ style name.
234   if (length() > 3) {
235     // zap any separators that are hiding on the end.
236     const int last = end();
237     if (separator(get(last))) zap(last, last);
238   } else if ( (length() == 2) && (get(1) == ':') ) {
239     // special case for dos drive names.  we turn it back into a valid
240     // directory rather than leaving it as just "X:".  that form of the name
241     // means something else under dos/windows.
242     *this += astring(DEFAULT_SEPARATOR, 1);
243   }
244 }
245
246 char filename::drive(bool interact_with_fs) const
247 {
248   // first guess: if second letter's a colon, first letter's the drive.
249   if (length() < 2)
250     return '\0';
251   if (get(1) == ':')
252     return get(0);
253   if (!interact_with_fs)
254     return '\0';
255
256   // otherwise, retrieve the file system's record for the file.
257   status_info fill;
258   if (!get_info(&fill))
259     return '\0';
260   return char('A' + fill.st_dev);
261 }
262
263 astring filename::extension() const
264 {
265   astring base(basename().raw());
266   int posn = base.find('.', base.end(), true);
267   if (negative(posn))
268     return "";
269   return base.substring(posn + 1, base.length() - 1);
270 }
271
272 astring filename::rootname() const
273 {
274   astring base(basename().raw());
275   int posn = base.find('.', base.end(), true);
276   if (negative(posn))
277     return base;
278   return base.substring(0, posn - 1);
279 }
280
281 bool filename::get_info(status_info *to_fill) const
282 {
283   int ret = stat(observe(), to_fill);
284   if (ret)
285     return false;
286   return true;
287 }
288
289 bool filename::is_directory() const
290 {
291   status_info fill;
292   if (!get_info(&fill))
293     return false;
294   return !!(fill.st_mode & S_IFDIR);
295 }
296
297 bool filename::is_writable() const
298 {
299   status_info fill;
300   if (!get_info(&fill))
301     return false;
302   return !!(fill.st_mode & S_IWRITE);
303 }
304
305 bool filename::is_readable() const
306 {
307   status_info fill;
308   if (!get_info(&fill))
309     return false;
310   return !!(fill.st_mode & S_IREAD);
311 }
312
313 bool filename::is_executable() const
314 {
315   status_info fill;
316   if (!get_info(&fill))
317     return false;
318   return !!(fill.st_mode & S_IEXEC);
319 }
320
321 bool filename::is_normal() const
322 {
323   status_info fill;
324   if (!get_info(&fill))
325     return false;
326 #if defined(__WIN32__) || defined(__VMS__)
327 //hmmm: is there a corresponding set of functions for windows, where applicable?
328   bool weird = false;
329 #else
330   bool weird = S_ISCHR(fill.st_mode)
331       || S_ISBLK(fill.st_mode)
332       || S_ISFIFO(fill.st_mode)
333       || S_ISSOCK(fill.st_mode);
334 #endif
335   return !weird;
336 }
337
338 int filename::find_last_separator(const astring &look_at) const
339 {
340   int last_sep = -1;
341   int sep = 0;
342   while (sep >= 0) {
343     sep = look_at.find(DEFAULT_SEPARATOR, last_sep + 1);
344     if (sep >= 0) last_sep = sep;
345   }
346   return last_sep;
347 }
348
349 filename filename::basename() const
350 {
351   astring basename = *this;
352   int last_sep = find_last_separator(basename);
353   if (last_sep >= 0) basename.zap(0, last_sep);
354   return basename;
355 }
356
357 filename filename::dirname() const
358 {
359   astring dirname = *this;
360   int last_sep = find_last_separator(dirname);
361   // we don't accept ripping off the first slash.
362   if (last_sep >= 1) {
363     // we can rip the slash and suffix off to get the directory name.  however,
364     // this might be in the form X: on windows.  if they want the slash to
365     // remain, they can use the dirname that appends it.
366     dirname.zap(last_sep, dirname.end());
367   } else {
368     if (get(0) == DEFAULT_SEPARATOR) {
369       // handle when we're up at the top of the filesystem.  on unix, once
370       // you hit the root, you can keep going up but you still remain at
371       // the root.  similarly on windoze, if there's no drive name in there.
372       dirname = astring(DEFAULT_SEPARATOR, 1);
373     } else {
374       // there's no slash at all in the filename any more.  we assume that
375       // the directory is the current one, if no other information is
376       // available.  this default is already used by some code.
377       dirname = NO_PARENT_DEFAULT;
378     }
379   }
380   return dirname;
381 }
382
383 astring filename::dirname(bool add_slash) const
384 {
385   astring tempname = dirname().raw();
386   if (add_slash) tempname += DEFAULT_SEPARATOR;
387   return tempname;
388 }
389
390 bool filename::exists() const
391 {
392   if (is_directory())
393     return true;
394   // if the file name is empty, that cannot exist.
395   if (!length())
396     return false;
397   return is_readable();
398 }
399
400 bool filename::legal_character(char to_check)
401 {
402   switch (to_check) {
403     case ':': case ';':
404     case '\\': case '/':
405     case '*': case '?': case '$': case '&': case '|':
406     case '\'': case '"': case '`':
407     case '(': case ')':
408     case '[': case ']':
409     case '<': case '>':
410     case '{': case '}':
411       return false;
412     default: return true;
413   }
414 }
415
416 void filename::detooth_filename(astring &to_clean, char replacement)
417 {
418   for (int i = 0; i < to_clean.length(); i++) {
419     if (!legal_character(to_clean[i]))
420       to_clean[i] = replacement;
421   }
422 }
423
424 int filename::packed_size() const
425 {
426   return PACKED_SIZE_INT32 + astring::packed_size();
427 }
428
429 void filename::pack(byte_array &packed_form) const
430 {
431   attach(packed_form, int(_had_directory));
432   astring::pack(packed_form);
433 }
434
435 bool filename::unpack(byte_array &packed_form)
436 {
437   int temp;
438   if (!detach(packed_form, temp))
439     return false;
440   _had_directory = temp;
441   if (!astring::unpack(packed_form))
442     return false;
443   return true;
444 }
445
446 void filename::separate(bool &rooted, string_array &pieces) const
447 {
448   pieces.reset();
449   const astring &raw_form = raw();
450   astring accumulator;  // holds the names we find.
451   rooted = raw_form.length() && separator(raw_form[0]);
452   for (int i = 0; i < raw_form.length(); i++) {
453     if (separator(raw_form[i])) {
454       // this is a separator character, so eat it and add the accumulated
455       // string to the list.
456       if (i && accumulator.length()) pieces += accumulator;
457       // now reset our accumulated text.
458       accumulator = astring::empty_string();
459     } else {
460       // not a separator, so just accumulate it.
461       accumulator += raw_form[i];
462     }
463   }
464   if (accumulator.length()) pieces += accumulator;
465 }
466
467 void filename::join(bool rooted, const string_array &pieces)
468 {
469   astring constructed_name;  // we'll make a filename here.
470   if (rooted) constructed_name += DEFAULT_SEPARATOR;
471   for (int i = 0; i < pieces.length(); i++) {
472     constructed_name += pieces[i];
473     if (!i || (i != pieces.length() - 1))
474       constructed_name += DEFAULT_SEPARATOR;
475   }
476   *this = constructed_name;
477 }
478
479 bool filename::base_compare_prefix(const filename &to_compare,
480     string_array &first, string_array &second)
481 {
482   bool first_rooted;
483   separate(first_rooted, first);
484   bool second_rooted;
485   to_compare.separate(second_rooted, second);
486   if (first_rooted != second_rooted) {
487     return false;
488   }
489   // that case should never be allowed, since there are some bits missing
490   // in the name to be compared.
491   if (first.length() > second.length())
492     return false;
493
494   // compare each of the pieces.
495   for (int i = 0; i < first.length(); i++) {
496 #if defined(__WIN32__) || defined(__VMS__)
497     // case-insensitive compare.
498     if (!first[i].iequals(second[i]))
499       return false;
500 #else
501     // case-sensitive compare.
502     if (first[i] != second[i])
503       return false;
504 #endif
505   }
506   return true;
507 }
508
509 bool filename::compare_prefix(const filename &to_compare, astring &sequel)
510 {
511   sequel = astring::empty_string();  // clean our output parameter.
512   string_array first;
513   string_array second;
514   if (!base_compare_prefix(to_compare, first, second))
515     return false;
516
517   // create the sequel string.
518   int extra_strings = second.length() - first.length();
519   for (int i = second.length() - extra_strings; i < second.length(); i++) {
520     sequel += second[i];
521     if (i != second.length() - 1) sequel += DEFAULT_SEPARATOR;
522   }
523
524   return true;
525 }
526
527 bool filename::compare_prefix(const filename &to_compare)
528 {
529   string_array first;
530   string_array second;
531   return base_compare_prefix(to_compare, first, second);
532 }
533
534 bool filename::base_compare_suffix(const filename &to_compare,
535     string_array &first, string_array &second)
536 {
537   bool first_rooted;
538   separate(first_rooted, first);
539   bool second_rooted;
540   to_compare.separate(second_rooted, second);
541   // that case should never be allowed, since there are some bits missing
542   // in the name to be compared.
543   if (first.length() > second.length())
544     return false;
545
546   // compare each of the pieces.
547   for (int i = first.length() - 1; i >= 0; i--) {
548 //clean up this computation; the difference in lengths is constant--use that.
549     int distance_from_end = first.length() - 1 - i;
550     int j = second.length() - 1 - distance_from_end;
551 #if defined(__WIN32__) || defined(__VMS__)
552     // case-insensitive compare.
553     if (!first[i].iequals(second[j]))
554       return false;
555 #else
556     // case-sensitive compare.
557     if (first[i] != second[j])
558       return false;
559 #endif
560   }
561   return true;
562 }
563
564 bool filename::compare_suffix(const filename &to_compare, astring &prequel)
565 {
566   prequel = astring::empty_string();  // clean our output parameter.
567   string_array first;
568   string_array second;
569   if (!base_compare_suffix(to_compare, first, second))
570     return false;
571
572   // create the prequel string.
573   int extra_strings = second.length() - first.length();
574   for (int i = 0; i < extra_strings; i++) {
575     prequel += second[i];
576     if (i != second.length() - 1) prequel += DEFAULT_SEPARATOR;
577   }
578   return true;
579 }
580
581 bool filename::compare_suffix(const filename &to_compare)
582 {
583   string_array first;
584   string_array second;
585   return base_compare_suffix(to_compare, first, second);
586 }
587
588 bool filename::chmod(int write_mode, int owner_mode) const
589 {
590   int chmod_value = 0;
591 #ifdef __UNIX__
592   if (write_mode & ALLOW_READ) {
593     if (owner_mode & USER_RIGHTS) chmod_value |= S_IRUSR;
594     if (owner_mode & GROUP_RIGHTS) chmod_value |= S_IRGRP;
595     if (owner_mode & OTHER_RIGHTS) chmod_value |= S_IROTH;
596   }
597   if (write_mode & ALLOW_WRITE) {
598     if (owner_mode & USER_RIGHTS) chmod_value |= S_IWUSR;
599     if (owner_mode & GROUP_RIGHTS) chmod_value |= S_IWGRP;
600     if (owner_mode & OTHER_RIGHTS) chmod_value |= S_IWOTH;
601   }
602 ////  chmod_value = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
603 #elif defined(__WIN32__)
604   if (write_mode & ALLOW_READ) {
605     chmod_value |= _S_IREAD;
606   }
607   if (write_mode & ALLOW_WRITE) {
608     chmod_value |= _S_IWRITE;
609   }
610 #else
611   #error unsupported OS type currently.
612 #endif
613   int chmod_result = ::chmod(raw().s(), chmod_value);
614   if (chmod_result) {
615 //    LOG(astring("there was a problem changing permissions on ") + raw());
616     return false;
617   }
618   return true;
619 }
620
621 } //namespace.
622