1 /*****************************************************************************\
4 * Author : Chris Koeritz *
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 \*****************************************************************************/
15 // implementation note: the filename is kept canonicalized. any constructor
16 // or assignment operator should ensure this (except the blank constructor).
20 #include <basis/byte_array.h>
21 #include <basis/functions.h>
22 #include <textual/parser_bits.h>
26 #include <sys/types.h>
35 #define LOG(to_print) printf("%s::%s: %s\n", static_class_name(), func, astring(to_print).s())
37 using namespace basis;
38 using namespace structures;
40 class status_info : public stat
44 namespace filesystem {
46 #if defined(__WIN32__) || defined(__VMS__)
47 const char DEFAULT_SEPARATOR = '\\';
48 #elif defined(__UNIX__)
49 const char DEFAULT_SEPARATOR = '/';
51 #error "We have no idea what the default path separator is."
54 const char *NO_PARENT_DEFAULT = ".";
55 // used when no directory name can be popped off.
62 filename::filename(const astring &name)
67 filename::filename(const astring &directory, const astring &name_of_file)
71 // if the directory is empty, use the current directory.
73 *this = astring(NO_PARENT_DEFAULT);
74 _had_directory = false;
76 // check for a slash on the end of the directory. add one if there is none
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;
86 filename::filename(const filename &to_copy)
88 _had_directory(to_copy._had_directory)
91 filename::~filename() {}
93 astring filename::default_separator() { return astring(DEFAULT_SEPARATOR, 1); }
95 astring &filename::raw() { return *this; }
97 const astring &filename::raw() const { return *this; }
99 bool filename::good() const { return exists(); }
101 bool filename::unlink() const { return ::unlink(observe()) == 0; }
103 astring filename::null_device()
112 bool filename::separator(char is_it)
113 { return (is_it == pc_separator) || (is_it == unix_separator); }
115 filename &filename::operator = (const filename &to_copy)
117 if (this == &to_copy) return *this;
118 (astring &)(*this) = to_copy;
119 _had_directory = to_copy._had_directory;
123 filename &filename::operator = (const astring &to_copy)
125 _had_directory = true;
126 if (this == &to_copy) return *this;
127 (astring &)(*this) = to_copy;
132 astring filename::pop()
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.
144 filename filename::parent() const { return dirname(); }
146 void filename::push(const astring &to_push)
148 *this = filename(*this, to_push);
151 void filename::canonicalize()
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))) {
159 put(j, DEFAULT_SEPARATOR);
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
166 if (!found_sep) _had_directory = false;
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))) {
176 // two in a row is no good, except for the first two.
177 i--; // skip back one and try again.
181 } else saw_sep = false;
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.
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 LOG(astring("turned cygdrive string into: ") + *this);
196 // now we convert msys...
197 if ( (length() >= 2) && (get(0) == DEFAULT_SEPARATOR)
198 && textual::parser_bits::is_alpha(get(1)) ) {
199 // we seem reasonably sure now that this is a windows path hiding in msys format, but
200 // the next character needs to be a slash (if there is a next character) for it to be
201 // the windows drive form. otherwise it could be /tmp, which would obviously not be
202 // intended as a windows path.
203 if ( (length() == 2) || (get(2) == DEFAULT_SEPARATOR) ) {
204 // cool, this should be interpretable as an msys path, except for those wacky types
205 // of folks that might use a top-level single character directory name. we cannot
206 // help them, because we have made a design decision to support msys-style paths.
207 // note that this would only affect someone if they were referring to their directory on
208 // the current windows partition (c:, d:, etc.) without providing the drive letter,
209 // if they had that single character directory name (e.g., c:\x, d:\q, etc.) and even
210 // then only on the near defunct windows platform.
211 zap(0, 0); // take off initial slash.
212 insert(1, ":"); // add the obligatory colon.
213 LOG(astring("turned msys string into: ") + *this);
218 // we don't crop the last separator if the name's too small. for msdos
219 // names, that would be chopping a slash off the c:\ style name.
221 // zap any separators that are hiding on the end.
222 const int last = end();
223 if (separator(get(last))) zap(last, last);
224 } else if ( (length() == 2) && (get(1) == ':') ) {
225 // special case for dos drive names. we turn it back into a valid
226 // directory rather than leaving it as just "X:". that form of the name
227 // means something else under dos/windows.
228 *this += astring(DEFAULT_SEPARATOR, 1);
232 char filename::drive(bool interact_with_fs) const
234 // first guess: if second letter's a colon, first letter's the drive.
239 if (!interact_with_fs)
242 // otherwise, retrieve the file system's record for the file.
244 if (!get_info(&fill))
246 return char('A' + fill.st_dev);
249 astring filename::extension() const
251 astring base(basename().raw());
252 int posn = base.find('.', base.end(), true);
255 return base.substring(posn + 1, base.length() - 1);
258 astring filename::rootname() const
260 astring base(basename().raw());
261 int posn = base.find('.', base.end(), true);
264 return base.substring(0, posn - 1);
267 bool filename::get_info(status_info *to_fill) const
269 int ret = stat(observe(), to_fill);
275 bool filename::is_directory() const
278 if (!get_info(&fill))
280 return !!(fill.st_mode & S_IFDIR);
283 bool filename::is_writable() const
286 if (!get_info(&fill))
288 return !!(fill.st_mode & S_IWRITE);
291 bool filename::is_readable() const
294 if (!get_info(&fill))
296 return !!(fill.st_mode & S_IREAD);
299 bool filename::is_executable() const
302 if (!get_info(&fill))
304 return !!(fill.st_mode & S_IEXEC);
307 int filename::find_last_separator(const astring &look_at) const
312 sep = look_at.find(DEFAULT_SEPARATOR, last_sep + 1);
313 if (sep >= 0) last_sep = sep;
318 filename filename::basename() const
320 astring basename = *this;
321 int last_sep = find_last_separator(basename);
322 if (last_sep >= 0) basename.zap(0, last_sep);
326 filename filename::dirname() const
328 astring dirname = *this;
329 int last_sep = find_last_separator(dirname);
330 // we don't accept ripping off the first slash.
332 // we can rip the slash and suffix off to get the directory name. however,
333 // this might be in the form X: on windows. if they want the slash to
334 // remain, they can use the dirname that appends it.
335 dirname.zap(last_sep, dirname.end());
337 if (get(0) == DEFAULT_SEPARATOR) {
338 // handle when we're up at the top of the filesystem. on unix, once
339 // you hit the root, you can keep going up but you still remain at
340 // the root. similarly on windoze, if there's no drive name in there.
341 dirname = astring(DEFAULT_SEPARATOR, 1);
343 // there's no slash at all in the filename any more. we assume that
344 // the directory is the current one, if no other information is
345 // available. this default is already used by some code.
346 dirname = NO_PARENT_DEFAULT;
352 astring filename::dirname(bool add_slash) const
354 astring tempname = dirname().raw();
355 if (add_slash) tempname += DEFAULT_SEPARATOR;
359 bool filename::exists() const
365 return is_readable();
366 /// byte_filer opened(observe(), "rb");
367 /// return opened.good();
370 bool filename::legal_character(char to_check)
375 case '*': case '?': case '$': case '&': case '|':
376 case '\'': case '"': case '`':
382 default: return true;
386 void filename::detooth_filename(astring &to_clean, char replacement)
388 for (int i = 0; i < to_clean.length(); i++) {
389 if (!legal_character(to_clean[i]))
390 to_clean[i] = replacement;
394 int filename::packed_size() const
396 return PACKED_SIZE_INT32 + astring::packed_size();
399 void filename::pack(byte_array &packed_form) const
401 attach(packed_form, int(_had_directory));
402 astring::pack(packed_form);
405 bool filename::unpack(byte_array &packed_form)
408 if (!detach(packed_form, temp))
410 _had_directory = temp;
411 if (!astring::unpack(packed_form))
416 void filename::separate(string_array &pieces) const
419 const astring &raw_form = raw();
420 astring accumulator; // holds the names we find.
421 for (int i = 0; i < raw_form.length(); i++) {
422 if (separator(raw_form[i])) {
423 // this is a separator character, so eat it and add the accumulated
424 // string to the list.
425 if (!i || accumulator.length()) pieces += accumulator;
426 // now reset our accumulated text.
427 accumulator = astring::empty_string();
429 // not a separator, so just accumulate it.
430 accumulator += raw_form[i];
433 if (accumulator.length()) pieces += accumulator;
436 void filename::join(const string_array &pieces)
438 astring constructed_name; // we'll make a filename here.
439 for (int i = 0; i < pieces.length(); i++) {
440 constructed_name += pieces[i];
441 if (!i || (i != pieces.length() - 1))
442 constructed_name += DEFAULT_SEPARATOR;
444 *this = constructed_name;
447 bool filename::base_compare_prefix(const filename &to_compare,
448 string_array &first, string_array &second)
451 to_compare.separate(second);
452 // that case should never be allowed, since there are some bits missing
453 // in the name to be compared.
454 if (first.length() > second.length())
457 // compare each of the pieces.
458 for (int i = 0; i < first.length(); i++) {
459 #if defined(__WIN32__) || defined(__VMS__)
460 // case-insensitive compare.
461 if (!first[i].iequals(second[i]))
464 // case-sensitive compare.
465 if (first[i] != second[i])
472 bool filename::compare_prefix(const filename &to_compare, astring &sequel)
474 sequel = astring::empty_string(); // clean our output parameter.
477 if (!base_compare_prefix(to_compare, first, second))
480 // create the sequel string.
481 int extra_strings = second.length() - first.length();
482 for (int i = second.length() - extra_strings; i < second.length(); i++) {
484 if (i != second.length() - 1) sequel += DEFAULT_SEPARATOR;
490 bool filename::compare_prefix(const filename &to_compare)
494 return base_compare_prefix(to_compare, first, second);
497 bool filename::base_compare_suffix(const filename &to_compare,
498 string_array &first, string_array &second)
501 to_compare.separate(second);
502 // that case should never be allowed, since there are some bits missing
503 // in the name to be compared.
504 if (first.length() > second.length())
507 // compare each of the pieces.
508 for (int i = first.length() - 1; i >= 0; i--) {
509 //clean up this computation; the difference in lengths is constant--use that.
510 int distance_from_end = first.length() - 1 - i;
511 int j = second.length() - 1 - distance_from_end;
512 #if defined(__WIN32__) || defined(__VMS__)
513 // case-insensitive compare.
514 if (!first[i].iequals(second[j]))
517 // case-sensitive compare.
518 if (first[i] != second[j])
525 bool filename::compare_suffix(const filename &to_compare, astring &prequel)
527 prequel = astring::empty_string(); // clean our output parameter.
530 if (!base_compare_suffix(to_compare, first, second))
533 // create the prequel string.
534 int extra_strings = second.length() - first.length();
535 for (int i = 0; i < extra_strings; i++) {
536 prequel += second[i];
537 if (i != second.length() - 1) prequel += DEFAULT_SEPARATOR;
542 bool filename::compare_suffix(const filename &to_compare)
546 return base_compare_suffix(to_compare, first, second);
549 bool filename::chmod(int write_mode, int owner_mode) const
553 if (write_mode & ALLOW_READ) {
554 if (owner_mode & USER_RIGHTS) chmod_value |= S_IRUSR;
555 if (owner_mode & GROUP_RIGHTS) chmod_value |= S_IRGRP;
556 if (owner_mode & OTHER_RIGHTS) chmod_value |= S_IROTH;
558 if (write_mode & ALLOW_WRITE) {
559 if (owner_mode & USER_RIGHTS) chmod_value |= S_IWUSR;
560 if (owner_mode & GROUP_RIGHTS) chmod_value |= S_IWGRP;
561 if (owner_mode & OTHER_RIGHTS) chmod_value |= S_IWOTH;
563 //// chmod_value = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
564 #elif defined(__WIN32__)
565 if (write_mode & ALLOW_READ) {
566 chmod_value |= _S_IREAD;
568 if (write_mode & ALLOW_WRITE) {
569 chmod_value |= _S_IWRITE;
572 #error unsupported OS type currently.
574 int chmod_result = ::chmod(raw().s(), chmod_value);
576 // LOG(astring("there was a problem changing permissions on ") + raw());