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