* ext/socket/socket.c: use PRIuSIZE.
[ruby-svn.git] / dir.c
blobcf278dc4a75de40944f2ecd2b331937330004efa
1 /**********************************************************************
3 dir.c -
5 $Author$
6 created at: Wed Jan 5 09:51:01 JST 1994
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9 Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
10 Copyright (C) 2000 Information-technology Promotion Agency, Japan
12 **********************************************************************/
14 #include "ruby/ruby.h"
15 #include "ruby/encoding.h"
17 #include <sys/types.h>
18 #include <sys/stat.h>
20 #ifdef HAVE_UNISTD_H
21 #include <unistd.h>
22 #endif
24 #if defined HAVE_DIRENT_H && !defined _WIN32
25 # include <dirent.h>
26 # define NAMLEN(dirent) strlen((dirent)->d_name)
27 #elif defined HAVE_DIRECT_H && !defined _WIN32
28 # include <direct.h>
29 # define NAMLEN(dirent) strlen((dirent)->d_name)
30 #else
31 # define dirent direct
32 # if !defined __NeXT__
33 # define NAMLEN(dirent) (dirent)->d_namlen
34 # else
35 # /* On some versions of NextStep, d_namlen is always zero, so avoid it. */
36 # define NAMLEN(dirent) strlen((dirent)->d_name)
37 # endif
38 # if HAVE_SYS_NDIR_H
39 # include <sys/ndir.h>
40 # endif
41 # if HAVE_SYS_DIR_H
42 # include <sys/dir.h>
43 # endif
44 # if HAVE_NDIR_H
45 # include <ndir.h>
46 # endif
47 # ifdef _WIN32
48 # include "win32/dir.h"
49 # endif
50 #endif
52 #include <errno.h>
54 #ifndef HAVE_STDLIB_H
55 char *getenv();
56 #endif
58 #ifndef HAVE_STRING_H
59 char *strchr(char*,char);
60 #endif
62 #include <ctype.h>
64 #include "ruby/util.h"
66 #if !defined HAVE_LSTAT && !defined lstat
67 #define lstat stat
68 #endif
70 #define FNM_NOESCAPE 0x01
71 #define FNM_PATHNAME 0x02
72 #define FNM_DOTMATCH 0x04
73 #define FNM_CASEFOLD 0x08
74 #if CASEFOLD_FILESYSTEM
75 #define FNM_SYSCASE FNM_CASEFOLD
76 #else
77 #define FNM_SYSCASE 0
78 #endif
80 #define FNM_NOMATCH 1
81 #define FNM_ERROR 2
83 # define Next(p, e, enc) (p + rb_enc_mbclen(p, e, enc))
84 # define Inc(p, e, enc) ((p) = Next(p, e, enc))
86 static int
87 char_casecmp(const char *p1, const char *p2, rb_encoding *enc, const int nocase)
89 const char *p1end, *p2end;
90 int c1, c2;
92 if (!*p1) return *p1;
93 if (!*p2) return -*p2;
94 p1end = p1 + strlen(p1);
95 p2end = p2 + strlen(p2);
96 c1 = rb_enc_codepoint(p1, p1end, enc);
97 c2 = rb_enc_codepoint(p2, p2end, enc);
99 if (c1 == c2) return 0;
100 if (nocase) {
101 c1 = rb_enc_toupper(c1, enc);
102 c2 = rb_enc_toupper(c2, enc);
104 return c1 - c2;
107 static char *
108 bracket(
109 const char *p, /* pattern (next to '[') */
110 const char *s, /* string */
111 int flags,
112 rb_encoding *enc)
114 const char *pend = p + strlen(p);
115 const int nocase = flags & FNM_CASEFOLD;
116 const int escape = !(flags & FNM_NOESCAPE);
118 int ok = 0, not = 0;
120 if (*p == '!' || *p == '^') {
121 not = 1;
122 p++;
125 while (*p != ']') {
126 const char *t1 = p;
127 if (escape && *t1 == '\\')
128 t1++;
129 if (!*t1)
130 return NULL;
131 p = Next(t1, pend, enc);
132 if (p[0] == '-' && p[1] != ']') {
133 const char *t2 = p + 1;
134 if (escape && *t2 == '\\')
135 t2++;
136 if (!*t2)
137 return NULL;
138 p = Next(t2, pend, enc);
139 if (!ok && char_casecmp(t1, s, enc, nocase) <= 0 && char_casecmp(s, t2, enc, nocase) <= 0)
140 ok = 1;
142 else
143 if (!ok && char_casecmp(t1, s, enc, nocase) == 0)
144 ok = 1;
147 return ok == not ? NULL : (char *)p + 1;
150 /* If FNM_PATHNAME is set, only path element will be matched. (upto '/' or '\0')
151 Otherwise, entire string will be matched.
152 End marker itself won't be compared.
153 And if function succeeds, *pcur reaches end marker.
155 #define UNESCAPE(p) (escape && *(p) == '\\' ? (p) + 1 : (p))
156 #define ISEND(p) (!*(p) || (pathname && *(p) == '/'))
157 #define RETURN(val) return *pcur = p, *scur = s, (val);
159 static int
160 fnmatch_helper(
161 const char **pcur, /* pattern */
162 const char **scur, /* string */
163 int flags,
164 rb_encoding *enc)
166 const int period = !(flags & FNM_DOTMATCH);
167 const int pathname = flags & FNM_PATHNAME;
168 const int escape = !(flags & FNM_NOESCAPE);
169 const int nocase = flags & FNM_CASEFOLD;
171 const char *ptmp = 0;
172 const char *stmp = 0;
174 const char *p = *pcur;
175 const char *pend = p + strlen(p);
176 const char *s = *scur;
177 const char *send = s + strlen(s);
179 if (period && *s == '.' && *UNESCAPE(p) != '.') /* leading period */
180 RETURN(FNM_NOMATCH);
182 while (1) {
183 switch (*p) {
184 case '*':
185 do { p++; } while (*p == '*');
186 if (ISEND(UNESCAPE(p))) {
187 p = UNESCAPE(p);
188 RETURN(0);
190 if (ISEND(s))
191 RETURN(FNM_NOMATCH);
192 ptmp = p;
193 stmp = s;
194 continue;
196 case '?':
197 if (ISEND(s))
198 RETURN(FNM_NOMATCH);
199 p++;
200 Inc(s, send, enc);
201 continue;
203 case '[': {
204 const char *t;
205 if (ISEND(s))
206 RETURN(FNM_NOMATCH);
207 if ((t = bracket(p + 1, s, flags, enc)) != 0) {
208 p = t;
209 Inc(s, send, enc);
210 continue;
212 goto failed;
216 /* ordinary */
217 p = UNESCAPE(p);
218 if (ISEND(s))
219 RETURN(ISEND(p) ? 0 : FNM_NOMATCH);
220 if (ISEND(p))
221 goto failed;
222 if (char_casecmp(p, s, enc, nocase) != 0)
223 goto failed;
224 Inc(p, pend, enc);
225 Inc(s, send, enc);
226 continue;
228 failed: /* try next '*' position */
229 if (ptmp && stmp) {
230 p = ptmp;
231 Inc(stmp, send, enc); /* !ISEND(*stmp) */
232 s = stmp;
233 continue;
235 RETURN(FNM_NOMATCH);
239 static int
240 fnmatch(
241 const char *pattern,
242 rb_encoding *enc,
243 const char *string,
244 int flags)
246 const char *p = pattern;
247 const char *s = string;
248 const char *send = s + strlen(string);
249 const int period = !(flags & FNM_DOTMATCH);
250 const int pathname = flags & FNM_PATHNAME;
252 const char *ptmp = 0;
253 const char *stmp = 0;
255 if (pathname) {
256 while (1) {
257 if (p[0] == '*' && p[1] == '*' && p[2] == '/') {
258 do { p += 3; } while (p[0] == '*' && p[1] == '*' && p[2] == '/');
259 ptmp = p;
260 stmp = s;
262 if (fnmatch_helper(&p, &s, flags, enc) == 0) {
263 while (*s && *s != '/') Inc(s, send, enc);
264 if (*p && *s) {
265 p++;
266 s++;
267 continue;
269 if (!*p && !*s)
270 return 0;
272 /* failed : try next recursion */
273 if (ptmp && stmp && !(period && *stmp == '.')) {
274 while (*stmp && *stmp != '/') Inc(stmp, send, enc);
275 if (*stmp) {
276 p = ptmp;
277 stmp++;
278 s = stmp;
279 continue;
282 return FNM_NOMATCH;
285 else
286 return fnmatch_helper(&p, &s, flags, enc);
289 VALUE rb_cDir;
291 struct dir_data {
292 DIR *dir;
293 char *path;
294 rb_encoding *intenc;
295 rb_encoding *extenc;
298 static void
299 free_dir(struct dir_data *dir)
301 if (dir) {
302 if (dir->dir) closedir(dir->dir);
303 if (dir->path) xfree(dir->path);
305 xfree(dir);
308 static VALUE dir_close(VALUE);
310 static VALUE
311 dir_s_alloc(VALUE klass)
313 struct dir_data *dirp;
314 VALUE obj = Data_Make_Struct(klass, struct dir_data, 0, free_dir, dirp);
316 dirp->dir = NULL;
317 dirp->path = NULL;
318 dirp->intenc = NULL;
319 dirp->extenc = NULL;
321 return obj;
325 * call-seq:
326 * Dir.new( string ) -> aDir
328 * Returns a new directory object for the named directory.
330 static VALUE
331 dir_initialize(int argc, VALUE *argv, VALUE dir)
333 struct dir_data *dp;
334 static rb_encoding *fs_encoding;
335 rb_encoding *intencoding, *extencoding;
336 VALUE dirname, opt;
337 static VALUE sym_intenc, sym_extenc;
339 if (!sym_intenc) {
340 sym_intenc = ID2SYM(rb_intern("internal_encoding"));
341 sym_extenc = ID2SYM(rb_intern("external_encoding"));
342 fs_encoding = rb_filesystem_encoding();
345 intencoding = NULL;
346 extencoding = fs_encoding;
347 rb_scan_args(argc, argv, "11", &dirname, &opt);
349 if (!NIL_P(opt)) {
350 VALUE v, extenc=Qnil, intenc=Qnil;
351 opt = rb_check_convert_type(opt, T_HASH, "Hash", "to_hash");
353 v = rb_hash_aref(opt, sym_intenc);
354 if (!NIL_P(v)) intenc = v;
355 v = rb_hash_aref(opt, sym_extenc);
356 if (!NIL_P(v)) extenc = v;
358 if (!NIL_P(extenc)) {
359 extencoding = rb_to_encoding(extenc);
360 if (!NIL_P(intenc)) {
361 intencoding = rb_to_encoding(intenc);
362 if (extencoding == intencoding) {
363 rb_warn("Ignoring internal encoding '%s': it is identical to external encoding '%s'",
364 RSTRING_PTR(rb_inspect(intenc)),
365 RSTRING_PTR(rb_inspect(extenc)));
366 intencoding = NULL;
370 else if (!NIL_P(intenc)) {
371 rb_raise(rb_eArgError, "External encoding must be specified when internal encoding is given");
376 rb_encoding *dirname_encoding = rb_enc_get(dirname);
377 if (rb_usascii_encoding() != dirname_encoding
378 && rb_ascii8bit_encoding() != dirname_encoding
379 #if defined __APPLE__
380 && rb_utf8_encoding() != dirname_encoding
381 #endif
382 && extencoding != dirname_encoding) {
383 if (!intencoding) intencoding = dirname_encoding;
384 dirname = rb_str_transcode(dirname, rb_enc_from_encoding(extencoding));
387 FilePathValue(dirname);
389 Data_Get_Struct(dir, struct dir_data, dp);
390 if (dp->dir) closedir(dp->dir);
391 if (dp->path) xfree(dp->path);
392 dp->dir = NULL;
393 dp->path = NULL;
394 dp->intenc = intencoding;
395 dp->extenc = extencoding;
396 dp->dir = opendir(RSTRING_PTR(dirname));
397 if (dp->dir == NULL) {
398 if (errno == EMFILE || errno == ENFILE) {
399 rb_gc();
400 dp->dir = opendir(RSTRING_PTR(dirname));
402 if (dp->dir == NULL) {
403 rb_sys_fail(RSTRING_PTR(dirname));
406 dp->path = strdup(RSTRING_PTR(dirname));
408 return dir;
412 * call-seq:
413 * Dir.open( string ) => aDir
414 * Dir.open( string ) {| aDir | block } => anObject
416 * With no block, <code>open</code> is a synonym for
417 * <code>Dir::new</code>. If a block is present, it is passed
418 * <i>aDir</i> as a parameter. The directory is closed at the end of
419 * the block, and <code>Dir::open</code> returns the value of the
420 * block.
422 static VALUE
423 dir_s_open(int argc, VALUE *argv, VALUE klass)
425 struct dir_data *dp;
426 VALUE dir = Data_Make_Struct(klass, struct dir_data, 0, free_dir, dp);
428 dir_initialize(argc, argv, dir);
429 if (rb_block_given_p()) {
430 return rb_ensure(rb_yield, dir, dir_close, dir);
433 return dir;
436 static void
437 dir_closed(void)
439 rb_raise(rb_eIOError, "closed directory");
442 static void
443 dir_check(VALUE dir)
445 if (!OBJ_TAINTED(dir) && rb_safe_level() >= 4)
446 rb_raise(rb_eSecurityError, "Insecure: operation on untainted Dir");
447 rb_check_frozen(dir);
450 #define GetDIR(obj, dirp) do {\
451 dir_check(dir);\
452 Data_Get_Struct(obj, struct dir_data, dirp);\
453 if (dirp->dir == NULL) dir_closed();\
454 } while (0)
456 static VALUE
457 dir_enc_str(VALUE str, struct dir_data *dirp)
459 rb_enc_associate(str, dirp->extenc);
460 if (dirp->intenc) {
461 str = rb_str_transcode(str, rb_enc_from_encoding(dirp->intenc));
463 return str;
467 * call-seq:
468 * dir.inspect => string
470 * Return a string describing this Dir object.
472 static VALUE
473 dir_inspect(VALUE dir)
475 struct dir_data *dirp;
477 Data_Get_Struct(dir, struct dir_data, dirp);
478 if (dirp->path) {
479 const char *c = rb_obj_classname(dir);
480 int len = strlen(c) + strlen(dirp->path) + 4;
481 VALUE s = rb_str_new(0, len);
482 snprintf(RSTRING_PTR(s), len+1, "#<%s:%s>", c, dirp->path);
483 return s;
485 return rb_funcall(dir, rb_intern("to_s"), 0, 0);
489 * call-seq:
490 * dir.path => string or nil
492 * Returns the path parameter passed to <em>dir</em>'s constructor.
494 * d = Dir.new("..")
495 * d.path #=> ".."
497 static VALUE
498 dir_path(VALUE dir)
500 struct dir_data *dirp;
502 Data_Get_Struct(dir, struct dir_data, dirp);
503 if (!dirp->path) return Qnil;
504 return dir_enc_str(rb_str_new2(dirp->path), dirp);
508 * call-seq:
509 * dir.read => string or nil
511 * Reads the next entry from <em>dir</em> and returns it as a string.
512 * Returns <code>nil</code> at the end of the stream.
514 * d = Dir.new("testdir")
515 * d.read #=> "."
516 * d.read #=> ".."
517 * d.read #=> "config.h"
519 static VALUE
520 dir_read(VALUE dir)
522 struct dir_data *dirp;
523 struct dirent *dp;
525 GetDIR(dir, dirp);
526 errno = 0;
527 dp = readdir(dirp->dir);
528 if (dp) {
529 return dir_enc_str(rb_tainted_str_new(dp->d_name, NAMLEN(dp)), dirp);
531 else if (errno == 0) { /* end of stream */
532 return Qnil;
534 else {
535 rb_sys_fail(0);
537 return Qnil; /* not reached */
541 * call-seq:
542 * dir.each { |filename| block } => dir
544 * Calls the block once for each entry in this directory, passing the
545 * filename of each entry as a parameter to the block.
547 * d = Dir.new("testdir")
548 * d.each {|x| puts "Got #{x}" }
550 * <em>produces:</em>
552 * Got .
553 * Got ..
554 * Got config.h
555 * Got main.rb
557 static VALUE
558 dir_each(VALUE dir)
560 struct dir_data *dirp;
561 struct dirent *dp;
563 RETURN_ENUMERATOR(dir, 0, 0);
564 GetDIR(dir, dirp);
565 rewinddir(dirp->dir);
566 for (dp = readdir(dirp->dir); dp != NULL; dp = readdir(dirp->dir)) {
567 rb_yield(dir_enc_str(rb_tainted_str_new(dp->d_name, NAMLEN(dp)), dirp));
568 if (dirp->dir == NULL) dir_closed();
570 return dir;
574 * call-seq:
575 * dir.pos => integer
576 * dir.tell => integer
578 * Returns the current position in <em>dir</em>. See also
579 * <code>Dir#seek</code>.
581 * d = Dir.new("testdir")
582 * d.tell #=> 0
583 * d.read #=> "."
584 * d.tell #=> 12
586 static VALUE
587 dir_tell(VALUE dir)
589 #ifdef HAVE_TELLDIR
590 struct dir_data *dirp;
591 long pos;
593 GetDIR(dir, dirp);
594 pos = telldir(dirp->dir);
595 return rb_int2inum(pos);
596 #else
597 rb_notimplement();
598 #endif
602 * call-seq:
603 * dir.seek( integer ) => dir
605 * Seeks to a particular location in <em>dir</em>. <i>integer</i>
606 * must be a value returned by <code>Dir#tell</code>.
608 * d = Dir.new("testdir") #=> #<Dir:0x401b3c40>
609 * d.read #=> "."
610 * i = d.tell #=> 12
611 * d.read #=> ".."
612 * d.seek(i) #=> #<Dir:0x401b3c40>
613 * d.read #=> ".."
615 static VALUE
616 dir_seek(VALUE dir, VALUE pos)
618 struct dir_data *dirp;
619 off_t p = NUM2OFFT(pos);
621 GetDIR(dir, dirp);
622 #ifdef HAVE_SEEKDIR
623 seekdir(dirp->dir, p);
624 return dir;
625 #else
626 rb_notimplement();
627 #endif
631 * call-seq:
632 * dir.pos( integer ) => integer
634 * Synonym for <code>Dir#seek</code>, but returns the position
635 * parameter.
637 * d = Dir.new("testdir") #=> #<Dir:0x401b3c40>
638 * d.read #=> "."
639 * i = d.pos #=> 12
640 * d.read #=> ".."
641 * d.pos = i #=> 12
642 * d.read #=> ".."
644 static VALUE
645 dir_set_pos(VALUE dir, VALUE pos)
647 dir_seek(dir, pos);
648 return pos;
652 * call-seq:
653 * dir.rewind => dir
655 * Repositions <em>dir</em> to the first entry.
657 * d = Dir.new("testdir")
658 * d.read #=> "."
659 * d.rewind #=> #<Dir:0x401b3fb0>
660 * d.read #=> "."
662 static VALUE
663 dir_rewind(VALUE dir)
665 struct dir_data *dirp;
667 if (rb_safe_level() >= 4 && !OBJ_TAINTED(dir)) {
668 rb_raise(rb_eSecurityError, "Insecure: can't close");
670 GetDIR(dir, dirp);
671 rewinddir(dirp->dir);
672 return dir;
676 * call-seq:
677 * dir.close => nil
679 * Closes the directory stream. Any further attempts to access
680 * <em>dir</em> will raise an <code>IOError</code>.
682 * d = Dir.new("testdir")
683 * d.close #=> nil
685 static VALUE
686 dir_close(VALUE dir)
688 struct dir_data *dirp;
690 GetDIR(dir, dirp);
691 closedir(dirp->dir);
692 dirp->dir = NULL;
694 return Qnil;
697 static void
698 dir_chdir(VALUE path)
700 if (chdir(RSTRING_PTR(path)) < 0)
701 rb_sys_fail(RSTRING_PTR(path));
704 static int chdir_blocking = 0;
705 static VALUE chdir_thread = Qnil;
707 struct chdir_data {
708 VALUE old_path, new_path;
709 int done;
712 static VALUE
713 chdir_yield(struct chdir_data *args)
715 dir_chdir(args->new_path);
716 args->done = Qtrue;
717 chdir_blocking++;
718 if (chdir_thread == Qnil)
719 chdir_thread = rb_thread_current();
720 return rb_yield(args->new_path);
723 static VALUE
724 chdir_restore(struct chdir_data *args)
726 if (args->done) {
727 chdir_blocking--;
728 if (chdir_blocking == 0)
729 chdir_thread = Qnil;
730 dir_chdir(args->old_path);
732 return Qnil;
736 * call-seq:
737 * Dir.chdir( [ string] ) => 0
738 * Dir.chdir( [ string] ) {| path | block } => anObject
740 * Changes the current working directory of the process to the given
741 * string. When called without an argument, changes the directory to
742 * the value of the environment variable <code>HOME</code>, or
743 * <code>LOGDIR</code>. <code>SystemCallError</code> (probably
744 * <code>Errno::ENOENT</code>) if the target directory does not exist.
746 * If a block is given, it is passed the name of the new current
747 * directory, and the block is executed with that as the current
748 * directory. The original working directory is restored when the block
749 * exits. The return value of <code>chdir</code> is the value of the
750 * block. <code>chdir</code> blocks can be nested, but in a
751 * multi-threaded program an error will be raised if a thread attempts
752 * to open a <code>chdir</code> block while another thread has one
753 * open.
755 * Dir.chdir("/var/spool/mail")
756 * puts Dir.pwd
757 * Dir.chdir("/tmp") do
758 * puts Dir.pwd
759 * Dir.chdir("/usr") do
760 * puts Dir.pwd
761 * end
762 * puts Dir.pwd
763 * end
764 * puts Dir.pwd
766 * <em>produces:</em>
768 * /var/spool/mail
769 * /tmp
770 * /usr
771 * /tmp
772 * /var/spool/mail
774 static VALUE
775 dir_s_chdir(int argc, VALUE *argv, VALUE obj)
777 VALUE path = Qnil;
779 rb_secure(2);
780 if (rb_scan_args(argc, argv, "01", &path) == 1) {
781 FilePathValue(path);
783 else {
784 const char *dist = getenv("HOME");
785 if (!dist) {
786 dist = getenv("LOGDIR");
787 if (!dist) rb_raise(rb_eArgError, "HOME/LOGDIR not set");
789 path = rb_str_new2(dist);
792 if (chdir_blocking > 0) {
793 if (!rb_block_given_p() || rb_thread_current() != chdir_thread)
794 rb_warn("conflicting chdir during another chdir block");
797 if (rb_block_given_p()) {
798 struct chdir_data args;
799 char *cwd = my_getcwd();
801 args.old_path = rb_tainted_str_new2(cwd); xfree(cwd);
802 args.new_path = path;
803 args.done = Qfalse;
804 return rb_ensure(chdir_yield, (VALUE)&args, chdir_restore, (VALUE)&args);
806 dir_chdir(path);
808 return INT2FIX(0);
812 * call-seq:
813 * Dir.getwd => string
814 * Dir.pwd => string
816 * Returns the path to the current working directory of this process as
817 * a string.
819 * Dir.chdir("/tmp") #=> 0
820 * Dir.getwd #=> "/tmp"
822 static VALUE
823 dir_s_getwd(VALUE dir)
825 char *path;
826 VALUE cwd;
828 rb_secure(4);
829 path = my_getcwd();
830 cwd = rb_tainted_str_new2(path);
832 xfree(path);
833 return cwd;
836 static void
837 check_dirname(volatile VALUE *dir)
839 char *path, *pend;
841 rb_secure(2);
842 FilePathValue(*dir);
843 path = RSTRING_PTR(*dir);
844 if (path && *(pend = rb_path_end(rb_path_skip_prefix(path)))) {
845 *dir = rb_str_new(path, pend - path);
850 * call-seq:
851 * Dir.chroot( string ) => 0
853 * Changes this process's idea of the file system root. Only a
854 * privileged process may make this call. Not available on all
855 * platforms. On Unix systems, see <code>chroot(2)</code> for more
856 * information.
858 static VALUE
859 dir_s_chroot(VALUE dir, VALUE path)
861 #if defined(HAVE_CHROOT) && !defined(__CHECKER__)
862 check_dirname(&path);
864 if (chroot(RSTRING_PTR(path)) == -1)
865 rb_sys_fail(RSTRING_PTR(path));
867 return INT2FIX(0);
868 #else
869 rb_notimplement();
870 return Qnil; /* not reached */
871 #endif
875 * call-seq:
876 * Dir.mkdir( string [, integer] ) => 0
878 * Makes a new directory named by <i>string</i>, with permissions
879 * specified by the optional parameter <i>anInteger</i>. The
880 * permissions may be modified by the value of
881 * <code>File::umask</code>, and are ignored on NT. Raises a
882 * <code>SystemCallError</code> if the directory cannot be created. See
883 * also the discussion of permissions in the class documentation for
884 * <code>File</code>.
887 static VALUE
888 dir_s_mkdir(int argc, VALUE *argv, VALUE obj)
890 VALUE path, vmode;
891 int mode;
893 if (rb_scan_args(argc, argv, "11", &path, &vmode) == 2) {
894 mode = NUM2INT(vmode);
896 else {
897 mode = 0777;
900 check_dirname(&path);
901 if (mkdir(RSTRING_PTR(path), mode) == -1)
902 rb_sys_fail(RSTRING_PTR(path));
904 return INT2FIX(0);
908 * call-seq:
909 * Dir.delete( string ) => 0
910 * Dir.rmdir( string ) => 0
911 * Dir.unlink( string ) => 0
913 * Deletes the named directory. Raises a subclass of
914 * <code>SystemCallError</code> if the directory isn't empty.
916 static VALUE
917 dir_s_rmdir(VALUE obj, VALUE dir)
919 check_dirname(&dir);
920 if (rmdir(RSTRING_PTR(dir)) < 0)
921 rb_sys_fail(RSTRING_PTR(dir));
923 return INT2FIX(0);
926 static void
927 sys_warning_1(const char* mesg)
929 rb_sys_warning("%s", mesg);
932 #define GLOB_VERBOSE (1UL << (sizeof(int) * CHAR_BIT - 1))
933 #define sys_warning(val) \
934 (void)((flags & GLOB_VERBOSE) && rb_protect((VALUE (*)(VALUE))sys_warning_1, (VALUE)(val), 0))
936 #define GLOB_ALLOC(type) (type *)malloc(sizeof(type))
937 #define GLOB_ALLOC_N(type, n) (type *)malloc(sizeof(type) * (n))
938 #define GLOB_FREE(ptr) free(ptr)
939 #define GLOB_JUMP_TAG(status) ((status == -1) ? rb_memerror() : rb_jump_tag(status))
942 * ENOTDIR can be returned by stat(2) if a non-leaf element of the path
943 * is not a directory.
945 #define to_be_ignored(e) ((e) == ENOENT || (e) == ENOTDIR)
947 /* System call with warning */
948 static int
949 do_stat(const char *path, struct stat *pst, int flags)
952 int ret = stat(path, pst);
953 if (ret < 0 && !to_be_ignored(errno))
954 sys_warning(path);
956 return ret;
959 static int
960 do_lstat(const char *path, struct stat *pst, int flags)
962 int ret = lstat(path, pst);
963 if (ret < 0 && !to_be_ignored(errno))
964 sys_warning(path);
966 return ret;
969 static DIR *
970 do_opendir(const char *path, int flags)
972 DIR *dirp = opendir(path);
973 if (dirp == NULL && !to_be_ignored(errno))
974 sys_warning(path);
976 return dirp;
979 /* Return nonzero if S has any special globbing chars in it. */
980 static int
981 has_magic(const char *s, int flags, rb_encoding *enc)
983 const int escape = !(flags & FNM_NOESCAPE);
984 const int nocase = flags & FNM_CASEFOLD;
986 register const char *p = s;
987 register const char *pend = p + strlen(p);
988 register char c;
990 while ((c = *p++) != 0) {
991 switch (c) {
992 case '*':
993 case '?':
994 case '[':
995 return 1;
997 case '\\':
998 if (escape && !(c = *p++))
999 return 0;
1000 continue;
1002 default:
1003 if (!FNM_SYSCASE && ISALPHA(c) && nocase)
1004 return 1;
1007 p = Next(p-1, pend, enc);
1010 return 0;
1013 /* Find separator in globbing pattern. */
1014 static char *
1015 find_dirsep(const char *s, int flags, rb_encoding *enc)
1017 const int escape = !(flags & FNM_NOESCAPE);
1019 register const char *p = s;
1020 register const char *pend = p + strlen(p);
1021 register char c;
1022 int open = 0;
1024 while ((c = *p++) != 0) {
1025 switch (c) {
1026 case '[':
1027 open = 1;
1028 continue;
1029 case ']':
1030 open = 0;
1031 continue;
1033 case '/':
1034 if (!open)
1035 return (char *)p-1;
1036 continue;
1038 case '\\':
1039 if (escape && !(c = *p++))
1040 return (char *)p-1;
1041 continue;
1044 p = Next(p-1, pend, enc);
1047 return (char *)p-1;
1050 /* Remove escaping backslashes */
1051 static void
1052 remove_backslashes(char *p, rb_encoding *enc)
1054 register const char *pend = p + strlen(p);
1055 char *t = p;
1056 char *s = p;
1058 while (*p) {
1059 if (*p == '\\') {
1060 if (t != s)
1061 memmove(t, s, p - s);
1062 t += p - s;
1063 s = ++p;
1064 if (!*p) break;
1066 Inc(p, pend, enc);
1069 while (*p++);
1071 if (t != s)
1072 memmove(t, s, p - s); /* move '\0' too */
1075 /* Globing pattern */
1076 enum glob_pattern_type { PLAIN, MAGICAL, RECURSIVE, MATCH_ALL, MATCH_DIR };
1078 struct glob_pattern {
1079 char *str;
1080 enum glob_pattern_type type;
1081 struct glob_pattern *next;
1084 static void glob_free_pattern(struct glob_pattern *list);
1086 static struct glob_pattern *
1087 glob_make_pattern(const char *p, int flags, rb_encoding *enc)
1089 struct glob_pattern *list, *tmp, **tail = &list;
1090 int dirsep = 0; /* pattern is terminated with '/' */
1092 while (*p) {
1093 tmp = GLOB_ALLOC(struct glob_pattern);
1094 if (!tmp) goto error;
1095 if (p[0] == '*' && p[1] == '*' && p[2] == '/') {
1096 /* fold continuous RECURSIVEs (needed in glob_helper) */
1097 do { p += 3; } while (p[0] == '*' && p[1] == '*' && p[2] == '/');
1098 tmp->type = RECURSIVE;
1099 tmp->str = 0;
1100 dirsep = 1;
1102 else {
1103 const char *m = find_dirsep(p, flags, enc);
1104 char *buf = GLOB_ALLOC_N(char, m-p+1);
1105 if (!buf) {
1106 GLOB_FREE(tmp);
1107 goto error;
1109 memcpy(buf, p, m-p);
1110 buf[m-p] = '\0';
1111 tmp->type = has_magic(buf, flags, enc) ? MAGICAL : PLAIN;
1112 tmp->str = buf;
1113 if (*m) {
1114 dirsep = 1;
1115 p = m + 1;
1117 else {
1118 dirsep = 0;
1119 p = m;
1122 *tail = tmp;
1123 tail = &tmp->next;
1126 tmp = GLOB_ALLOC(struct glob_pattern);
1127 if (!tmp) {
1128 error:
1129 *tail = 0;
1130 glob_free_pattern(list);
1131 return 0;
1133 tmp->type = dirsep ? MATCH_DIR : MATCH_ALL;
1134 tmp->str = 0;
1135 *tail = tmp;
1136 tmp->next = 0;
1138 return list;
1141 static void
1142 glob_free_pattern(struct glob_pattern *list)
1144 while (list) {
1145 struct glob_pattern *tmp = list;
1146 list = list->next;
1147 if (tmp->str)
1148 GLOB_FREE(tmp->str);
1149 GLOB_FREE(tmp);
1153 static char *
1154 join_path(const char *path, int dirsep, const char *name)
1156 long len = strlen(path);
1157 char *buf = GLOB_ALLOC_N(char, len+strlen(name)+(dirsep?1:0)+1);
1159 if (!buf) return 0;
1160 memcpy(buf, path, len);
1161 if (dirsep) {
1162 strcpy(buf+len, "/");
1163 len++;
1165 strcpy(buf+len, name);
1166 return buf;
1169 enum answer { YES, NO, UNKNOWN };
1171 #ifndef S_ISDIR
1172 # define S_ISDIR(m) ((m & S_IFMT) == S_IFDIR)
1173 #endif
1175 #ifndef S_ISLNK
1176 # ifndef S_IFLNK
1177 # define S_ISLNK(m) (0)
1178 # else
1179 # define S_ISLNK(m) ((m & S_IFMT) == S_IFLNK)
1180 # endif
1181 #endif
1183 struct glob_args {
1184 void (*func)(const char *, VALUE, void *);
1185 const char *path;
1186 VALUE value;
1187 rb_encoding *enc;
1190 static VALUE
1191 glob_func_caller(VALUE val)
1193 struct glob_args *args = (struct glob_args *)val;
1195 (*args->func)(args->path, args->value, args->enc);
1196 return Qnil;
1199 #define glob_call_func(func, path, arg, enc) (*func)(path, arg, enc)
1201 static int
1202 glob_helper(
1203 const char *path,
1204 int dirsep, /* '/' should be placed before appending child entry's name to 'path'. */
1205 enum answer exist, /* Does 'path' indicate an existing entry? */
1206 enum answer isdir, /* Does 'path' indicate a directory or a symlink to a directory? */
1207 struct glob_pattern **beg,
1208 struct glob_pattern **end,
1209 int flags,
1210 ruby_glob_func *func,
1211 VALUE arg,
1212 rb_encoding *enc)
1214 struct stat st;
1215 int status = 0;
1216 struct glob_pattern **cur, **new_beg, **new_end;
1217 int plain = 0, magical = 0, recursive = 0, match_all = 0, match_dir = 0;
1218 int escape = !(flags & FNM_NOESCAPE);
1220 for (cur = beg; cur < end; ++cur) {
1221 struct glob_pattern *p = *cur;
1222 if (p->type == RECURSIVE) {
1223 recursive = 1;
1224 p = p->next;
1226 switch (p->type) {
1227 case PLAIN:
1228 plain = 1;
1229 break;
1230 case MAGICAL:
1231 magical = 1;
1232 break;
1233 case MATCH_ALL:
1234 match_all = 1;
1235 break;
1236 case MATCH_DIR:
1237 match_dir = 1;
1238 break;
1239 case RECURSIVE:
1240 rb_bug("continuous RECURSIVEs");
1244 if (*path) {
1245 if (match_all && exist == UNKNOWN) {
1246 if (do_lstat(path, &st, flags) == 0) {
1247 exist = YES;
1248 isdir = S_ISDIR(st.st_mode) ? YES : S_ISLNK(st.st_mode) ? UNKNOWN : NO;
1250 else {
1251 exist = NO;
1252 isdir = NO;
1255 if (match_dir && isdir == UNKNOWN) {
1256 if (do_stat(path, &st, flags) == 0) {
1257 exist = YES;
1258 isdir = S_ISDIR(st.st_mode) ? YES : NO;
1260 else {
1261 exist = NO;
1262 isdir = NO;
1265 if (match_all && exist == YES) {
1266 status = glob_call_func(func, path, arg, enc);
1267 if (status) return status;
1269 if (match_dir && isdir == YES) {
1270 char *tmp = join_path(path, dirsep, "");
1271 if (!tmp) return -1;
1272 status = glob_call_func(func, tmp, arg, enc);
1273 GLOB_FREE(tmp);
1274 if (status) return status;
1278 if (exist == NO || isdir == NO) return 0;
1280 if (magical || recursive) {
1281 struct dirent *dp;
1282 DIR *dirp = do_opendir(*path ? path : ".", flags);
1283 if (dirp == NULL) return 0;
1285 for (dp = readdir(dirp); dp != NULL; dp = readdir(dirp)) {
1286 char *buf = join_path(path, dirsep, dp->d_name);
1287 enum answer new_isdir = UNKNOWN;
1289 if (!buf) {
1290 status = -1;
1291 break;
1293 if (recursive && strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0
1294 && fnmatch("*", rb_usascii_encoding(), dp->d_name, flags) == 0) {
1295 #ifndef _WIN32
1296 if (do_lstat(buf, &st, flags) == 0)
1297 new_isdir = S_ISDIR(st.st_mode) ? YES : S_ISLNK(st.st_mode) ? UNKNOWN : NO;
1298 else
1299 new_isdir = NO;
1300 #else
1301 new_isdir = dp->d_isdir ? (!dp->d_isrep ? YES : UNKNOWN) : NO;
1302 #endif
1305 new_beg = new_end = GLOB_ALLOC_N(struct glob_pattern *, (end - beg) * 2);
1306 if (!new_beg) {
1307 GLOB_FREE(buf);
1308 status = -1;
1309 break;
1312 for (cur = beg; cur < end; ++cur) {
1313 struct glob_pattern *p = *cur;
1314 if (p->type == RECURSIVE) {
1315 if (new_isdir == YES) /* not symlink but real directory */
1316 *new_end++ = p; /* append recursive pattern */
1317 p = p->next; /* 0 times recursion */
1319 if (p->type == PLAIN || p->type == MAGICAL) {
1320 if (fnmatch(p->str, enc, dp->d_name, flags) == 0)
1321 *new_end++ = p->next;
1325 status = glob_helper(buf, 1, YES, new_isdir, new_beg, new_end,
1326 flags, func, arg, enc);
1327 GLOB_FREE(buf);
1328 GLOB_FREE(new_beg);
1329 if (status) break;
1332 closedir(dirp);
1334 else if (plain) {
1335 struct glob_pattern **copy_beg, **copy_end, **cur2;
1337 copy_beg = copy_end = GLOB_ALLOC_N(struct glob_pattern *, end - beg);
1338 if (!copy_beg) return -1;
1339 for (cur = beg; cur < end; ++cur)
1340 *copy_end++ = (*cur)->type == PLAIN ? *cur : 0;
1342 for (cur = copy_beg; cur < copy_end; ++cur) {
1343 if (*cur) {
1344 char *buf;
1345 char *name;
1346 name = GLOB_ALLOC_N(char, strlen((*cur)->str) + 1);
1347 if (!name) {
1348 status = -1;
1349 break;
1351 strcpy(name, (*cur)->str);
1352 if (escape) remove_backslashes(name, enc);
1354 new_beg = new_end = GLOB_ALLOC_N(struct glob_pattern *, end - beg);
1355 if (!new_beg) {
1356 GLOB_FREE(name);
1357 status = -1;
1358 break;
1360 *new_end++ = (*cur)->next;
1361 for (cur2 = cur + 1; cur2 < copy_end; ++cur2) {
1362 if (*cur2 && fnmatch((*cur2)->str, enc, name, flags) == 0) {
1363 *new_end++ = (*cur2)->next;
1364 *cur2 = 0;
1368 buf = join_path(path, dirsep, name);
1369 GLOB_FREE(name);
1370 if (!buf) {
1371 GLOB_FREE(new_beg);
1372 status = -1;
1373 break;
1375 status = glob_helper(buf, 1, UNKNOWN, UNKNOWN, new_beg,
1376 new_end, flags, func, arg, enc);
1377 GLOB_FREE(buf);
1378 GLOB_FREE(new_beg);
1379 if (status) break;
1383 GLOB_FREE(copy_beg);
1386 return status;
1389 static int
1390 ruby_glob0(const char *path, int flags, ruby_glob_func *func, VALUE arg, rb_encoding *enc)
1392 struct glob_pattern *list;
1393 const char *root, *start;
1394 char *buf;
1395 int n;
1396 int status;
1398 start = root = path;
1399 flags |= FNM_SYSCASE;
1400 #if defined DOSISH
1401 root = rb_path_skip_prefix(root);
1402 #endif
1404 if (root && *root == '/') root++;
1406 n = root - start;
1407 buf = GLOB_ALLOC_N(char, n + 1);
1408 if (!buf) return -1;
1409 MEMCPY(buf, start, char, n);
1410 buf[n] = '\0';
1412 list = glob_make_pattern(root, flags, enc);
1413 if (!list) {
1414 GLOB_FREE(buf);
1415 return -1;
1417 status = glob_helper(buf, 0, UNKNOWN, UNKNOWN, &list, &list + 1, flags, func, arg, enc);
1418 glob_free_pattern(list);
1419 GLOB_FREE(buf);
1421 return status;
1425 ruby_glob(const char *path, int flags, ruby_glob_func *func, VALUE arg)
1427 return ruby_glob0(path, flags & ~GLOB_VERBOSE, func, arg,
1428 rb_ascii8bit_encoding());
1431 static int
1432 rb_glob_caller(const char *path, VALUE a, void *enc)
1434 int status;
1435 struct glob_args *args = (struct glob_args *)a;
1437 args->path = path;
1438 rb_protect(glob_func_caller, a, &status);
1439 return status;
1442 static int
1443 rb_glob2(const char *path, int flags,
1444 void (*func)(const char *, VALUE, void *), VALUE arg,
1445 rb_encoding* enc)
1447 struct glob_args args;
1449 args.func = func;
1450 args.value = arg;
1451 args.enc = enc;
1453 if (flags & FNM_SYSCASE) {
1454 rb_warning("Dir.glob() ignores File::FNM_CASEFOLD");
1457 return ruby_glob0(path, flags | GLOB_VERBOSE, rb_glob_caller, (VALUE)&args,
1458 enc);
1461 void
1462 rb_glob(const char *path, void (*func)(const char *, VALUE, void *), VALUE arg)
1464 int status = rb_glob2(path, 0, func, arg, rb_ascii8bit_encoding());
1465 if (status) GLOB_JUMP_TAG(status);
1468 static void
1469 push_pattern(const char *path, VALUE ary, void *enc)
1471 VALUE vpath = rb_tainted_str_new2(path);
1472 rb_enc_associate(vpath, enc);
1473 rb_ary_push(ary, vpath);
1476 static int
1477 ruby_brace_expand(const char *str, int flags, ruby_glob_func *func, VALUE arg,
1478 rb_encoding *enc)
1480 const int escape = !(flags & FNM_NOESCAPE);
1481 const char *p = str;
1482 const char *pend = p + strlen(p);
1483 const char *s = p;
1484 const char *lbrace = 0, *rbrace = 0;
1485 int nest = 0, status = 0;
1487 while (*p) {
1488 if (*p == '{' && nest++ == 0) {
1489 lbrace = p;
1491 if (*p == '}' && --nest <= 0) {
1492 rbrace = p;
1493 break;
1495 if (*p == '\\' && escape) {
1496 if (!*++p) break;
1498 Inc(p, pend, enc);
1501 if (lbrace && rbrace) {
1502 char *buf = GLOB_ALLOC_N(char, strlen(s) + 1);
1503 long shift;
1505 if (!buf) return -1;
1506 memcpy(buf, s, lbrace-s);
1507 shift = (lbrace-s);
1508 p = lbrace;
1509 while (p < rbrace) {
1510 const char *t = ++p;
1511 nest = 0;
1512 while (p < rbrace && !(*p == ',' && nest == 0)) {
1513 if (*p == '{') nest++;
1514 if (*p == '}') nest--;
1515 if (*p == '\\' && escape) {
1516 if (++p == rbrace) break;
1518 Inc(p, pend, enc);
1520 memcpy(buf+shift, t, p-t);
1521 strcpy(buf+shift+(p-t), rbrace+1);
1522 status = ruby_brace_expand(buf, flags, func, arg, enc);
1523 if (status) break;
1525 GLOB_FREE(buf);
1527 else if (!lbrace && !rbrace) {
1528 status = (*func)(s, arg, enc);
1531 return status;
1534 struct brace_args {
1535 ruby_glob_func *func;
1536 VALUE value;
1537 int flags;
1540 static int
1541 glob_brace(const char *path, VALUE val, void *enc)
1543 struct brace_args *arg = (struct brace_args *)val;
1545 return ruby_glob0(path, arg->flags, arg->func, arg->value, enc);
1548 static int
1549 ruby_brace_glob0(const char *str, int flags, ruby_glob_func *func, VALUE arg,
1550 rb_encoding* enc)
1552 struct brace_args args;
1554 args.func = func;
1555 args.value = arg;
1556 args.flags = flags;
1557 return ruby_brace_expand(str, flags, glob_brace, (VALUE)&args, enc);
1561 ruby_brace_glob(const char *str, int flags, ruby_glob_func *func, VALUE arg)
1563 return ruby_brace_glob0(str, flags & ~GLOB_VERBOSE, func, arg,
1564 rb_ascii8bit_encoding());
1567 static int
1568 push_glob(VALUE ary, VALUE str, int flags)
1570 struct glob_args args;
1571 rb_encoding *enc = rb_enc_get(str);
1573 args.func = push_pattern;
1574 args.value = ary;
1575 args.enc = enc;
1577 return ruby_brace_glob0(RSTRING_PTR(str), flags | GLOB_VERBOSE,
1578 rb_glob_caller, (VALUE)&args, enc);
1581 static VALUE
1582 rb_push_glob(VALUE str, int flags) /* '\0' is delimiter */
1584 long offset = 0;
1585 VALUE ary;
1587 StringValue(str);
1588 ary = rb_ary_new();
1590 while (offset < RSTRING_LEN(str)) {
1591 char *p, *pend;
1592 int status;
1593 p = RSTRING_PTR(str) + offset;
1594 status = push_glob(ary, rb_enc_str_new(p, strlen(p), rb_enc_get(str)),
1595 flags);
1596 if (status) GLOB_JUMP_TAG(status);
1597 if (offset >= RSTRING_LEN(str)) break;
1598 p += strlen(p) + 1;
1599 pend = RSTRING_PTR(str) + RSTRING_LEN(str);
1600 while (p < pend && !*p)
1601 p++;
1602 offset = p - RSTRING_PTR(str);
1605 return ary;
1608 static VALUE
1609 dir_globs(long argc, VALUE *argv, int flags)
1611 VALUE ary = rb_ary_new();
1612 long i;
1614 for (i = 0; i < argc; ++i) {
1615 int status;
1616 VALUE str = argv[i];
1617 StringValue(str);
1618 status = push_glob(ary, str, flags);
1619 if (status) GLOB_JUMP_TAG(status);
1622 return ary;
1626 * call-seq:
1627 * Dir[ array ] => array
1628 * Dir[ string [, string ...] ] => array
1630 * Equivalent to calling
1631 * <code>Dir.glob(</code><i>array,</i><code>0)</code> and
1632 * <code>Dir.glob([</code><i>string,...</i><code>],0)</code>.
1635 static VALUE
1636 dir_s_aref(int argc, VALUE *argv, VALUE obj)
1638 if (argc == 1) {
1639 return rb_push_glob(argv[0], 0);
1641 return dir_globs(argc, argv, 0);
1645 * call-seq:
1646 * Dir.glob( pattern, [flags] ) => array
1647 * Dir.glob( pattern, [flags] ) {| filename | block } => nil
1649 * Returns the filenames found by expanding <i>pattern</i> which is
1650 * an +Array+ of the patterns or the pattern +String+, either as an
1651 * <i>array</i> or as parameters to the block. Note that this pattern
1652 * is not a regexp (it's closer to a shell glob). See
1653 * <code>File::fnmatch</code> for the meaning of the <i>flags</i>
1654 * parameter. Note that case sensitivity depends on your system (so
1655 * <code>File::FNM_CASEFOLD</code> is ignored)
1657 * <code>*</code>:: Matches any file. Can be restricted by
1658 * other values in the glob. <code>*</code>
1659 * will match all files; <code>c*</code> will
1660 * match all files beginning with
1661 * <code>c</code>; <code>*c</code> will match
1662 * all files ending with <code>c</code>; and
1663 * <code>*c*</code> will match all files that
1664 * have <code>c</code> in them (including at
1665 * the beginning or end). Equivalent to
1666 * <code>/ .* /x</code> in regexp.
1667 * <code>**</code>:: Matches directories recursively.
1668 * <code>?</code>:: Matches any one character. Equivalent to
1669 * <code>/.{1}/</code> in regexp.
1670 * <code>[set]</code>:: Matches any one character in +set+.
1671 * Behaves exactly like character sets in
1672 * Regexp, including set negation
1673 * (<code>[^a-z]</code>).
1674 * <code>{p,q}</code>:: Matches either literal <code>p</code> or
1675 * literal <code>q</code>. Matching literals
1676 * may be more than one character in length.
1677 * More than two literals may be specified.
1678 * Equivalent to pattern alternation in
1679 * regexp.
1680 * <code>\</code>:: Escapes the next metacharacter.
1682 * Dir["config.?"] #=> ["config.h"]
1683 * Dir.glob("config.?") #=> ["config.h"]
1684 * Dir.glob("*.[a-z][a-z]") #=> ["main.rb"]
1685 * Dir.glob("*.[^r]*") #=> ["config.h"]
1686 * Dir.glob("*.{rb,h}") #=> ["main.rb", "config.h"]
1687 * Dir.glob("*") #=> ["config.h", "main.rb"]
1688 * Dir.glob("*", File::FNM_DOTMATCH) #=> [".", "..", "config.h", "main.rb"]
1690 * rbfiles = File.join("**", "*.rb")
1691 * Dir.glob(rbfiles) #=> ["main.rb",
1692 * # "lib/song.rb",
1693 * # "lib/song/karaoke.rb"]
1694 * libdirs = File.join("**", "lib")
1695 * Dir.glob(libdirs) #=> ["lib"]
1697 * librbfiles = File.join("**", "lib", "**", "*.rb")
1698 * Dir.glob(librbfiles) #=> ["lib/song.rb",
1699 * # "lib/song/karaoke.rb"]
1701 * librbfiles = File.join("**", "lib", "*.rb")
1702 * Dir.glob(librbfiles) #=> ["lib/song.rb"]
1704 static VALUE
1705 dir_s_glob(int argc, VALUE *argv, VALUE obj)
1707 VALUE str, rflags, ary;
1708 int flags;
1710 if (rb_scan_args(argc, argv, "11", &str, &rflags) == 2)
1711 flags = NUM2INT(rflags);
1712 else
1713 flags = 0;
1715 ary = rb_check_array_type(str);
1716 if (NIL_P(ary)) {
1717 ary = rb_push_glob(str, flags);
1719 else {
1720 volatile VALUE v = ary;
1721 ary = dir_globs(RARRAY_LEN(v), RARRAY_PTR(v), flags);
1724 if (rb_block_given_p()) {
1725 rb_ary_each(ary);
1726 return Qnil;
1728 return ary;
1731 static VALUE
1732 dir_open_dir(int argc, VALUE *argv)
1734 VALUE dir = rb_funcall2(rb_cDir, rb_intern("open"), argc, argv);
1736 if (TYPE(dir) != T_DATA ||
1737 RDATA(dir)->dfree != (RUBY_DATA_FUNC)free_dir) {
1738 rb_raise(rb_eTypeError, "wrong argument type %s (expected Dir)",
1739 rb_obj_classname(dir));
1741 return dir;
1746 * call-seq:
1747 * Dir.foreach( dirname ) {| filename | block } => nil
1749 * Calls the block once for each entry in the named directory, passing
1750 * the filename of each entry as a parameter to the block.
1752 * Dir.foreach("testdir") {|x| puts "Got #{x}" }
1754 * <em>produces:</em>
1756 * Got .
1757 * Got ..
1758 * Got config.h
1759 * Got main.rb
1762 static VALUE
1763 dir_foreach(int argc, VALUE *argv, VALUE io)
1765 VALUE dir;
1767 RETURN_ENUMERATOR(io, argc, argv);
1768 dir = dir_open_dir(argc, argv);
1769 rb_ensure(dir_each, dir, dir_close, dir);
1770 return Qnil;
1774 * call-seq:
1775 * Dir.entries( dirname ) => array
1777 * Returns an array containing all of the filenames in the given
1778 * directory. Will raise a <code>SystemCallError</code> if the named
1779 * directory doesn't exist.
1781 * Dir.entries("testdir") #=> [".", "..", "config.h", "main.rb"]
1784 static VALUE
1785 dir_entries(int argc, VALUE *argv, VALUE io)
1787 VALUE dir;
1789 dir = dir_open_dir(argc, argv);
1790 return rb_ensure(rb_Array, dir, dir_close, dir);
1794 * call-seq:
1795 * File.fnmatch( pattern, path, [flags] ) => (true or false)
1796 * File.fnmatch?( pattern, path, [flags] ) => (true or false)
1798 * Returns true if <i>path</i> matches against <i>pattern</i> The
1799 * pattern is not a regular expression; instead it follows rules
1800 * similar to shell filename globbing. It may contain the following
1801 * metacharacters:
1803 * <code>*</code>:: Matches any file. Can be restricted by
1804 * other values in the glob. <code>*</code>
1805 * will match all files; <code>c*</code> will
1806 * match all files beginning with
1807 * <code>c</code>; <code>*c</code> will match
1808 * all files ending with <code>c</code>; and
1809 * <code>*c*</code> will match all files that
1810 * have <code>c</code> in them (including at
1811 * the beginning or end). Equivalent to
1812 * <code>/ .* /x</code> in regexp.
1813 * <code>**</code>:: Matches directories recursively or files
1814 * expansively.
1815 * <code>?</code>:: Matches any one character. Equivalent to
1816 * <code>/.{1}/</code> in regexp.
1817 * <code>[set]</code>:: Matches any one character in +set+.
1818 * Behaves exactly like character sets in
1819 * Regexp, including set negation
1820 * (<code>[^a-z]</code>).
1821 * <code>\</code>:: Escapes the next metacharacter.
1823 * <i>flags</i> is a bitwise OR of the <code>FNM_xxx</code>
1824 * parameters. The same glob pattern and flags are used by
1825 * <code>Dir::glob</code>.
1827 * File.fnmatch('cat', 'cat') #=> true # match entire string
1828 * File.fnmatch('cat', 'category') #=> false # only match partial string
1829 * File.fnmatch('c{at,ub}s', 'cats') #=> false # { } isn't supported
1831 * File.fnmatch('c?t', 'cat') #=> true # '?' match only 1 character
1832 * File.fnmatch('c??t', 'cat') #=> false # ditto
1833 * File.fnmatch('c*', 'cats') #=> true # '*' match 0 or more characters
1834 * File.fnmatch('c*t', 'c/a/b/t') #=> true # ditto
1835 * File.fnmatch('ca[a-z]', 'cat') #=> true # inclusive bracket expression
1836 * File.fnmatch('ca[^t]', 'cat') #=> false # exclusive bracket expression ('^' or '!')
1838 * File.fnmatch('cat', 'CAT') #=> false # case sensitive
1839 * File.fnmatch('cat', 'CAT', File::FNM_CASEFOLD) #=> true # case insensitive
1841 * File.fnmatch('?', '/', File::FNM_PATHNAME) #=> false # wildcard doesn't match '/' on FNM_PATHNAME
1842 * File.fnmatch('*', '/', File::FNM_PATHNAME) #=> false # ditto
1843 * File.fnmatch('[/]', '/', File::FNM_PATHNAME) #=> false # ditto
1845 * File.fnmatch('\?', '?') #=> true # escaped wildcard becomes ordinary
1846 * File.fnmatch('\a', 'a') #=> true # escaped ordinary remains ordinary
1847 * File.fnmatch('\a', '\a', File::FNM_NOESCAPE) #=> true # FNM_NOESACPE makes '\' ordinary
1848 * File.fnmatch('[\?]', '?') #=> true # can escape inside bracket expression
1850 * File.fnmatch('*', '.profile') #=> false # wildcard doesn't match leading
1851 * File.fnmatch('*', '.profile', File::FNM_DOTMATCH) #=> true # period by default.
1852 * File.fnmatch('.*', '.profile') #=> true
1854 * rbfiles = '**' '/' '*.rb' # you don't have to do like this. just write in single string.
1855 * File.fnmatch(rbfiles, 'main.rb') #=> false
1856 * File.fnmatch(rbfiles, './main.rb') #=> false
1857 * File.fnmatch(rbfiles, 'lib/song.rb') #=> true
1858 * File.fnmatch('**.rb', 'main.rb') #=> true
1859 * File.fnmatch('**.rb', './main.rb') #=> false
1860 * File.fnmatch('**.rb', 'lib/song.rb') #=> true
1861 * File.fnmatch('*', 'dave/.profile') #=> true
1863 * pattern = '*' '/' '*'
1864 * File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME) #=> false
1865 * File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true
1867 * pattern = '**' '/' 'foo'
1868 * File.fnmatch(pattern, 'a/b/c/foo', File::FNM_PATHNAME) #=> true
1869 * File.fnmatch(pattern, '/a/b/c/foo', File::FNM_PATHNAME) #=> true
1870 * File.fnmatch(pattern, 'c:/a/b/c/foo', File::FNM_PATHNAME) #=> true
1871 * File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME) #=> false
1872 * File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true
1874 static VALUE
1875 file_s_fnmatch(int argc, VALUE *argv, VALUE obj)
1877 VALUE pattern, path;
1878 VALUE rflags;
1879 int flags;
1881 if (rb_scan_args(argc, argv, "21", &pattern, &path, &rflags) == 3)
1882 flags = NUM2INT(rflags);
1883 else
1884 flags = 0;
1886 StringValue(pattern);
1887 FilePathStringValue(path);
1889 if (fnmatch(RSTRING_PTR(pattern), rb_enc_get(pattern), RSTRING_PTR(path),
1890 flags) == 0)
1891 return Qtrue;
1893 return Qfalse;
1897 * Objects of class <code>Dir</code> are directory streams representing
1898 * directories in the underlying file system. They provide a variety of
1899 * ways to list directories and their contents. See also
1900 * <code>File</code>.
1902 * The directory used in these examples contains the two regular files
1903 * (<code>config.h</code> and <code>main.rb</code>), the parent
1904 * directory (<code>..</code>), and the directory itself
1905 * (<code>.</code>).
1907 void
1908 Init_Dir(void)
1910 rb_cDir = rb_define_class("Dir", rb_cObject);
1912 rb_include_module(rb_cDir, rb_mEnumerable);
1914 rb_define_alloc_func(rb_cDir, dir_s_alloc);
1915 rb_define_singleton_method(rb_cDir, "open", dir_s_open, -1);
1916 rb_define_singleton_method(rb_cDir, "foreach", dir_foreach, -1);
1917 rb_define_singleton_method(rb_cDir, "entries", dir_entries, -1);
1919 rb_define_method(rb_cDir,"initialize", dir_initialize, -1);
1920 rb_define_method(rb_cDir,"path", dir_path, 0);
1921 rb_define_method(rb_cDir,"inspect", dir_inspect, 0);
1922 rb_define_method(rb_cDir,"read", dir_read, 0);
1923 rb_define_method(rb_cDir,"each", dir_each, 0);
1924 rb_define_method(rb_cDir,"rewind", dir_rewind, 0);
1925 rb_define_method(rb_cDir,"tell", dir_tell, 0);
1926 rb_define_method(rb_cDir,"seek", dir_seek, 1);
1927 rb_define_method(rb_cDir,"pos", dir_tell, 0);
1928 rb_define_method(rb_cDir,"pos=", dir_set_pos, 1);
1929 rb_define_method(rb_cDir,"close", dir_close, 0);
1931 rb_define_singleton_method(rb_cDir,"chdir", dir_s_chdir, -1);
1932 rb_define_singleton_method(rb_cDir,"getwd", dir_s_getwd, 0);
1933 rb_define_singleton_method(rb_cDir,"pwd", dir_s_getwd, 0);
1934 rb_define_singleton_method(rb_cDir,"chroot", dir_s_chroot, 1);
1935 rb_define_singleton_method(rb_cDir,"mkdir", dir_s_mkdir, -1);
1936 rb_define_singleton_method(rb_cDir,"rmdir", dir_s_rmdir, 1);
1937 rb_define_singleton_method(rb_cDir,"delete", dir_s_rmdir, 1);
1938 rb_define_singleton_method(rb_cDir,"unlink", dir_s_rmdir, 1);
1940 rb_define_singleton_method(rb_cDir,"glob", dir_s_glob, -1);
1941 rb_define_singleton_method(rb_cDir,"[]", dir_s_aref, -1);
1942 rb_define_singleton_method(rb_cDir,"exist?", rb_file_directory_p, 1); /* in file.c */
1943 rb_define_singleton_method(rb_cDir,"exists?", rb_file_directory_p, 1); /* in file.c */
1945 rb_define_singleton_method(rb_cFile,"fnmatch", file_s_fnmatch, -1);
1946 rb_define_singleton_method(rb_cFile,"fnmatch?", file_s_fnmatch, -1);
1948 rb_file_const("FNM_NOESCAPE", INT2FIX(FNM_NOESCAPE));
1949 rb_file_const("FNM_PATHNAME", INT2FIX(FNM_PATHNAME));
1950 rb_file_const("FNM_DOTMATCH", INT2FIX(FNM_DOTMATCH));
1951 rb_file_const("FNM_CASEFOLD", INT2FIX(FNM_CASEFOLD));
1952 rb_file_const("FNM_SYSCASE", INT2FIX(FNM_SYSCASE));