lots of mods getting windows to build under cygwin without visual studio.
[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   const astring CYGDRIVE_PATH = astring(astring(DEFAULT_SEPARATOR, 1) + "cygdrive"
194       + astring(DEFAULT_SEPARATOR, 1));
195   // must be at least as long as the string we're looking for, plus a drive letter afterwards.
196   if ( (length() > CYGDRIVE_PATH.length() + 1) && begins(CYGDRIVE_PATH) ) {
197     zap(0, CYGDRIVE_PATH.length() - 1);  // whack the cygdrive portion plus two slashes.
198     insert(1, ":");  // add a colon after the imputed drive letter.
199 //LOG(astring("turned cygdrive string into: ") + *this);
200   }
201   // now we convert msys...
202   if ( (length() >= 2) && (get(0) == DEFAULT_SEPARATOR)
203         && textual::parser_bits::is_alpha(get(1)) ) {
204     // we seem reasonably sure now that this is a windows path hiding in msys format, but
205     // the next character needs to be a slash (if there is a next character) for it to be
206     // the windows drive form.  otherwise it could be /tmp, which would obviously not be
207     // intended as a windows path.
208     if ( (length() == 2) || (get(2) == DEFAULT_SEPARATOR) ) {
209       // cool, this should be interpretable as an msys path, except for those wacky types
210       // of folks that might use a top-level single character directory name.  we cannot
211       // help them, because we have made a design decision to support msys-style paths.
212       // note that this would only affect someone if they were referring to their directory on
213       // the current windows partition (c:, d:, etc.) without providing the drive letter,
214       // if they had that single character directory name (e.g., c:\x, d:\q, etc.) and even
215       // then only on the near defunct windows platform.
216       zap(0, 0);  // take off initial slash.
217       insert(1, ":");  // add the obligatory colon.
218 //LOG(astring("turned msys string into: ") + *this);
219     }
220   } 
221 #endif
222
223   // we don't crop the last separator if the name's too small.  for msdos
224   // names, that would be chopping a slash off the c:\ style name.
225   if (length() > 3) {
226     // zap any separators that are hiding on the end.
227     const int last = end();
228     if (separator(get(last))) zap(last, last);
229   } else if ( (length() == 2) && (get(1) == ':') ) {
230     // special case for dos drive names.  we turn it back into a valid
231     // directory rather than leaving it as just "X:".  that form of the name
232     // means something else under dos/windows.
233     *this += astring(DEFAULT_SEPARATOR, 1);
234   }
235 }
236
237 char filename::drive(bool interact_with_fs) const
238 {
239   // first guess: if second letter's a colon, first letter's the drive.
240   if (length() < 2)
241     return '\0';
242   if (get(1) == ':')
243     return get(0);
244   if (!interact_with_fs)
245     return '\0';
246
247   // otherwise, retrieve the file system's record for the file.
248   status_info fill;
249   if (!get_info(&fill))
250     return '\0';
251   return char('A' + fill.st_dev);
252 }
253
254 astring filename::extension() const
255 {
256   astring base(basename().raw());
257   int posn = base.find('.', base.end(), true);
258   if (negative(posn))
259     return "";
260   return base.substring(posn + 1, base.length() - 1);
261 }
262
263 astring filename::rootname() const
264 {
265   astring base(basename().raw());
266   int posn = base.find('.', base.end(), true);
267   if (negative(posn))
268     return base;
269   return base.substring(0, posn - 1);
270 }
271
272 bool filename::get_info(status_info *to_fill) const
273 {
274   int ret = stat(observe(), to_fill);
275   if (ret)
276     return false;
277   return true;
278 }
279
280 bool filename::is_directory() const
281 {
282   status_info fill;
283   if (!get_info(&fill))
284     return false;
285   return !!(fill.st_mode & S_IFDIR);
286 }
287
288 bool filename::is_writable() const
289 {
290   status_info fill;
291   if (!get_info(&fill))
292     return false;
293   return !!(fill.st_mode & S_IWRITE);
294 }
295
296 bool filename::is_readable() const
297 {
298   status_info fill;
299   if (!get_info(&fill))
300     return false;
301   return !!(fill.st_mode & S_IREAD);
302 }
303
304 bool filename::is_executable() const
305 {
306   status_info fill;
307   if (!get_info(&fill))
308     return false;
309   return !!(fill.st_mode & S_IEXEC);
310 }
311
312 bool filename::is_normal() const
313 {
314   status_info fill;
315   if (!get_info(&fill))
316     return false;
317 #if defined(__WIN32__) || defined(__VMS__)
318 //hmmm: is there a corresponding set of functions for windows, where applicable?
319   bool weird = false;
320 #else
321   bool weird = S_ISCHR(fill.st_mode)
322       || S_ISBLK(fill.st_mode)
323       || S_ISFIFO(fill.st_mode)
324       || S_ISSOCK(fill.st_mode);
325 #endif
326   return !weird;
327 }
328
329 int filename::find_last_separator(const astring &look_at) const
330 {
331   int last_sep = -1;
332   int sep = 0;
333   while (sep >= 0) {
334     sep = look_at.find(DEFAULT_SEPARATOR, last_sep + 1);
335     if (sep >= 0) last_sep = sep;
336   }
337   return last_sep;
338 }
339
340 filename filename::basename() const
341 {
342   astring basename = *this;
343   int last_sep = find_last_separator(basename);
344   if (last_sep >= 0) basename.zap(0, last_sep);
345   return basename;
346 }
347
348 filename filename::dirname() const
349 {
350   astring dirname = *this;
351   int last_sep = find_last_separator(dirname);
352   // we don't accept ripping off the first slash.
353   if (last_sep >= 1) {
354     // we can rip the slash and suffix off to get the directory name.  however,
355     // this might be in the form X: on windows.  if they want the slash to
356     // remain, they can use the dirname that appends it.
357     dirname.zap(last_sep, dirname.end());
358   } else {
359     if (get(0) == DEFAULT_SEPARATOR) {
360       // handle when we're up at the top of the filesystem.  on unix, once
361       // you hit the root, you can keep going up but you still remain at
362       // the root.  similarly on windoze, if there's no drive name in there.
363       dirname = astring(DEFAULT_SEPARATOR, 1);
364     } else {
365       // there's no slash at all in the filename any more.  we assume that
366       // the directory is the current one, if no other information is
367       // available.  this default is already used by some code.
368       dirname = NO_PARENT_DEFAULT;
369     }
370   }
371   return dirname;
372 }
373
374 astring filename::dirname(bool add_slash) const
375 {
376   astring tempname = dirname().raw();
377   if (add_slash) tempname += DEFAULT_SEPARATOR;
378   return tempname;
379 }
380
381 bool filename::exists() const
382 {
383   if (is_directory())
384     return true;
385   // if the file name is empty, that cannot exist.
386   if (!length())
387     return false;
388   return is_readable();
389 }
390
391 bool filename::legal_character(char to_check)
392 {
393   switch (to_check) {
394     case ':': case ';':
395     case '\\': case '/':
396     case '*': case '?': case '$': case '&': case '|':
397     case '\'': case '"': case '`':
398     case '(': case ')':
399     case '[': case ']':
400     case '<': case '>':
401     case '{': case '}':
402       return false;
403     default: return true;
404   }
405 }
406
407 void filename::detooth_filename(astring &to_clean, char replacement)
408 {
409   for (int i = 0; i < to_clean.length(); i++) {
410     if (!legal_character(to_clean[i]))
411       to_clean[i] = replacement;
412   }
413 }
414
415 int filename::packed_size() const
416 {
417   return PACKED_SIZE_INT32 + astring::packed_size();
418 }
419
420 void filename::pack(byte_array &packed_form) const
421 {
422   attach(packed_form, int(_had_directory));
423   astring::pack(packed_form);
424 }
425
426 bool filename::unpack(byte_array &packed_form)
427 {
428   int temp;
429   if (!detach(packed_form, temp))
430     return false;
431   _had_directory = temp;
432   if (!astring::unpack(packed_form))
433     return false;
434   return true;
435 }
436
437 void filename::separate(bool &rooted, string_array &pieces) const
438 {
439   pieces.reset();
440   const astring &raw_form = raw();
441   astring accumulator;  // holds the names we find.
442   rooted = raw_form.length() && separator(raw_form[0]);
443   for (int i = 0; i < raw_form.length(); i++) {
444     if (separator(raw_form[i])) {
445       // this is a separator character, so eat it and add the accumulated
446       // string to the list.
447       if (i && accumulator.length()) pieces += accumulator;
448       // now reset our accumulated text.
449       accumulator = astring::empty_string();
450     } else {
451       // not a separator, so just accumulate it.
452       accumulator += raw_form[i];
453     }
454   }
455   if (accumulator.length()) pieces += accumulator;
456 }
457
458 void filename::join(bool rooted, const string_array &pieces)
459 {
460   astring constructed_name;  // we'll make a filename here.
461   if (rooted) constructed_name += DEFAULT_SEPARATOR;
462   for (int i = 0; i < pieces.length(); i++) {
463     constructed_name += pieces[i];
464     if (!i || (i != pieces.length() - 1))
465       constructed_name += DEFAULT_SEPARATOR;
466   }
467   *this = constructed_name;
468 }
469
470 bool filename::base_compare_prefix(const filename &to_compare,
471     string_array &first, string_array &second)
472 {
473   bool first_rooted;
474   separate(first_rooted, first);
475   bool second_rooted;
476   to_compare.separate(second_rooted, second);
477   if (first_rooted != second_rooted) {
478     return false;
479   }
480   // that case should never be allowed, since there are some bits missing
481   // in the name to be compared.
482   if (first.length() > second.length())
483     return false;
484
485   // compare each of the pieces.
486   for (int i = 0; i < first.length(); i++) {
487 #if defined(__WIN32__) || defined(__VMS__)
488     // case-insensitive compare.
489     if (!first[i].iequals(second[i]))
490       return false;
491 #else
492     // case-sensitive compare.
493     if (first[i] != second[i])
494       return false;
495 #endif
496   }
497   return true;
498 }
499
500 bool filename::compare_prefix(const filename &to_compare, astring &sequel)
501 {
502   sequel = astring::empty_string();  // clean our output parameter.
503   string_array first;
504   string_array second;
505   if (!base_compare_prefix(to_compare, first, second))
506     return false;
507
508   // create the sequel string.
509   int extra_strings = second.length() - first.length();
510   for (int i = second.length() - extra_strings; i < second.length(); i++) {
511     sequel += second[i];
512     if (i != second.length() - 1) sequel += DEFAULT_SEPARATOR;
513   }
514
515   return true;
516 }
517
518 bool filename::compare_prefix(const filename &to_compare)
519 {
520   string_array first;
521   string_array second;
522   return base_compare_prefix(to_compare, first, second);
523 }
524
525 bool filename::base_compare_suffix(const filename &to_compare,
526     string_array &first, string_array &second)
527 {
528   bool first_rooted;
529   separate(first_rooted, first);
530   bool second_rooted;
531   to_compare.separate(second_rooted, second);
532   // that case should never be allowed, since there are some bits missing
533   // in the name to be compared.
534   if (first.length() > second.length())
535     return false;
536
537   // compare each of the pieces.
538   for (int i = first.length() - 1; i >= 0; i--) {
539 //clean up this computation; the difference in lengths is constant--use that.
540     int distance_from_end = first.length() - 1 - i;
541     int j = second.length() - 1 - distance_from_end;
542 #if defined(__WIN32__) || defined(__VMS__)
543     // case-insensitive compare.
544     if (!first[i].iequals(second[j]))
545       return false;
546 #else
547     // case-sensitive compare.
548     if (first[i] != second[j])
549       return false;
550 #endif
551   }
552   return true;
553 }
554
555 bool filename::compare_suffix(const filename &to_compare, astring &prequel)
556 {
557   prequel = astring::empty_string();  // clean our output parameter.
558   string_array first;
559   string_array second;
560   if (!base_compare_suffix(to_compare, first, second))
561     return false;
562
563   // create the prequel string.
564   int extra_strings = second.length() - first.length();
565   for (int i = 0; i < extra_strings; i++) {
566     prequel += second[i];
567     if (i != second.length() - 1) prequel += DEFAULT_SEPARATOR;
568   }
569   return true;
570 }
571
572 bool filename::compare_suffix(const filename &to_compare)
573 {
574   string_array first;
575   string_array second;
576   return base_compare_suffix(to_compare, first, second);
577 }
578
579 bool filename::chmod(int write_mode, int owner_mode) const
580 {
581   int chmod_value = 0;
582 #ifdef __UNIX__
583   if (write_mode & ALLOW_READ) {
584     if (owner_mode & USER_RIGHTS) chmod_value |= S_IRUSR;
585     if (owner_mode & GROUP_RIGHTS) chmod_value |= S_IRGRP;
586     if (owner_mode & OTHER_RIGHTS) chmod_value |= S_IROTH;
587   }
588   if (write_mode & ALLOW_WRITE) {
589     if (owner_mode & USER_RIGHTS) chmod_value |= S_IWUSR;
590     if (owner_mode & GROUP_RIGHTS) chmod_value |= S_IWGRP;
591     if (owner_mode & OTHER_RIGHTS) chmod_value |= S_IWOTH;
592   }
593 ////  chmod_value = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
594 #elif defined(__WIN32__)
595   if (write_mode & ALLOW_READ) {
596     chmod_value |= _S_IREAD;
597   }
598   if (write_mode & ALLOW_WRITE) {
599     chmod_value |= _S_IWRITE;
600   }
601 #else
602   #error unsupported OS type currently.
603 #endif
604   int chmod_result = ::chmod(raw().s(), chmod_value);
605   if (chmod_result) {
606 //    LOG(astring("there was a problem changing permissions on ") + raw());
607     return false;
608   }
609   return true;
610 }
611
612 } //namespace.
613